BfModule.cpp 885 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928
  1. //#define USE_THUNKED_MddLLOC..
  2. #include "BeefySysLib/util/AllocDebug.h"
  3. #pragma warning(disable:4996)
  4. #pragma warning(push) // 6
  5. #include "BfCompiler.h"
  6. #include "BfSystem.h"
  7. #include "BfParser.h"
  8. #include "BfCodeGen.h"
  9. #include "BfExprEvaluator.h"
  10. #include "../Backend/BeLibManger.h"
  11. #include "BfConstResolver.h"
  12. #include "BfMangler.h"
  13. #include "BeefySysLib/util/PerfTimer.h"
  14. #include "BeefySysLib/util/BeefPerf.h"
  15. #include "BeefySysLib/util/StackHelper.h"
  16. #include "BfSourceClassifier.h"
  17. #include "BfAutoComplete.h"
  18. #include "BfDemangler.h"
  19. #include "BfResolvePass.h"
  20. #include "BfFixits.h"
  21. #include "BfIRCodeGen.h"
  22. #include "BfDefBuilder.h"
  23. #include "BfDeferEvalChecker.h"
  24. #include "CeMachine.h"
  25. #include "CeDebugger.h"
  26. #include <fcntl.h>
  27. #include <time.h>
  28. #pragma warning(pop)
  29. //////////////////////////////////////////////////////////////////////////
  30. static bool gDebugStuff = false;
  31. USING_NS_BF;
  32. //////////////////////////////////////////////////////////////////////////
  33. void BfLocalVariable::Init()
  34. {
  35. if (mResolvedType->IsValuelessType())
  36. {
  37. mAssignedKind = BfLocalVarAssignKind_Unconditional;
  38. return;
  39. }
  40. if (mAssignedKind != BfLocalVarAssignKind_None)
  41. return;
  42. bool isStruct = mResolvedType->IsStruct();
  43. if (mResolvedType->IsRef())
  44. isStruct = mResolvedType->GetUnderlyingType()->IsStruct();
  45. if ((isStruct) || ((mIsThis) && (mResolvedType->IsStructOrStructPtr())))
  46. {
  47. auto resolvedTypeRef = mResolvedType;
  48. if ((resolvedTypeRef->IsPointer()) || (resolvedTypeRef->IsRef()))
  49. resolvedTypeRef = resolvedTypeRef->GetUnderlyingType();
  50. auto typeInstance = resolvedTypeRef->ToTypeInstance();
  51. mUnassignedFieldFlags = (1 << typeInstance->mMergedFieldDataCount) - 1;
  52. if ((mIsThis) && (typeInstance->mBaseType != NULL))
  53. {
  54. // Base ctor is responsible for initializing its own fields
  55. mUnassignedFieldFlags &= ~(((int64)1 << typeInstance->mBaseType->mMergedFieldDataCount) - 1);
  56. }
  57. if (mUnassignedFieldFlags == 0)
  58. mAssignedKind = BfLocalVarAssignKind_Unconditional;
  59. }
  60. else
  61. {
  62. mUnassignedFieldFlags = 1;
  63. }
  64. }
  65. BfLocalMethod::~BfLocalMethod()
  66. {
  67. BfLogSys(mSystem, "~BfLocalMethod %p\n", this);
  68. if (mMethodDeclaration != NULL)
  69. {
  70. mSource->mRefCount--;
  71. BF_ASSERT(mSource->mRefCount >= 0);
  72. }
  73. delete mMethodInstanceGroup;
  74. delete mMethodDef;
  75. }
  76. void BfLocalMethod::Dispose()
  77. {
  78. if (mMethodInstanceGroup == NULL)
  79. return;
  80. if (mMethodInstanceGroup->mDefault != NULL)
  81. mMethodInstanceGroup->mDefault->Dispose();
  82. if (mMethodInstanceGroup->mMethodSpecializationMap != NULL)
  83. {
  84. for (auto& kv : *mMethodInstanceGroup->mMethodSpecializationMap)
  85. kv.mValue->Dispose();
  86. }
  87. }
  88. void BfDeferredLocalAssignData::ExtendFrom(BfDeferredLocalAssignData* outerLocalAssignData, bool doChain)
  89. {
  90. mIsChained = doChain;
  91. if (outerLocalAssignData == NULL)
  92. return;
  93. mChainedAssignData = outerLocalAssignData;
  94. if (!doChain)
  95. {
  96. outerLocalAssignData->BreakExtendChain();
  97. mAssignedLocals = outerLocalAssignData->mAssignedLocals;
  98. }
  99. mVarIdBarrier = outerLocalAssignData->mVarIdBarrier;
  100. }
  101. // The "extend chain" is broken when we have a conditional where the variable may not be defined after the block.
  102. // IE: "a" will be defined after the following, but "b" will not necessarily be defined.
  103. // if ((GetValue(out a)) && (GetValue(out b)) {}
  104. void BfDeferredLocalAssignData::BreakExtendChain()
  105. {
  106. if (!mIsChained)
  107. return;
  108. mIsChained = false;
  109. if (mChainedAssignData == NULL)
  110. return;
  111. mChainedAssignData->BreakExtendChain();
  112. mAssignedLocals = mChainedAssignData->mAssignedLocals;
  113. }
  114. void BfDeferredLocalAssignData::SetIntersection(const BfDeferredLocalAssignData& otherLocalAssignData)
  115. {
  116. BreakExtendChain();
  117. for (int i = 0; i < (int)mAssignedLocals.size(); )
  118. {
  119. auto& local = mAssignedLocals[i];
  120. bool wantRemove = true;
  121. bool foundOtherFields = false;
  122. for (auto& otherLocalAssignData : otherLocalAssignData.mAssignedLocals)
  123. {
  124. if (otherLocalAssignData.mLocalVar == local.mLocalVar)
  125. {
  126. if ((otherLocalAssignData.mLocalVarField == local.mLocalVarField) || (otherLocalAssignData.mLocalVarField == -1))
  127. {
  128. if (otherLocalAssignData.mAssignKind == BfLocalVarAssignKind_Conditional)
  129. local.mAssignKind = BfLocalVarAssignKind_Conditional;
  130. wantRemove = false;
  131. }
  132. else
  133. foundOtherFields = true;
  134. }
  135. }
  136. if ((wantRemove) && (foundOtherFields))
  137. {
  138. for (auto& otherLocalAssignData : otherLocalAssignData.mAssignedLocals)
  139. {
  140. if (otherLocalAssignData.mLocalVar == local.mLocalVar)
  141. {
  142. mAssignedLocals.Add(otherLocalAssignData);
  143. }
  144. }
  145. }
  146. if (wantRemove)
  147. {
  148. mAssignedLocals.RemoveAt(i);
  149. }
  150. else
  151. i++;
  152. }
  153. mHadFallthrough = mHadFallthrough && otherLocalAssignData.mHadFallthrough;
  154. }
  155. void BfDeferredLocalAssignData::Validate() const
  156. {
  157. for (auto var : mAssignedLocals)
  158. {
  159. BF_ASSERT((uintptr)var.mLocalVar->mName.length() < 100000);
  160. }
  161. }
  162. void BfDeferredLocalAssignData::SetUnion(const BfDeferredLocalAssignData& otherLocalAssignData)
  163. {
  164. BreakExtendChain();
  165. Validate();
  166. otherLocalAssignData.Validate();
  167. auto otherItr = otherLocalAssignData.mAssignedLocals.begin();
  168. while (otherItr != otherLocalAssignData.mAssignedLocals.end())
  169. {
  170. if (!mAssignedLocals.Contains(*otherItr))
  171. mAssignedLocals.push_back(*otherItr);
  172. ++otherItr;
  173. }
  174. mHadFallthrough = mHadFallthrough || otherLocalAssignData.mHadFallthrough;
  175. }
  176. BfMethodState::~BfMethodState()
  177. {
  178. BF_ASSERT(mPendingNullConditional == NULL);
  179. if (mPrevMethodState != NULL)
  180. {
  181. BF_ASSERT(mCurAccessId == 1);
  182. BF_ASSERT(mCurLocalVarId <= 0);
  183. }
  184. for (auto local : mLocals)
  185. {
  186. if (local->mIsBumpAlloc)
  187. local->~BfLocalVariable();
  188. else
  189. delete local;
  190. }
  191. for (auto& kv : mLambdaCache)
  192. delete kv.mValue;
  193. }
  194. BfMethodState* BfMethodState::GetMethodStateForLocal(BfLocalVariable* localVar)
  195. {
  196. auto checkMethodState = this;
  197. while (checkMethodState != NULL)
  198. {
  199. if ((localVar->mLocalVarIdx < checkMethodState->mLocals.size()) &&
  200. (checkMethodState->mLocals[localVar->mLocalVarIdx] == localVar))
  201. return checkMethodState;
  202. checkMethodState = checkMethodState->mPrevMethodState;
  203. }
  204. BF_FATAL("Failed to find method state for localvar");
  205. return NULL;
  206. }
  207. void BfMethodState::LocalDefined(BfLocalVariable* localVar, int fieldIdx, BfLocalVarAssignKind assignKind, bool isFromDeferredAssignData)
  208. {
  209. auto localVarMethodState = GetMethodStateForLocal(localVar);
  210. if (localVarMethodState != this)
  211. {
  212. return;
  213. }
  214. if (localVar->mAssignedKind == BfLocalVarAssignKind_None)
  215. {
  216. BfDeferredLocalAssignData* ifDeferredLocalAssignData = NULL;
  217. // 'a' is always defined, but 'b' isn't:
  218. // if (Check(out a) || Check(out b)) { } int z = a;
  219. auto deferredLocalAssignData = mDeferredLocalAssignData;
  220. if ((deferredLocalAssignData != NULL) &&
  221. (deferredLocalAssignData->mIsIfCondition) &&
  222. (!deferredLocalAssignData->mIfMayBeSkipped))
  223. {
  224. ifDeferredLocalAssignData = deferredLocalAssignData;
  225. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  226. }
  227. while ((deferredLocalAssignData != NULL) &&
  228. ((deferredLocalAssignData->mIsChained) || (deferredLocalAssignData->mIsUnconditional)))
  229. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  230. if (assignKind == BfLocalVarAssignKind_None)
  231. assignKind = ((deferredLocalAssignData != NULL) && (deferredLocalAssignData->mLeftBlock)) ? BfLocalVarAssignKind_Conditional : BfLocalVarAssignKind_Unconditional;
  232. if (localVar->mAssignedKind >= assignKind)
  233. {
  234. // Leave it alone
  235. }
  236. else if ((deferredLocalAssignData == NULL) || (localVar->mLocalVarId >= deferredLocalAssignData->mVarIdBarrier))
  237. {
  238. if (fieldIdx >= 0)
  239. {
  240. localVar->mUnassignedFieldFlags &= ~((int64)1 << fieldIdx);
  241. if (localVar->mUnassignedFieldFlags == 0)
  242. {
  243. if (localVar->mAssignedKind == BfLocalVarAssignKind_None)
  244. localVar->mAssignedKind = assignKind;
  245. }
  246. }
  247. else
  248. {
  249. localVar->mAssignedKind = assignKind;
  250. }
  251. }
  252. else
  253. {
  254. BF_ASSERT(deferredLocalAssignData->mVarIdBarrier != -1);
  255. BfAssignedLocal defineVal = {localVar, fieldIdx, assignKind};
  256. if (!deferredLocalAssignData->Contains(defineVal))
  257. deferredLocalAssignData->mAssignedLocals.push_back(defineVal);
  258. if (ifDeferredLocalAssignData != NULL)
  259. {
  260. if (!ifDeferredLocalAssignData->Contains(defineVal))
  261. ifDeferredLocalAssignData->mAssignedLocals.push_back(defineVal);
  262. }
  263. }
  264. }
  265. localVar->mWrittenToId = GetRootMethodState()->mCurAccessId++;
  266. }
  267. void BfMethodState::ApplyDeferredLocalAssignData(const BfDeferredLocalAssignData& deferredLocalAssignData)
  268. {
  269. BF_ASSERT(&deferredLocalAssignData != mDeferredLocalAssignData);
  270. for (auto& assignedLocal : deferredLocalAssignData.mAssignedLocals)
  271. {
  272. LocalDefined(assignedLocal.mLocalVar, assignedLocal.mLocalVarField, assignedLocal.mAssignKind, true);
  273. }
  274. }
  275. void BfMethodState::Reset()
  276. {
  277. mHeadScope.mDeferredCallEntries.DeleteAll();
  278. }
  279. //////////////////////////////////////////////////////////////////////////
  280. void BfAmbiguityContext::Add(int id, BfTypeInterfaceEntry* interfaceEntry, int methodIdx, BfMethodInstance* candidateA, BfMethodInstance* candidateB)
  281. {
  282. Entry* entry = NULL;
  283. if (mEntries.TryAdd(id, NULL, &entry))
  284. {
  285. entry->mInterfaceEntry = interfaceEntry;
  286. entry->mMethodIdx = methodIdx;
  287. }
  288. if (!entry->mCandidates.Contains(candidateA))
  289. entry->mCandidates.push_back(candidateA);
  290. if (!entry->mCandidates.Contains(candidateB))
  291. entry->mCandidates.push_back(candidateB);
  292. }
  293. void BfAmbiguityContext::Remove(int id)
  294. {
  295. mEntries.Remove(id);
  296. }
  297. void BfAmbiguityContext::Finish()
  298. {
  299. for (auto& entryPair : mEntries)
  300. {
  301. int id = entryPair.mKey;
  302. auto entry = &entryPair.mValue;
  303. if (id >= 0)
  304. {
  305. auto declMethodInstance = mTypeInstance->mVirtualMethodTable[id].mDeclaringMethod;
  306. auto error = mModule->Fail(StrFormat("Method '%s' has ambiguous overrides", mModule->MethodToString(declMethodInstance).c_str()), declMethodInstance->mMethodDef->GetRefNode());
  307. for (auto candidate : entry->mCandidates)
  308. {
  309. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", mModule->MethodToString(candidate).c_str()), candidate->mMethodDef->GetRefNode());
  310. }
  311. }
  312. else
  313. {
  314. auto iMethodInst = entry->mInterfaceEntry->mInterfaceType->mMethodInstanceGroups[entry->mMethodIdx].mDefault;
  315. auto error = mModule->Fail(StrFormat("Interface method '%s' has ambiguous implementations", mModule->MethodToString(iMethodInst).c_str()), entry->mInterfaceEntry->mDeclaringType->GetRefNode());
  316. for (auto candidate : entry->mCandidates)
  317. {
  318. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", mModule->MethodToString(candidate).c_str()), candidate->mMethodDef->GetRefNode());
  319. }
  320. }
  321. }
  322. }
  323. //////////////////////////////////////////////////////////////////////////
  324. class HasAppendAllocVisitor : BfElementVisitor
  325. {
  326. public:
  327. bool mHas;
  328. public:
  329. HasAppendAllocVisitor()
  330. {
  331. mHas = false;
  332. }
  333. void Visit(BfObjectCreateExpression* objCreateExpr)
  334. {
  335. if (auto newToken = BfNodeDynCast<BfTokenNode>(objCreateExpr->mNewNode))
  336. {
  337. if (newToken->GetToken() == BfToken_Append)
  338. {
  339. mHas = true;
  340. }
  341. }
  342. }
  343. bool HasAppendAlloc(BfAstNode* node)
  344. {
  345. mHas = false;
  346. VisitChild(node);
  347. return mHas;
  348. }
  349. };
  350. class AppendAllocVisitor : public BfStructuralVisitor
  351. {
  352. public:
  353. BfModule* mModule;
  354. HasAppendAllocVisitor mHasAppendAllocVisitor;
  355. BfTypedValue mConstAccum;
  356. bool mFailed;
  357. bool mIsFirstConstPass;
  358. int mCurAppendAlign;
  359. public:
  360. AppendAllocVisitor()
  361. {
  362. mFailed = false;
  363. mIsFirstConstPass = false;
  364. mCurAppendAlign = 1;
  365. }
  366. void EmitAppendAlign(int align, int sizeMultiple = 0)
  367. {
  368. BF_ASSERT(align > 0);
  369. if (mIsFirstConstPass)
  370. mModule->mCurMethodInstance->mAppendAllocAlign = BF_MAX((int)mModule->mCurMethodInstance->mAppendAllocAlign, align);
  371. if (sizeMultiple == 0)
  372. sizeMultiple = align;
  373. if (mCurAppendAlign == 0)
  374. mCurAppendAlign = sizeMultiple;
  375. else
  376. {
  377. if (sizeMultiple % align == 0)
  378. mCurAppendAlign = align;
  379. else
  380. mCurAppendAlign = sizeMultiple % align;
  381. }
  382. BF_ASSERT(mCurAppendAlign > 0);
  383. if (mConstAccum)
  384. {
  385. auto constant = mModule->mBfIRBuilder->GetConstant(mConstAccum.mValue);
  386. if (constant != NULL)
  387. mConstAccum.mValue = mModule->GetConstValue(BF_ALIGN(constant->mInt64, align));
  388. else
  389. BF_ASSERT(mIsFirstConstPass);
  390. return;
  391. }
  392. mModule->EmitAppendAlign(align, sizeMultiple);
  393. }
  394. void Visit(BfAstNode* astNode) override
  395. {
  396. mModule->VisitChild(astNode);
  397. }
  398. void DoObjectCreate(BfObjectCreateExpression* objCreateExpr, BfVariableDeclaration* variableDecl)
  399. {
  400. if (auto newToken = BfNodeDynCast<BfTokenNode>(objCreateExpr->mNewNode))
  401. {
  402. if (newToken->GetToken() == BfToken_Append)
  403. {
  404. //auto variableDecl = BfNodeDynCast<BfVariableDeclaration>(objCreateExpr->mParent);
  405. auto accumValuePtr = mModule->mCurMethodState->mRetVal.mValue;
  406. auto intPtrType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  407. BfArrayType* arrayType = NULL;
  408. bool isArrayAlloc = false;
  409. bool isRawArrayAlloc = objCreateExpr->mStarToken != NULL;
  410. SizedArray<BfIRValue, 2> dimLengthVals;
  411. BfType* origResolvedTypeRef = NULL;
  412. if (auto dotTypeRef = BfNodeDynCast<BfDotTypeReference>(objCreateExpr->mTypeRef))
  413. {
  414. if (variableDecl != NULL)
  415. {
  416. origResolvedTypeRef = mModule->ResolveTypeRef(variableDecl->mTypeRef, BfPopulateType_Data, BfResolveTypeRefFlag_NoResolveGenericParam);
  417. if (origResolvedTypeRef->IsObject())
  418. {
  419. if (origResolvedTypeRef->IsArray())
  420. {
  421. arrayType = (BfArrayType*)origResolvedTypeRef;
  422. origResolvedTypeRef = origResolvedTypeRef->GetUnderlyingType();
  423. isArrayAlloc = true;
  424. }
  425. }
  426. else if (origResolvedTypeRef->IsPointer())
  427. {
  428. origResolvedTypeRef = origResolvedTypeRef->GetUnderlyingType();
  429. }
  430. }
  431. }
  432. else if (auto arrayTypeRef = BfNodeDynCast<BfArrayTypeRef>(objCreateExpr->mTypeRef))
  433. {
  434. isArrayAlloc = true;
  435. bool handled = false;
  436. if (auto dotTypeRef = BfNodeDynCast<BfDotTypeReference>(arrayTypeRef->mElementType))
  437. {
  438. if (variableDecl->mTypeRef != NULL)
  439. {
  440. auto variableType = mModule->ResolveTypeRef(variableDecl->mTypeRef);
  441. if (variableType != NULL)
  442. {
  443. if (variableType->IsArray())
  444. origResolvedTypeRef = variableType->GetUnderlyingType();
  445. }
  446. handled = true;
  447. }
  448. }
  449. if (!handled)
  450. {
  451. origResolvedTypeRef = mModule->ResolveTypeRef(arrayTypeRef->mElementType);
  452. }
  453. if (origResolvedTypeRef == NULL)
  454. {
  455. mModule->AssertErrorState();
  456. return;
  457. }
  458. int dimensions = 1;
  459. if (arrayTypeRef->mParams.size() != 0)
  460. {
  461. auto intType = mModule->ResolveTypeDef(mModule->mSystem->mTypeIntPtr);
  462. for (auto arg : arrayTypeRef->mParams)
  463. {
  464. if (auto tokenNode = BfNodeDynCastExact<BfTokenNode>(arg))
  465. {
  466. if (tokenNode->GetToken() == BfToken_Comma)
  467. {
  468. if (isRawArrayAlloc)
  469. {
  470. mModule->Fail("Sized arrays cannot be multidimensional", tokenNode);
  471. continue;
  472. }
  473. dimensions++;
  474. continue;
  475. }
  476. }
  477. auto expr = BfNodeDynCast<BfExpression>(arg);
  478. if ((isRawArrayAlloc) && (!dimLengthVals.IsEmpty()))
  479. {
  480. mModule->CreateValueFromExpression(expr, intType);
  481. continue;
  482. }
  483. BfTypedValue dimLength;
  484. if (expr == NULL)
  485. {
  486. // Not specified
  487. dimLengthVals.push_back(BfIRValue());
  488. continue;
  489. }
  490. if (arg != NULL)
  491. dimLength = mModule->CreateValueFromExpression(expr, intType);
  492. if (!dimLength)
  493. {
  494. dimLength = mModule->GetDefaultTypedValue(intType);
  495. }
  496. dimLengthVals.push_back(dimLength.mValue);
  497. }
  498. }
  499. if (!isRawArrayAlloc)
  500. arrayType = mModule->CreateArrayType(origResolvedTypeRef, dimensions);
  501. }
  502. if (origResolvedTypeRef == NULL)
  503. origResolvedTypeRef = mModule->ResolveTypeRef(objCreateExpr->mTypeRef, BfPopulateType_Data, BfResolveTypeRefFlag_NoResolveGenericParam);
  504. if (origResolvedTypeRef == NULL)
  505. {
  506. mModule->AssertErrorState();
  507. return;
  508. }
  509. bool isGenericParam = origResolvedTypeRef->IsGenericParam();
  510. auto resolvedTypeRef = origResolvedTypeRef;
  511. auto resultType = resolvedTypeRef;
  512. BfIRValue sizeValue;
  513. int curAlign = 0;
  514. if (isArrayAlloc)
  515. {
  516. int dimensions = 1;
  517. if (arrayType != NULL)
  518. dimensions = arrayType->mDimensions;
  519. bool sizeFailed = false;
  520. //
  521. {
  522. BfAstNode* initNode = objCreateExpr;
  523. for (int dim = 0; dim < dimensions; dim++)
  524. {
  525. BfAstNode* nextInitNode = NULL;
  526. int dimSize = -1;
  527. if (initNode == objCreateExpr)
  528. {
  529. dimSize = objCreateExpr->mArguments.size();
  530. if (!objCreateExpr->mArguments.IsEmpty())
  531. nextInitNode = objCreateExpr->mArguments[0];
  532. }
  533. else if (auto tupleNode = BfNodeDynCast<BfTupleExpression>(initNode))
  534. {
  535. dimSize = (int)tupleNode->mCommas.size() + 1;
  536. }
  537. if (dimSize >= 0)
  538. {
  539. if (dim >= dimLengthVals.size())
  540. dimLengthVals.Add(mModule->GetConstValue(dimSize));
  541. }
  542. else
  543. {
  544. sizeFailed = true;
  545. }
  546. }
  547. }
  548. BfIRValue allocCount;
  549. if (!sizeFailed)
  550. {
  551. if (!dimLengthVals.IsEmpty())
  552. {
  553. allocCount = dimLengthVals[0];
  554. for (int dim = 1; dim < (int)dimLengthVals.size(); dim++)
  555. allocCount = mModule->mBfIRBuilder->CreateMul(allocCount, dimLengthVals[dim]);
  556. }
  557. }
  558. if (!allocCount)
  559. {
  560. mFailed = true;
  561. if (!mIsFirstConstPass)
  562. {
  563. if (!mConstAccum)
  564. mModule->Fail("Unable to determine append alloc size", objCreateExpr->mNewNode);
  565. return;
  566. }
  567. }
  568. mModule->PopulateType(resultType);
  569. if (isRawArrayAlloc)
  570. {
  571. curAlign = resultType->mAlign;
  572. EmitAppendAlign(resultType->mAlign);
  573. sizeValue = mModule->mBfIRBuilder->CreateMul(mModule->GetConstValue(resultType->GetStride()), allocCount);
  574. }
  575. else
  576. {
  577. if (arrayType == NULL)
  578. arrayType = mModule->CreateArrayType(resultType, 1);
  579. // Array is a special case where the total size isn't aligned with mAlign
  580. // since we add arbitrary elements to the end without padding the end to align
  581. EmitAppendAlign(arrayType->mAlign, resultType->mAlign);
  582. curAlign = arrayType->mAlign;
  583. auto firstElementField = &arrayType->mFieldInstances.back();
  584. int arrayClassSize = arrayType->mInstSize - firstElementField->mDataSize;
  585. sizeValue = mModule->GetConstValue(arrayClassSize);
  586. BfIRValue elementDataSize = mModule->mBfIRBuilder->CreateMul(mModule->GetConstValue(resultType->GetStride()), allocCount);
  587. sizeValue = mModule->mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  588. }
  589. }
  590. else
  591. {
  592. auto typeInst = resultType->ToTypeInstance();
  593. if (typeInst != NULL)
  594. {
  595. curAlign = typeInst->mInstAlign;
  596. EmitAppendAlign(typeInst->mInstAlign, typeInst->mInstSize);
  597. sizeValue = mModule->GetConstValue(typeInst->mInstSize);
  598. }
  599. else
  600. {
  601. curAlign = resultType->mAlign;
  602. EmitAppendAlign(resultType->mAlign, resultType->mSize);
  603. sizeValue = mModule->GetConstValue(resultType->mSize);
  604. }
  605. BfTypedValue emtpyThis(mModule->mBfIRBuilder->GetFakeVal(), resultType, (typeInst == NULL) || (typeInst->IsComposite()));
  606. BfExprEvaluator exprEvaluator(mModule);
  607. SetAndRestoreValue<bool> prevNoBind(exprEvaluator.mNoBind, exprEvaluator.mNoBind || isGenericParam);
  608. BfFunctionBindResult bindResult;
  609. bindResult.mWantsArgs = true;
  610. exprEvaluator.mFunctionBindResult = &bindResult;
  611. SizedArray<BfExpression*, 8> copiedArgs;
  612. for (BfExpression* arg : objCreateExpr->mArguments)
  613. copiedArgs.push_back(arg);
  614. BfSizedArray<BfExpression*> sizedArgExprs(copiedArgs);
  615. BfResolvedArgs argValues(&sizedArgExprs);
  616. if (typeInst != NULL)
  617. {
  618. exprEvaluator.ResolveArgValues(argValues);
  619. exprEvaluator.MatchConstructor(objCreateExpr->mTypeRef, objCreateExpr, emtpyThis, typeInst, argValues, false, true);
  620. }
  621. exprEvaluator.mFunctionBindResult = NULL;
  622. if (bindResult.mMethodInstance != NULL)
  623. {
  624. if (bindResult.mMethodInstance->mMethodDef->mHasAppend)
  625. {
  626. auto calcAppendArgs = bindResult.mIRArgs;
  627. BF_ASSERT(calcAppendArgs[0].IsFake());
  628. calcAppendArgs.RemoveRange(0, 2); // Remove 'this' and 'appendIdx'
  629. auto calcAppendMethodModule = mModule->GetMethodInstanceAtIdx(bindResult.mMethodInstance->GetOwner(), bindResult.mMethodInstance->mMethodDef->mIdx + 1, BF_METHODNAME_CALCAPPEND);
  630. auto subDependSize = mModule->TryConstCalcAppend(calcAppendMethodModule.mMethodInstance, calcAppendArgs);
  631. if (calcAppendMethodModule.mMethodInstance->mAppendAllocAlign > 0)
  632. {
  633. EmitAppendAlign(calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  634. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign > -1);
  635. mModule->mCurMethodState->mCurAppendAlign = BF_MAX(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign, 0);
  636. }
  637. curAlign = std::max(curAlign, (int)calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  638. if ((!subDependSize) && (!mConstAccum))
  639. {
  640. BF_ASSERT(calcAppendMethodModule.mFunc);
  641. subDependSize = exprEvaluator.CreateCall(objCreateExpr, calcAppendMethodModule.mMethodInstance, calcAppendMethodModule.mFunc, false, calcAppendArgs);
  642. BF_ASSERT(subDependSize.mType == mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  643. }
  644. if (subDependSize)
  645. sizeValue = mModule->mBfIRBuilder->CreateAdd(sizeValue, subDependSize.mValue);
  646. else
  647. mFailed = true;
  648. }
  649. }
  650. }
  651. if (sizeValue)
  652. {
  653. if (mConstAccum)
  654. {
  655. if (!sizeValue.IsConst())
  656. {
  657. mFailed = true;
  658. if (!mIsFirstConstPass)
  659. return;
  660. }
  661. mConstAccum.mValue = mModule->mBfIRBuilder->CreateAdd(sizeValue, mConstAccum.mValue);
  662. }
  663. else
  664. {
  665. auto prevVal = mModule->mBfIRBuilder->CreateAlignedLoad(accumValuePtr, intPtrType->mAlign);
  666. auto addedVal = mModule->mBfIRBuilder->CreateAdd(sizeValue, prevVal);
  667. mModule->mBfIRBuilder->CreateAlignedStore(addedVal, accumValuePtr, intPtrType->mAlign);
  668. }
  669. }
  670. }
  671. }
  672. }
  673. void Visit(BfObjectCreateExpression* objCreateExpr) override
  674. {
  675. DoObjectCreate(objCreateExpr, NULL);
  676. }
  677. void Visit(BfVariableDeclaration* varDecl) override
  678. {
  679. if (mHasAppendAllocVisitor.HasAppendAlloc(varDecl))
  680. {
  681. if (auto objectCreateExpr = BfNodeDynCast<BfObjectCreateExpression>(varDecl->mInitializer))
  682. DoObjectCreate(objectCreateExpr, varDecl);
  683. else
  684. VisitChild(varDecl->mInitializer);
  685. if (varDecl->mNameNode != NULL)
  686. {
  687. BfLocalVariable* localDef = new BfLocalVariable();
  688. localDef->mName = varDecl->mNameNode->ToString();
  689. localDef->mNameNode = BfNodeDynCast<BfIdentifierNode>(varDecl->mNameNode);
  690. localDef->mResolvedType = mModule->GetPrimitiveType(BfTypeCode_None);
  691. localDef->mIsReadOnly = true;
  692. localDef->mParamFailed = true;
  693. localDef->mReadFromId = 0;
  694. mModule->AddLocalVariableDef(localDef);
  695. }
  696. }
  697. else
  698. {
  699. mModule->Visit(varDecl);
  700. }
  701. }
  702. void Visit(BfExpressionStatement* exprStatement) override
  703. {
  704. VisitChild(exprStatement->mExpression);
  705. }
  706. // void Visit(BfIfStatement* ifStmt) override
  707. // {
  708. // mModule->DoIfStatement(ifStmt,
  709. // mHasAppendAllocVisitor.HasAppendAlloc(ifStmt->mTrueStatement),
  710. // mHasAppendAllocVisitor.HasAppendAlloc(ifStmt->mFalseStatement));
  711. // }
  712. void Visit(BfBlock* block) override
  713. {
  714. if (!mHasAppendAllocVisitor.HasAppendAlloc(block))
  715. return;
  716. int appendAllocIdx = -1;
  717. for (int childIdx = block->mChildArr.mSize - 1; childIdx >= 0; childIdx--)
  718. {
  719. auto child = block->mChildArr.mVals[childIdx];
  720. if (mHasAppendAllocVisitor.HasAppendAlloc(child))
  721. {
  722. for (int emitIdx = 0; emitIdx <= childIdx; emitIdx++)
  723. {
  724. auto emitChild = block->mChildArr.mVals[emitIdx];
  725. mModule->UpdateSrcPos(emitChild);
  726. VisitChild(emitChild);
  727. if ((mFailed) && (!mIsFirstConstPass))
  728. break;
  729. }
  730. break;
  731. }
  732. }
  733. }
  734. };
  735. //////////////////////////////////////////////////////////////////////////
  736. BfModule* gLastCreatedModule = NULL;
  737. BfModule::BfModule(BfContext* context, const StringImpl& moduleName)
  738. {
  739. BfLogSys(context->mSystem, "BfModule::BFModule %p %s\n", this, moduleName.c_str());
  740. gLastCreatedModule = this;
  741. mContext = context;
  742. mModuleName = moduleName;
  743. if (!moduleName.empty())
  744. {
  745. StringT<256> upperModuleName = moduleName;
  746. MakeUpper(upperModuleName);
  747. mContext->mUsedModuleNames.Add(upperModuleName);
  748. }
  749. mAddedToCount = false;
  750. mParentModule = NULL;
  751. mNextAltModule = NULL;
  752. mBfIRBuilder = NULL;
  753. mWantsIRIgnoreWrites = false;
  754. mModuleOptions = NULL;
  755. mLastUsedRevision = -1;
  756. mUsedSlotCount = -1;
  757. mIsReified = true;
  758. mGeneratesCode = true;
  759. mReifyQueued = false;
  760. mIsSpecialModule = false;
  761. mIsComptimeModule = false;
  762. mIsScratchModule = false;
  763. mIsSpecializedMethodModuleRoot = false; // There may be mNextAltModules extending from this
  764. mHadBuildError = false;
  765. mHadBuildWarning = false;
  766. mIgnoreErrors = false;
  767. mHadIgnoredError = false;
  768. mIgnoreWarnings = false;
  769. mReportErrors = true;
  770. mIsInsideAutoComplete = false;
  771. mIsDeleting = false;
  772. mSkipInnerLookup = false;
  773. mIsHotModule = false;
  774. mSetIllegalSrcPosition = false;
  775. mNoResolveGenericParams = false;
  776. mWroteToLib = false;
  777. mContext = context;
  778. mCompiler = context->mCompiler;
  779. mSystem = mCompiler->mSystem;
  780. mProject = NULL;
  781. mCurMethodState = NULL;
  782. mAttributeState = NULL;
  783. mCurLocalMethodId = 0;
  784. mParentNodeEntry = NULL;
  785. mRevision = -1;
  786. mRebuildIdx = 0;
  787. mLastModuleWrittenRevision = 0;
  788. mIsModuleMutable = false;
  789. mExtensionCount = 0;
  790. mIncompleteMethodCount = 0;
  791. mOnDemandMethodCount = 0;
  792. mHasGenericMethods = false;
  793. mCurMethodInstance = NULL;
  794. mCurTypeInstance = NULL;
  795. mAwaitingInitFinish = false;
  796. mAwaitingFinish = false;
  797. mHasFullDebugInfo = false;
  798. mHadHotObjectWrites = false;
  799. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  800. mBuiltInFuncs[i] = BfIRFunction();
  801. BfLogSysM("Creating module %p: %s Reified: %d ResolveOnly: %d\n", this, mModuleName.c_str(), mIsReified, mCompiler->mIsResolveOnly);
  802. }
  803. void BfReportMemory();
  804. BfModule::~BfModule()
  805. {
  806. mRevision = -2;
  807. BfLogSysM("Deleting module %p: %s \n", this, mModuleName.c_str());
  808. if (!mIsDeleting)
  809. RemoveModuleData();
  810. }
  811. void BfModule::RemoveModuleData()
  812. {
  813. BF_ASSERT(!mIsDeleting);
  814. if (!mModuleName.empty())
  815. {
  816. // Note: module names not necessarily unique
  817. mContext->mUsedModuleNames.Remove(ToUpper(mModuleName));
  818. }
  819. CleanupFileInstances();
  820. delete mBfIRBuilder;
  821. mBfIRBuilder = NULL;
  822. //delete mCpu;
  823. for (auto prevModule : mPrevIRBuilders)
  824. delete prevModule;
  825. mPrevIRBuilders.Clear();
  826. for (auto& pairVal : mDeferredMethodCallData)
  827. delete pairVal.mValue;
  828. mDeferredMethodCallData.Clear();
  829. mDeferredMethodIds.Clear();
  830. for (auto& specModulePair : mSpecializedMethodModules)
  831. delete specModulePair.mValue;
  832. mSpecializedMethodModules.Clear();
  833. if (mNextAltModule != NULL)
  834. delete mNextAltModule;
  835. mNextAltModule = NULL;
  836. if (mModuleOptions != NULL)
  837. delete mModuleOptions;
  838. mModuleOptions = NULL;
  839. BfReportMemory();
  840. }
  841. void BfModule::Init(bool isFullRebuild)
  842. {
  843. mContext->mFinishedModuleWorkList.Remove(this);
  844. if ((mCompiler->mIsResolveOnly) && (this != mContext->mUnreifiedModule))
  845. BF_ASSERT(mIsReified);
  846. if (!mIsScratchModule)
  847. {
  848. mCompiler->mStats.mModulesStarted++;
  849. if (mIsReified)
  850. mCompiler->mStats.mReifiedModuleCount++;
  851. mAddedToCount = true;
  852. }
  853. mIsHotModule = (mProject != NULL) && (mCompiler->mOptions.mHotProject != NULL) && (mCompiler->mOptions.mHotProject->ContainsReference(mProject));
  854. mFuncReferences.Clear();
  855. mClassVDataRefs.Clear();
  856. mClassVDataExtRefs.Clear();
  857. //mTypeDataRefs.Clear();
  858. mDbgRawAllocDataRefs.Clear();
  859. CleanupFileInstances();
  860. mStaticFieldRefs.Clear();
  861. //mInterfaceSlotRefs.Clear();
  862. // If we are just doing an extension then the ownede types aren't rebuilt.
  863. // If we set mRevision then QueueMethodSpecializations wouldn't actually queue up required specializations
  864. // and we'd end up with link errors if the original module uniquely referred to any generic methods
  865. if (isFullRebuild)
  866. mRevision = mCompiler->mRevision;
  867. BF_ASSERT(mCurTypeInstance == NULL);
  868. mIsModuleMutable = true;
  869. BF_ASSERT((mBfIRBuilder == NULL) || (mCompiler->mIsResolveOnly));
  870. if (!mIsComptimeModule)
  871. {
  872. #ifdef _DEBUG
  873. EnsureIRBuilder(mCompiler->mLastAutocompleteModule == this);
  874. #else
  875. EnsureIRBuilder(false);
  876. #endif
  877. }
  878. mCurMethodState = NULL;
  879. mAwaitingInitFinish = true;
  880. mOnDemandMethodCount = 0;
  881. mAwaitingFinish = false;
  882. mHasForceLinkMarker = false;
  883. mUsedSlotCount = -1;
  884. }
  885. bool BfModule::WantsFinishModule()
  886. {
  887. return (mIncompleteMethodCount == 0) && (mOnDemandMethodCount == 0) && (!mHasGenericMethods) && (!mIsScratchModule) && (mExtensionCount == 0) && (mParentModule == NULL);
  888. }
  889. bool BfModule::IsHotCompile()
  890. {
  891. return mCompiler->IsHotCompile() && !mIsComptimeModule;
  892. }
  893. void BfModule::FinishInit()
  894. {
  895. BF_ASSERT(mAwaitingInitFinish);
  896. auto moduleOptions = GetModuleOptions();
  897. mBfIRBuilder->Start(mModuleName, mCompiler->mSystem->mPtrSize, IsOptimized());
  898. mBfIRBuilder->Module_SetTargetTriple(mCompiler->mOptions.mTargetTriple, mCompiler->mOptions.mTargetCPU);
  899. mBfIRBuilder->SetBackend(IsTargetingBeefBackend());
  900. if (moduleOptions.mOptLevel == BfOptLevel_OgPlus)
  901. {
  902. // Og+ requires debug info
  903. moduleOptions.mEmitDebugInfo = 1;
  904. }
  905. mHasFullDebugInfo = moduleOptions.mEmitDebugInfo == 1;
  906. if (mIsComptimeModule)
  907. mHasFullDebugInfo = true;
  908. if (((!mCompiler->mIsResolveOnly) && (!mIsScratchModule) && (moduleOptions.mEmitDebugInfo != 0) && (mIsReified)) ||
  909. (mIsComptimeModule))
  910. {
  911. mBfIRBuilder->DbgInit();
  912. }
  913. else
  914. mHasFullDebugInfo = false;
  915. if ((mBfIRBuilder->DbgHasInfo()) && (mModuleName != "") &&
  916. ((moduleOptions.mEmitDebugInfo != 0)))
  917. {
  918. if (mCompiler->mOptions.IsCodeView())
  919. {
  920. mBfIRBuilder->Module_AddModuleFlag("CodeView", 1);
  921. }
  922. else
  923. {
  924. mBfIRBuilder->Module_AddModuleFlag("Dwarf Version", 4);
  925. }
  926. mBfIRBuilder->Module_AddModuleFlag("Debug Info Version", 3);
  927. mDICompileUnit = mBfIRBuilder->DbgCreateCompileUnit(llvm::dwarf::DW_LANG_C_plus_plus, mModuleName, ".", "Beef Compiler 0.42.3", /*moduleOptions.mOptLevel > 0*/false, "", 0, !mHasFullDebugInfo);
  928. }
  929. mAwaitingInitFinish = false;
  930. }
  931. void BfModule::CalcGeneratesCode()
  932. {
  933. if ((!mIsReified) || (mIsScratchModule))
  934. {
  935. mGeneratesCode = false;
  936. return;
  937. }
  938. mGeneratesCode = false;
  939. for (auto typeInst : mOwnedTypeInstances)
  940. if (!typeInst->IsInterface())
  941. mGeneratesCode = true;
  942. }
  943. void BfModule::ReifyModule()
  944. {
  945. BF_ASSERT((mCompiler->mCompileState != BfCompiler::CompileState_Unreified) && (mCompiler->mCompileState != BfCompiler::CompileState_VData));
  946. BfLogSysM("ReifyModule %@ %s\n", this, mModuleName.c_str());
  947. BF_ASSERT((this != mContext->mScratchModule) && (this != mContext->mUnreifiedModule));
  948. mIsReified = true;
  949. CalcGeneratesCode();
  950. mReifyQueued = false;
  951. StartNewRevision(RebuildKind_SkipOnDemandTypes, true);
  952. mCompiler->mStats.mModulesReified++;
  953. }
  954. void BfModule::UnreifyModule()
  955. {
  956. BfLogSysM("UnreifyModule %p %s\n", this, mModuleName.c_str());
  957. BF_ASSERT((this != mContext->mScratchModule) && (this != mContext->mUnreifiedModule));
  958. mIsReified = false;
  959. CalcGeneratesCode();
  960. mReifyQueued = false;
  961. StartNewRevision(RebuildKind_None, true);
  962. mCompiler->mStats.mModulesUnreified++;
  963. }
  964. void BfModule::CleanupFileInstances()
  965. {
  966. for (auto& itr : mNamedFileInstanceMap)
  967. {
  968. BfLogSysM("FileInstance deleted: %p\n", itr.mValue);
  969. delete itr.mValue;
  970. }
  971. mCurFilePosition.mFileInstance = NULL;//
  972. mFileInstanceMap.Clear();
  973. mNamedFileInstanceMap.Clear();
  974. }
  975. void BfModule::Cleanup()
  976. {
  977. CleanupFileInstances();
  978. }
  979. void BfModule::PrepareForIRWriting(BfTypeInstance* typeInst)
  980. {
  981. if (HasCompiledOutput())
  982. {
  983. // It's possible that the target's code hasn't changed but we're requesting a new generic method specialization
  984. if ((!mIsModuleMutable) && (!typeInst->IsUnspecializedType()) && (!typeInst->mResolvingVarField))
  985. {
  986. StartExtension();
  987. }
  988. }
  989. else
  990. {
  991. EnsureIRBuilder();
  992. }
  993. }
  994. void BfModule::SetupIRBuilder(bool dbgVerifyCodeGen)
  995. {
  996. if (mIsScratchModule)
  997. {
  998. mBfIRBuilder->mIgnoreWrites = true;
  999. BF_ASSERT(!dbgVerifyCodeGen);
  1000. }
  1001. #ifdef _DEBUG
  1002. if (mCompiler->mIsResolveOnly)
  1003. {
  1004. // For "deep" verification testing
  1005. /*if (!mIsSpecialModule)
  1006. dbgVerifyCodeGen = true;*/
  1007. // We only want to turn this off on smaller builds for testing
  1008. mBfIRBuilder->mIgnoreWrites = true;
  1009. if (dbgVerifyCodeGen)
  1010. mBfIRBuilder->mIgnoreWrites = false;
  1011. if (!mBfIRBuilder->mIgnoreWrites)
  1012. {
  1013. // The only purpose of not ignoring writes is so we can verify the codegen one instruction at a time
  1014. mBfIRBuilder->mDbgVerifyCodeGen = true;
  1015. }
  1016. }
  1017. else if (!mGeneratesCode)
  1018. {
  1019. mBfIRBuilder->mIgnoreWrites = true;
  1020. }
  1021. else
  1022. {
  1023. // We almost always want this to be 'false' unless we need need to be able to inspect the generated LLVM
  1024. // code as we walk the AST
  1025. //mBfIRBuilder->mDbgVerifyCodeGen = true;
  1026. if (
  1027. (mModuleName == "-")
  1028. //|| (mModuleName == "BeefTest2_ClearColorValue")
  1029. //|| (mModuleName == "Tests_FuncRefs")
  1030. )
  1031. mBfIRBuilder->mDbgVerifyCodeGen = true;
  1032. // Just for testing!
  1033. //mBfIRBuilder->mIgnoreWrites = true;
  1034. }
  1035. #else
  1036. if (mCompiler->mIsResolveOnly)
  1037. {
  1038. // Always ignore writes in resolveOnly for release builds
  1039. mBfIRBuilder->mIgnoreWrites = true;
  1040. }
  1041. else
  1042. {
  1043. // Just for memory testing! This breaks everything.
  1044. //mBfIRBuilder->mIgnoreWrites = true;
  1045. // For "deep" verification testing
  1046. //mBfIRBuilder->mDbgVerifyCodeGen = true;
  1047. }
  1048. #endif
  1049. mWantsIRIgnoreWrites = mBfIRBuilder->mIgnoreWrites;
  1050. }
  1051. void BfModule::EnsureIRBuilder(bool dbgVerifyCodeGen)
  1052. {
  1053. BF_ASSERT(!mIsDeleting);
  1054. if (mBfIRBuilder == NULL)
  1055. {
  1056. if ((!mIsScratchModule) && (!mAddedToCount))
  1057. {
  1058. mCompiler->mStats.mModulesStarted++;
  1059. mAddedToCount = true;
  1060. }
  1061. BF_ASSERT(mStaticFieldRefs.GetCount() == 0);
  1062. /*if (mCompiler->mIsResolveOnly)
  1063. BF_ASSERT(mIsResolveOnly);*/
  1064. mBfIRBuilder = new BfIRBuilder(this);
  1065. BfLogSysM("Created mBfIRBuilder %p in %p %s Reified: %d\n", mBfIRBuilder, this, mModuleName.c_str(), mIsReified);
  1066. SetupIRBuilder(dbgVerifyCodeGen);
  1067. }
  1068. }
  1069. BfIRValue BfModule::CreateForceLinkMarker(BfModule* module, String* outName)
  1070. {
  1071. String name = "FORCELINKMOD_" + module->mModuleName;
  1072. if (outName != NULL)
  1073. *outName = name;
  1074. auto markerType = GetPrimitiveType(BfTypeCode_Int8);
  1075. return mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(markerType), true, BfIRLinkageType_External, (module == this) ? mBfIRBuilder->CreateConst(BfTypeCode_Int8, 0) : BfIRValue(), name);
  1076. }
  1077. void BfModule::StartNewRevision(RebuildKind rebuildKind, bool force)
  1078. {
  1079. BP_ZONE("BfModule::StartNewRevision");
  1080. // The project MAY be deleted because disabling a project can cause types to be deleted which
  1081. // causes other types rebuild BEFORE they get deleted, which is okay (though wasteful)
  1082. //BF_ASSERT((mProject == NULL) || (!mProject->mDisabled));
  1083. if (mCompiler->mCompileState == BfCompiler::CompileState_Cleanup)
  1084. {
  1085. // Cleaning up local methods may cause some necessary NewRevisions
  1086. force = true;
  1087. }
  1088. // Already on new revision?
  1089. if ((mRevision == mCompiler->mRevision) && (!force))
  1090. return;
  1091. mHadBuildError = false;
  1092. mHadBuildWarning = false;
  1093. mExtensionCount = 0;
  1094. mRevision = mCompiler->mRevision;
  1095. mRebuildIdx++;
  1096. ClearModuleData(!force);
  1097. // Clear this here, not in ClearModuleData, so we preserve those references even after writing out module
  1098. if (rebuildKind != BfModule::RebuildKind_None) // Leave string pool refs for when we need to use things like [LinkName("")] methods bofore re-reification
  1099. {
  1100. mStringPoolRefs.Clear();
  1101. mUnreifiedStringPoolRefs.Clear();
  1102. }
  1103. mDllImportEntries.Clear();
  1104. mImportFileNames.Clear();
  1105. for (auto& pairVal : mDeferredMethodCallData)
  1106. delete pairVal.mValue;
  1107. mDeferredMethodCallData.Clear();
  1108. mDeferredMethodIds.Clear();
  1109. mModuleRefs.Clear();
  1110. mOutFileNames.Clear();
  1111. mTypeDataRefs.Clear();
  1112. mInterfaceSlotRefs.Clear();
  1113. if (rebuildKind == BfModule::RebuildKind_None)
  1114. {
  1115. for (auto& specPair : mSpecializedMethodModules)
  1116. {
  1117. auto specModule = specPair.mValue;
  1118. if (specModule->mIsReified != mIsReified)
  1119. {
  1120. if (mIsReified)
  1121. specModule->ReifyModule();
  1122. else
  1123. specModule->UnreifyModule();
  1124. }
  1125. }
  1126. }
  1127. else
  1128. {
  1129. for (auto& specPair : mSpecializedMethodModules)
  1130. {
  1131. auto specModule = specPair.mValue;
  1132. BfLogSysM("Setting module mIsDeleting %p due to parent module starting a new revision\n", specModule);
  1133. // This module is no longer needed
  1134. specModule->RemoveModuleData();
  1135. specModule->mIsDeleting = true;
  1136. mContext->mDeletingModules.Add(specModule);
  1137. }
  1138. }
  1139. mSpecializedMethodModules.Clear();
  1140. delete mNextAltModule;
  1141. mNextAltModule = NULL;
  1142. BF_ASSERT(mModuleOptions == NULL);
  1143. BfLogSysM("Mod:%p StartNewRevision: %s Revision: %d\n", this, mModuleName.c_str(), mRevision);
  1144. bool needsTypePopulated = false;
  1145. int oldOnDemandCount = 0;
  1146. // We don't have to rebuild types in the unspecialized module because there is no
  1147. // data that's needed -- their method instances are all NULL and the module
  1148. // doesn't get included in the build
  1149. if (this != mContext->mScratchModule)
  1150. {
  1151. for (int typeIdx = 0; typeIdx < (int)mOwnedTypeInstances.size(); typeIdx++)
  1152. {
  1153. auto typeInst = mOwnedTypeInstances[typeIdx];
  1154. if (!typeInst->IsDeleting())
  1155. {
  1156. typeInst->mIsReified = mIsReified;
  1157. if (rebuildKind != BfModule::RebuildKind_None)
  1158. {
  1159. if (typeInst->IsOnDemand())
  1160. {
  1161. // Changing config should require on demand types to be recreated, but reifying a module shouldn't cause the type to be deleted
  1162. if (rebuildKind == BfModule::RebuildKind_All)
  1163. mContext->DeleteType(typeInst);
  1164. else
  1165. {
  1166. RebuildMethods(typeInst);
  1167. }
  1168. }
  1169. else
  1170. //TODO: Why weren't we placing specialzied in purgatory here originally? This caused failed types to stick around too long
  1171. mContext->RebuildType(typeInst, false, false, true);
  1172. //mContext->RebuildType(typeInst, false, false, false);
  1173. }
  1174. else
  1175. {
  1176. auto _HandleMethod = [&](BfMethodInstance* methodInstance)
  1177. {
  1178. if ((methodInstance != NULL) && (methodInstance->mDeclModule != NULL))
  1179. methodInstance->mDeclModule = this;
  1180. };
  1181. for (auto& methodGroup : typeInst->mMethodInstanceGroups)
  1182. {
  1183. if ((methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) ||
  1184. (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl) ||
  1185. (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference) ||
  1186. (methodGroup.mOnDemandKind == BfMethodOnDemandKind_InWorkList))
  1187. {
  1188. oldOnDemandCount++;
  1189. }
  1190. _HandleMethod(methodGroup.mDefault);
  1191. if (methodGroup.mMethodSpecializationMap != NULL)
  1192. for (auto& kv : *methodGroup.mMethodSpecializationMap)
  1193. _HandleMethod(kv.mValue);
  1194. }
  1195. }
  1196. if (typeInst->IsDeleting())
  1197. typeIdx--;
  1198. }
  1199. }
  1200. }
  1201. if (!mIsDeleting)
  1202. Init();
  1203. mOnDemandMethodCount += oldOnDemandCount;
  1204. VerifyOnDemandMethods();
  1205. }
  1206. void BfModule::StartExtension()
  1207. {
  1208. BF_ASSERT(!mIsModuleMutable);
  1209. BfLogSysM("Extension started of module %p\n", this);
  1210. mExtensionCount++;
  1211. if (mBfIRBuilder != NULL)
  1212. mPrevIRBuilders.push_back(mBfIRBuilder);
  1213. mBfIRBuilder = NULL;
  1214. mWantsIRIgnoreWrites = false;
  1215. mFuncReferences.Clear();
  1216. mClassVDataRefs.Clear();
  1217. mClassVDataExtRefs.Clear();
  1218. for (auto& kv : mTypeDataRefs)
  1219. kv.mValue = BfIRValue();
  1220. mDbgRawAllocDataRefs.Clear();
  1221. mStringCharPtrPool.Clear();
  1222. mStringObjectPool.Clear();
  1223. mStaticFieldRefs.Clear();
  1224. for (auto& kv : mInterfaceSlotRefs)
  1225. kv.mValue = BfIRValue();
  1226. for (auto& pairVal : mDeferredMethodCallData)
  1227. delete pairVal.mValue;
  1228. mDeferredMethodCallData.Clear();
  1229. mDeferredMethodIds.Clear();
  1230. DisownMethods();
  1231. BfLogSysM("Mod:%p StartExtension: %s\n", this, mModuleName.c_str());
  1232. bool wasAwaitingInitFinish = mAwaitingInitFinish;
  1233. int prevOnDemandMethodCount = mOnDemandMethodCount;
  1234. Init(false);
  1235. if (!wasAwaitingInitFinish)
  1236. FinishInit();
  1237. mOnDemandMethodCount = prevOnDemandMethodCount;
  1238. }
  1239. void BfModule::GetConstClassValueParam(BfIRValue classVData, SizedArrayImpl<BfIRValue>& typeValueParams)
  1240. {
  1241. auto hasObjectDebugFlags = mContext->mBfObjectType->mFieldInstances[0].mResolvedType->IsInteger();
  1242. BfIRValue vDataValue;
  1243. if (hasObjectDebugFlags)
  1244. vDataValue = mBfIRBuilder->CreatePtrToInt(classVData, BfTypeCode_IntPtr);
  1245. else
  1246. vDataValue = mBfIRBuilder->CreateBitCast(classVData, mBfIRBuilder->MapType(mContext->mBfClassVDataPtrType));
  1247. typeValueParams.push_back(vDataValue);
  1248. if (hasObjectDebugFlags)
  1249. {
  1250. auto primType = GetPrimitiveType(BfTypeCode_IntPtr);
  1251. typeValueParams.push_back(GetDefaultValue(primType));
  1252. }
  1253. }
  1254. BfIRValue BfModule::GetConstValue(int64 val)
  1255. {
  1256. return mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)val);
  1257. }
  1258. BfIRValue BfModule::GetConstValue(int64 val, BfType* type)
  1259. {
  1260. BfType* checkType = type;
  1261. if (type->IsTypedPrimitive())
  1262. {
  1263. checkType = type->GetUnderlyingType();
  1264. }
  1265. if (checkType->IsPrimitiveType())
  1266. {
  1267. auto primType = (BfPrimitiveType*)checkType;
  1268. if (checkType->IsFloat())
  1269. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (double)val);
  1270. else
  1271. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (uint64)val);
  1272. }
  1273. return BfIRValue();
  1274. }
  1275. BfIRValue BfModule::GetConstValue8(int val)
  1276. {
  1277. return mBfIRBuilder->CreateConst(BfTypeCode_Int8, (uint64)val);
  1278. }
  1279. BfIRValue BfModule::GetConstValue32(int32 val)
  1280. {
  1281. return mBfIRBuilder->CreateConst(BfTypeCode_Int32, (uint64)val);
  1282. }
  1283. BfIRValue BfModule::GetConstValue64(int64 val)
  1284. {
  1285. return mBfIRBuilder->CreateConst(BfTypeCode_Int64, (uint64)val);
  1286. }
  1287. BfIRValue BfModule::GetDefaultValue(BfType* type)
  1288. {
  1289. PopulateType(type, BfPopulateType_Data);
  1290. mBfIRBuilder->PopulateType(type, BfIRPopulateType_Declaration);
  1291. if (type->IsTypedPrimitive())
  1292. {
  1293. auto underlyingType = type->GetUnderlyingType();
  1294. if (underlyingType == NULL)
  1295. return mBfIRBuilder->CreateConst(BfTypeCode_Int64, 0);
  1296. return GetDefaultValue(type->GetUnderlyingType());
  1297. }
  1298. if (type->IsPointer() || type->IsObjectOrInterface() || type->IsGenericParam() || type->IsVar() || type->IsRef() || type->IsNull() ||
  1299. type->IsModifiedTypeType() || type->IsConcreteInterfaceType())
  1300. return mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(type));
  1301. if ((type->IsIntegral()) || (type->IsBoolean()))
  1302. {
  1303. auto primType = (BfPrimitiveType*)type;
  1304. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (uint64)0);
  1305. }
  1306. if (type->IsFloat())
  1307. {
  1308. auto primType = (BfPrimitiveType*)type;
  1309. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, 0.0);
  1310. }
  1311. return mBfIRBuilder->CreateConstAggZero(mBfIRBuilder->MapType(type));
  1312. }
  1313. BfTypedValue BfModule::GetFakeTypedValue(BfType* type)
  1314. {
  1315. // This is a conservative "IsValueless", since it's not an error to use a fakeVal even if we don't need one
  1316. if (type->mSize == 0)
  1317. return BfTypedValue(BfIRValue::sValueless, type);
  1318. else if (mBfIRBuilder != NULL)
  1319. return BfTypedValue(mBfIRBuilder->GetFakeVal(), type);
  1320. else
  1321. return BfTypedValue(BfIRValue(BfIRValueFlags_Value, -1), type);
  1322. }
  1323. BfTypedValue BfModule::GetDefaultTypedValue(BfType* type, bool allowRef, BfDefaultValueKind defaultValueKind)
  1324. {
  1325. if (type->IsVar())
  1326. return BfTypedValue(mBfIRBuilder->GetFakeVal(), type);
  1327. PopulateType(type, BfPopulateType_Data);
  1328. mBfIRBuilder->PopulateType(type, type->IsValueType() ? BfIRPopulateType_Full : BfIRPopulateType_Declaration);
  1329. if (defaultValueKind == BfDefaultValueKind_Undef)
  1330. {
  1331. return BfTypedValue(mBfIRBuilder->GetUndefConstValue(mBfIRBuilder->MapType(type)), type);
  1332. }
  1333. BfTypedValue typedValue;
  1334. if ((defaultValueKind != BfDefaultValueKind_Const) && (!type->IsValuelessType()))
  1335. {
  1336. if (type->IsRef())
  1337. {
  1338. BfRefType* refType = (BfRefType*)type;
  1339. BfType* underlyingType = refType->GetUnderlyingType();
  1340. typedValue = BfTypedValue(CreateAlloca(underlyingType), underlyingType, BfTypedValueKind_Addr);
  1341. }
  1342. else
  1343. {
  1344. typedValue = BfTypedValue(CreateAlloca(type), type, BfTypedValueKind_Addr);
  1345. }
  1346. if (!mBfIRBuilder->mIgnoreWrites)
  1347. {
  1348. mBfIRBuilder->CreateMemSet(typedValue.mValue, GetConstValue(0, GetPrimitiveType(BfTypeCode_Int8)),
  1349. GetConstValue(type->mSize), type->mAlign);
  1350. }
  1351. if ((defaultValueKind == BfDefaultValueKind_Value) && (!type->IsRef()))
  1352. typedValue = LoadValue(typedValue);
  1353. return typedValue;
  1354. }
  1355. if ((type->IsRef()) && (!allowRef))
  1356. {
  1357. BfRefType* refType = (BfRefType*)type;
  1358. BfType* underlyingType = refType->GetUnderlyingType();
  1359. if (underlyingType->IsValuelessType())
  1360. typedValue = BfTypedValue(mBfIRBuilder->GetFakeVal(), underlyingType, true);
  1361. else
  1362. typedValue = BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(type)), underlyingType, true);
  1363. }
  1364. else
  1365. {
  1366. typedValue = BfTypedValue(GetDefaultValue(type), type, (defaultValueKind == BfDefaultValueKind_Addr) ? BfTypedValueKind_Addr : BfTypedValueKind_Value);
  1367. }
  1368. return typedValue;
  1369. }
  1370. BfIRValue BfModule::CreateStringCharPtr(const StringImpl& str, int stringId, bool define)
  1371. {
  1372. String stringDataName = StrFormat("__bfStrData%d", stringId);
  1373. auto charType = GetPrimitiveType(BfTypeCode_Char8);
  1374. BfIRType irStrCharType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(charType), (int)str.length() + 1);
  1375. BfIRValue strConstant;
  1376. if (define)
  1377. {
  1378. strConstant = mBfIRBuilder->CreateConstString(str);
  1379. }
  1380. BfIRValue gv = mBfIRBuilder->CreateGlobalVariable(irStrCharType,
  1381. true, BfIRLinkageType_External,
  1382. strConstant, stringDataName);
  1383. if (define)
  1384. mBfIRBuilder->GlobalVar_SetUnnamedAddr(gv, true);
  1385. return mBfIRBuilder->CreateInBoundsGEP(gv, 0, 0);
  1386. }
  1387. void BfModule::FixConstValueParams(BfTypeInstance* typeInst, SizedArrayImpl<BfIRValue>& valueParams, bool fillInPadding)
  1388. {
  1389. if ((!typeInst->mTypeDef->mIsCombinedPartial) && (!fillInPadding))
  1390. return;
  1391. int prevDataIdx = -1;
  1392. int usedDataIdx = 0;
  1393. int valueParamIdx = 0;
  1394. if (typeInst->mBaseType != NULL)
  1395. {
  1396. usedDataIdx++;
  1397. valueParamIdx++;
  1398. prevDataIdx++;
  1399. }
  1400. int startingParamsSize = (int)valueParams.mSize;
  1401. for (int fieldIdx = 0; fieldIdx < (int)typeInst->mFieldInstances.size(); fieldIdx++)
  1402. {
  1403. auto fieldInstance = &typeInst->mFieldInstances[fieldIdx];
  1404. if (fieldInstance->mDataIdx < 0)
  1405. continue;
  1406. BF_ASSERT(fieldInstance->mDataIdx > prevDataIdx);
  1407. if (fillInPadding)
  1408. {
  1409. for (int i = prevDataIdx + 1; i < fieldInstance->mDataIdx; i++)
  1410. valueParams.Insert(valueParamIdx++, mBfIRBuilder->CreateConstArrayZero(0));
  1411. }
  1412. valueParamIdx++;
  1413. prevDataIdx = fieldInstance->mDataIdx;
  1414. usedDataIdx++;
  1415. if (usedDataIdx <= valueParams.mSize)
  1416. continue;
  1417. valueParams.Add(GetDefaultValue(fieldInstance->mResolvedType));
  1418. }
  1419. }
  1420. BfIRValue BfModule::CreateStringObjectValue(const StringImpl& str, int stringId, bool define)
  1421. {
  1422. auto stringTypeInst = ResolveTypeDef(mCompiler->mStringTypeDef, define ? BfPopulateType_Data : BfPopulateType_Declaration)->ToTypeInstance();
  1423. mBfIRBuilder->PopulateType(stringTypeInst);
  1424. auto classVDataGlobal = CreateClassVDataGlobal(stringTypeInst);
  1425. String stringObjName = StrFormat("__bfStrObj%d", stringId);
  1426. BfIRValue stringValData;
  1427. if (define)
  1428. {
  1429. BfIRValue stringCharsVal = CreateStringCharPtr(str, stringId, define);
  1430. mStringCharPtrPool[stringId] = stringCharsVal;
  1431. SizedArray<BfIRValue, 8> typeValueParams;
  1432. GetConstClassValueParam(classVDataGlobal, typeValueParams);
  1433. FixConstValueParams(stringTypeInst->mBaseType, typeValueParams);
  1434. auto objData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(stringTypeInst->mBaseType, BfIRPopulateType_Full), typeValueParams);
  1435. auto lenByteCount = stringTypeInst->mFieldInstances[0].mResolvedType->mSize;
  1436. typeValueParams.clear();
  1437. typeValueParams.push_back(objData);
  1438. if (lenByteCount == 4)
  1439. {
  1440. typeValueParams.push_back(GetConstValue32((int)str.length())); // mLength
  1441. typeValueParams.push_back(GetConstValue32((int32)(0x40000000 + str.length() + 1))); // mAllocSizeAndFlags
  1442. }
  1443. else
  1444. {
  1445. typeValueParams.push_back(GetConstValue64(str.length())); // mLength
  1446. typeValueParams.push_back(GetConstValue64(0x4000000000000000LL + str.length() + 1)); // mAllocSizeAndFlags
  1447. }
  1448. typeValueParams.push_back(stringCharsVal); // mPtr
  1449. FixConstValueParams(stringTypeInst, typeValueParams);
  1450. stringValData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(stringTypeInst, BfIRPopulateType_Full), typeValueParams);
  1451. }
  1452. mBfIRBuilder->PopulateType(stringTypeInst);
  1453. auto stringValLiteral = mBfIRBuilder->CreateGlobalVariable(
  1454. mBfIRBuilder->MapTypeInst(stringTypeInst, BfIRPopulateType_Full),
  1455. true,
  1456. BfIRLinkageType_External,
  1457. define ? stringValData : BfIRValue(),
  1458. stringObjName);
  1459. return stringValLiteral;
  1460. }
  1461. int BfModule::GetStringPoolIdx(BfIRValue constantStr, BfIRConstHolder* constHolder)
  1462. {
  1463. BF_ASSERT(constantStr.IsConst());
  1464. if (constHolder == NULL)
  1465. constHolder = mBfIRBuilder;
  1466. auto constant = constHolder->GetConstant(constantStr);
  1467. if (constant->mTypeCode == BfTypeCode_StringId)
  1468. {
  1469. return constant->mInt32;
  1470. }
  1471. while (constant->mConstType == BfConstType_BitCast)
  1472. {
  1473. auto constBitCast = (BfConstantBitCast*)constant;
  1474. constant = constHolder->GetConstantById(constBitCast->mTarget);
  1475. }
  1476. if (constant->mConstType == BfConstType_GEP32_2)
  1477. {
  1478. auto constGEP = (BfConstantGEP32_2*)constant;
  1479. constant = constHolder->GetConstantById(constGEP->mTarget);
  1480. }
  1481. if (constant->mConstType == BfConstType_GlobalVar)
  1482. {
  1483. auto constGV = (BfGlobalVar*)constant;
  1484. const char* strDataPrefix = "__bfStrData";
  1485. if (strncmp(constGV->mName, strDataPrefix, strlen(strDataPrefix)) == 0)
  1486. return atoi(constGV->mName + strlen(strDataPrefix));
  1487. const char* strObjPrefix = "__bfStrObj";
  1488. if (strncmp(constGV->mName, strObjPrefix, strlen(strObjPrefix)) == 0)
  1489. return atoi(constGV->mName + strlen(strObjPrefix));
  1490. }
  1491. return -1;
  1492. }
  1493. String* BfModule::GetStringPoolString(BfIRValue constantStr, BfIRConstHolder * constHolder)
  1494. {
  1495. int strId = GetStringPoolIdx(constantStr, constHolder);
  1496. if (strId != -1)
  1497. {
  1498. auto& entry = mContext->mStringObjectIdMap[strId];
  1499. return &entry.mString;
  1500. }
  1501. return NULL;
  1502. }
  1503. CeDbgState* BfModule::GetCeDbgState()
  1504. {
  1505. if (!mIsComptimeModule)
  1506. return NULL;
  1507. if ((mCompiler->mCeMachine != NULL) && (mCompiler->mCeMachine->mDebugger != NULL))
  1508. return mCompiler->mCeMachine->mDebugger->mCurDbgState;
  1509. return NULL;
  1510. }
  1511. BfIRValue BfModule::GetStringCharPtr(int stringId, bool force)
  1512. {
  1513. if ((mBfIRBuilder->mIgnoreWrites) && (!force))
  1514. {
  1515. mUnreifiedStringPoolRefs.Add(stringId);
  1516. return mBfIRBuilder->CreateConst(BfTypeCode_StringId, stringId);
  1517. }
  1518. BfIRValue* irValue = NULL;
  1519. if (!mStringCharPtrPool.TryAdd(stringId, NULL, &irValue))
  1520. return *irValue;
  1521. // If this wasn't in neither dictionary yet, add to mStringPoolRefs
  1522. if (!mStringObjectPool.ContainsKey(stringId))
  1523. mStringPoolRefs.Add(stringId);
  1524. const StringImpl& str = mContext->mStringObjectIdMap[stringId].mString;
  1525. BfIRValue strCharPtrConst = CreateStringCharPtr(str, stringId, false);
  1526. *irValue = strCharPtrConst;
  1527. return strCharPtrConst;
  1528. }
  1529. BfIRValue BfModule::GetStringCharPtr(BfIRValue strValue, bool force)
  1530. {
  1531. if (strValue.IsConst())
  1532. {
  1533. int stringId = GetStringPoolIdx(strValue);
  1534. BF_ASSERT(stringId != -1);
  1535. return GetStringCharPtr(stringId, force);
  1536. }
  1537. BfIRValue charPtrPtr = mBfIRBuilder->CreateInBoundsGEP(strValue, 0, 1);
  1538. BfIRValue charPtr = mBfIRBuilder->CreateLoad(charPtrPtr);
  1539. return charPtr;
  1540. }
  1541. BfIRValue BfModule::GetStringCharPtr(const StringImpl& str, bool force)
  1542. {
  1543. return GetStringCharPtr(GetStringObjectValue(str, force), force);
  1544. }
  1545. BfIRValue BfModule::GetStringObjectValue(int strId, bool define, bool force)
  1546. {
  1547. BfIRValue* objValue;
  1548. if (mStringObjectPool.TryGetValue(strId, &objValue))
  1549. return *objValue;
  1550. auto stringPoolEntry = mContext->mStringObjectIdMap[strId];
  1551. return GetStringObjectValue(stringPoolEntry.mString, define, force);
  1552. }
  1553. BfIRValue BfModule::GetStringObjectValue(const StringImpl& str, bool define, bool force)
  1554. {
  1555. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef, define ? BfPopulateType_Data : BfPopulateType_Declaration);
  1556. mBfIRBuilder->PopulateType(stringType);
  1557. int strId = mContext->GetStringLiteralId(str);
  1558. if ((mBfIRBuilder->mIgnoreWrites) && (!force))
  1559. {
  1560. auto refModule = this;
  1561. if ((this == mContext->mUnreifiedModule) && (mCurTypeInstance != NULL))
  1562. refModule = mCurTypeInstance->mModule;
  1563. refModule->mUnreifiedStringPoolRefs.Add(strId);
  1564. return mBfIRBuilder->CreateConst(BfTypeCode_StringId, strId);
  1565. }
  1566. BfIRValue* irValuePtr = NULL;
  1567. if (mStringObjectPool.TryGetValue(strId, &irValuePtr))
  1568. return *irValuePtr;
  1569. // If this wasn't in neither dictionary yet, add to mStringPoolRefs
  1570. if (!mStringCharPtrPool.ContainsKey(strId))
  1571. mStringPoolRefs.Add(strId);
  1572. BfIRValue strObject = CreateStringObjectValue(str, strId, define);
  1573. mStringObjectPool[strId] = strObject;
  1574. mStringPoolRefs.Add(strId);
  1575. return strObject;
  1576. }
  1577. BfIRValue BfModule::CreateGlobalConstValue(const StringImpl& name, BfIRValue constant, BfIRType type, bool external)
  1578. {
  1579. auto newConst = mBfIRBuilder->CreateGlobalVariable(
  1580. type,
  1581. true,
  1582. external ? BfIRLinkageType_External : BfIRLinkageType_Internal,
  1583. constant,
  1584. name.c_str());
  1585. return newConst;
  1586. }
  1587. void BfModule::NewScopeState(bool createLexicalBlock, bool flushValueScope)
  1588. {
  1589. auto curScope = mCurMethodState->mCurScope;
  1590. if (curScope->mLabelNode != NULL)
  1591. {
  1592. curScope->mLabelNode->ToString(curScope->mLabel);
  1593. auto rootMethodState = mCurMethodState->GetRootMethodState();
  1594. curScope->mScopeLocalId = rootMethodState->mCurLocalVarId++;
  1595. auto autoComplete = mCompiler->GetAutoComplete();
  1596. if (autoComplete != NULL)
  1597. autoComplete->CheckLabel(curScope->mLabelNode, NULL, curScope);
  1598. }
  1599. if (!mCurMethodState->mCurScope->mLabel.IsEmpty())
  1600. {
  1601. auto checkScope = mCurMethodState->mCurScope->mPrevScope;
  1602. while (checkScope != NULL)
  1603. {
  1604. if (checkScope->mLabel == mCurMethodState->mCurScope->mLabel)
  1605. {
  1606. auto errorNode = Fail("Duplicate scope label", curScope->mLabelNode);
  1607. if (errorNode != NULL)
  1608. mCompiler->mPassInstance->MoreInfo("See previous scope label", checkScope->mLabelNode);
  1609. break;
  1610. }
  1611. checkScope = checkScope->mPrevScope;
  1612. }
  1613. }
  1614. auto prevScope = mCurMethodState->mCurScope->mPrevScope;
  1615. if ((flushValueScope) && (prevScope != NULL) && (prevScope->mValueScopeStart))
  1616. {
  1617. if (prevScope->mHadScopeValueRetain)
  1618. mBfIRBuilder->CreateValueScopeSoftEnd(prevScope->mValueScopeStart);
  1619. else
  1620. mBfIRBuilder->CreateValueScopeHardEnd(prevScope->mValueScopeStart);
  1621. }
  1622. mCurMethodState->mBlockNestLevel++;
  1623. if ((createLexicalBlock) && (mBfIRBuilder->DbgHasInfo()) && (mHasFullDebugInfo))
  1624. {
  1625. // DIScope could be NULL if we're in an unspecialized method (for example)
  1626. if (mCurMethodState->mCurScope->mDIScope)
  1627. mCurMethodState->mCurScope->mDIScope = mBfIRBuilder->DbgCreateLexicalBlock(mCurMethodState->mCurScope->mDIScope, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mCurFilePosition.mCurColumn);
  1628. }
  1629. mCurMethodState->mCurScope->mLocalVarStart = (int)mCurMethodState->mLocals.size();
  1630. mCurMethodState->mCurScope->mBlock = mBfIRBuilder->MaybeChainNewBlock((!mCurMethodState->mCurScope->mLabel.empty()) ? mCurMethodState->mCurScope->mLabel : "newScope");
  1631. mCurMethodState->mCurScope->mMixinState = mCurMethodState->mMixinState;
  1632. }
  1633. void BfModule::RestoreScoreState_LocalVariables()
  1634. {
  1635. while (mCurMethodState->mCurScope->mLocalVarStart < (int)mCurMethodState->mLocals.size())
  1636. {
  1637. auto localVar = mCurMethodState->mLocals.back();
  1638. LocalVariableDone(localVar, false);
  1639. mCurMethodState->mLocals.pop_back();
  1640. if (localVar->mShadowedLocal != NULL)
  1641. {
  1642. BfLocalVarEntry* localVarEntryPtr;
  1643. if (mCurMethodState->mLocalVarSet.TryGet(BfLocalVarEntry(localVar), &localVarEntryPtr))
  1644. {
  1645. localVarEntryPtr->mLocalVar = localVar->mShadowedLocal;
  1646. }
  1647. }
  1648. else
  1649. {
  1650. mCurMethodState->mLocalVarSet.Remove(BfLocalVarEntry(localVar));
  1651. }
  1652. if (localVar->mIsBumpAlloc)
  1653. localVar->~BfLocalVariable();
  1654. else
  1655. delete localVar;
  1656. }
  1657. }
  1658. void BfModule::RestoreScopeState()
  1659. {
  1660. BfScopeData* prevScopeData = mCurMethodState->mCurScope->mPrevScope;
  1661. mCurMethodState->mBlockNestLevel--;
  1662. if (!mCurMethodState->mCurScope->mAtEndBlocks.empty())
  1663. {
  1664. BfIRBlock afterEndBlock;
  1665. if (!mCurMethodState->mLeftBlockUncond)
  1666. {
  1667. afterEndBlock = mBfIRBuilder->CreateBlock("scopeAfterEnd");
  1668. mBfIRBuilder->CreateBr(afterEndBlock);
  1669. mBfIRBuilder->ClearDebugLocation_Last();
  1670. }
  1671. for (auto preExitBlock : mCurMethodState->mCurScope->mAtEndBlocks)
  1672. mBfIRBuilder->MoveBlockToEnd(preExitBlock);
  1673. if (afterEndBlock)
  1674. {
  1675. mBfIRBuilder->AddBlock(afterEndBlock);
  1676. mBfIRBuilder->SetInsertPoint(afterEndBlock);
  1677. }
  1678. }
  1679. if (!mCurMethodState->mLeftBlockUncond)
  1680. EmitDeferredScopeCalls(true, mCurMethodState->mCurScope);
  1681. RestoreScoreState_LocalVariables();
  1682. if (mCurMethodState->mCurScope->mValueScopeStart)
  1683. mBfIRBuilder->CreateValueScopeHardEnd(mCurMethodState->mCurScope->mValueScopeStart);
  1684. mCurMethodState->mCurScope = prevScopeData;
  1685. mCurMethodState->mTailScope = mCurMethodState->mCurScope;
  1686. }
  1687. BfIRValue BfModule::CreateAlloca(BfType* type, bool addLifetime, const char* name, BfIRValue arraySize)
  1688. {
  1689. if (mBfIRBuilder->mIgnoreWrites)
  1690. return mBfIRBuilder->GetFakeVal();
  1691. BF_ASSERT((*(int8*)&addLifetime == 1) || (*(int8*)&addLifetime == 0));
  1692. mBfIRBuilder->PopulateType(type);
  1693. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  1694. if (!mBfIRBuilder->mIgnoreWrites)
  1695. BF_ASSERT(!prevInsertBlock.IsFake());
  1696. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  1697. BfIRValue allocaInst;
  1698. if (arraySize)
  1699. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type), arraySize);
  1700. else
  1701. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type));
  1702. mBfIRBuilder->SetAllocaAlignment(allocaInst, type->mAlign);
  1703. mBfIRBuilder->ClearDebugLocation(allocaInst);
  1704. if (name != NULL)
  1705. mBfIRBuilder->SetName(allocaInst, name);
  1706. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  1707. if ((addLifetime) && (WantsLifetimes()))
  1708. {
  1709. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  1710. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  1711. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  1712. }
  1713. return allocaInst;
  1714. }
  1715. BfIRValue BfModule::CreateAllocaInst(BfTypeInstance* typeInst, bool addLifetime, const char* name)
  1716. {
  1717. if (mBfIRBuilder->mIgnoreWrites)
  1718. return mBfIRBuilder->GetFakeVal();
  1719. BF_ASSERT((*(int8*)&addLifetime == 1) || (*(int8*)&addLifetime == 0));
  1720. mBfIRBuilder->PopulateType(typeInst);
  1721. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  1722. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  1723. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapTypeInst(typeInst));
  1724. mBfIRBuilder->SetAllocaAlignment(allocaInst, typeInst->mInstAlign);
  1725. mBfIRBuilder->ClearDebugLocation(allocaInst);
  1726. if (name != NULL)
  1727. mBfIRBuilder->SetName(allocaInst, name);
  1728. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  1729. if ((addLifetime) && (WantsLifetimes()))
  1730. {
  1731. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  1732. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  1733. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  1734. }
  1735. return allocaInst;
  1736. }
  1737. BfDeferredCallEntry* BfModule::AddStackAlloc(BfTypedValue val, BfIRValue arraySize, BfAstNode* refNode, BfScopeData* scopeData, bool condAlloca, bool mayEscape, BfIRBlock valBlock)
  1738. {
  1739. //This was removed because we want the alloc to be added to the __deferred list if it's actually a "stack"
  1740. // 'stack' in a head scopeData is really the same as 'scopeData', so use the simpler scopeData handling
  1741. /*if (mCurMethodState->mInHeadScope)
  1742. isScopeAlloc = true;*/
  1743. if (scopeData == NULL)
  1744. return NULL;
  1745. auto checkBaseType = val.mType->ToTypeInstance();
  1746. if ((checkBaseType != NULL) && (checkBaseType->IsObject()) && (!arraySize))
  1747. {
  1748. bool hadDtorCall = false;
  1749. while (checkBaseType != NULL)
  1750. {
  1751. BfMethodDef* dtorMethodDef = checkBaseType->mTypeDef->GetMethodByName("~this");
  1752. if (dtorMethodDef != NULL)
  1753. {
  1754. auto dtorMethodInstance = GetMethodInstance(checkBaseType, dtorMethodDef, BfTypeVector());
  1755. if (dtorMethodInstance)
  1756. {
  1757. bool isDynAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsDyn(scopeData));
  1758. BfIRValue useVal = val.mValue;
  1759. BfIRBlock prevBlock = mBfIRBuilder->GetInsertBlock();
  1760. if (valBlock)
  1761. mBfIRBuilder->SetInsertPoint(valBlock);
  1762. useVal = mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapTypeInstPtr(checkBaseType));
  1763. if (!useVal.IsConst())
  1764. mBfIRBuilder->ClearDebugLocation(useVal);
  1765. if (valBlock)
  1766. mBfIRBuilder->SetInsertPoint(prevBlock);
  1767. if (isDynAlloc)
  1768. {
  1769. //
  1770. }
  1771. else if (condAlloca)
  1772. {
  1773. BF_ASSERT(!IsTargetingBeefBackend());
  1774. BF_ASSERT(!isDynAlloc);
  1775. auto valPtr = CreateAlloca(checkBaseType);
  1776. mBfIRBuilder->ClearDebugLocation_Last();
  1777. mBfIRBuilder->CreateAlignedStore(useVal, valPtr, checkBaseType->mAlign);
  1778. mBfIRBuilder->ClearDebugLocation_Last();
  1779. useVal = valPtr;
  1780. }
  1781. SizedArray<BfIRValue, 1> llvmArgs;
  1782. llvmArgs.push_back(useVal);
  1783. auto deferredCall = AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1784. if (deferredCall != NULL)
  1785. {
  1786. deferredCall->mCastThis = (val.mType != checkBaseType) && (!isDynAlloc);
  1787. if (condAlloca)
  1788. deferredCall->mArgsNeedLoad = true;
  1789. }
  1790. hadDtorCall = true;
  1791. break;
  1792. }
  1793. }
  1794. checkBaseType = checkBaseType->mBaseType;
  1795. }
  1796. return NULL;
  1797. }
  1798. //TODO: In the future we could be smarter about statically determining that our value hasn't escaped and eliding this
  1799. if (mayEscape)
  1800. {
  1801. if ((!IsOptimized()) && (!mIsComptimeModule) && (!val.mType->IsValuelessType()) && (!mBfIRBuilder->mIgnoreWrites) && (!mCompiler->mIsResolveOnly))
  1802. {
  1803. auto nullPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  1804. bool isDyn = mCurMethodState->mCurScope->IsDyn(scopeData);
  1805. if (!isDyn)
  1806. {
  1807. const char* methodName = arraySize ? "SetDeletedArray" : "SetDeleted";
  1808. BfModuleMethodInstance dtorMethodInstance = GetInternalMethod(methodName);
  1809. BF_ASSERT(dtorMethodInstance.mMethodInstance != NULL);
  1810. if (!dtorMethodInstance.mMethodInstance)
  1811. {
  1812. Fail(StrFormat("Unable to find %s", methodName));
  1813. }
  1814. else
  1815. {
  1816. SizedArray<BfIRValue, 1> llvmArgs;
  1817. if (IsTargetingBeefBackend())
  1818. {
  1819. llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(nullPtrType)));
  1820. //mBfIRBuilder->ClearDebugLocation_Last();
  1821. }
  1822. else
  1823. llvmArgs.push_back(val.mValue);
  1824. llvmArgs.push_back(GetConstValue(val.mType->mSize));
  1825. llvmArgs.push_back(GetConstValue32(val.mType->mAlign));
  1826. if (arraySize)
  1827. llvmArgs.push_back(arraySize);
  1828. return AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1829. }
  1830. }
  1831. else
  1832. {
  1833. if ((arraySize) && (!arraySize.IsConst()) && (val.mType->mSize < mSystem->mPtrSize))
  1834. {
  1835. BfIRValue clearSize = arraySize;
  1836. if (val.mType->GetStride() > 1)
  1837. clearSize = mBfIRBuilder->CreateMul(clearSize, GetConstValue(val.mType->GetStride()));
  1838. const char* methodName = "SetDeletedX";
  1839. BfModuleMethodInstance dtorMethodInstance = GetInternalMethod(methodName);
  1840. BF_ASSERT(dtorMethodInstance);
  1841. if (!dtorMethodInstance)
  1842. {
  1843. Fail(StrFormat("Unable to find %s", methodName));
  1844. }
  1845. else
  1846. {
  1847. SizedArray<BfIRValue, 1> llvmArgs;
  1848. llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(nullPtrType)));
  1849. //mBfIRBuilder->ClearDebugLocation_Last();
  1850. llvmArgs.push_back(clearSize);
  1851. return AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1852. }
  1853. }
  1854. else
  1855. {
  1856. intptr clearSize = val.mType->mSize;
  1857. auto constant = mBfIRBuilder->GetConstant(arraySize);
  1858. if (constant != NULL)
  1859. clearSize = (intptr)(clearSize * constant->mInt64);
  1860. const char* funcName = "SetDeleted1";
  1861. if (clearSize >= 16)
  1862. funcName = "SetDeleted16";
  1863. else if (clearSize >= 8)
  1864. funcName = "SetDeleted8";
  1865. else if (clearSize >= 4)
  1866. funcName = "SetDeleted4";
  1867. BfModuleMethodInstance dtorMethodInstance = GetInternalMethod(funcName);
  1868. BF_ASSERT(dtorMethodInstance.mMethodInstance != NULL);
  1869. if (!dtorMethodInstance)
  1870. {
  1871. Fail(StrFormat("Unable to find %s", funcName));
  1872. }
  1873. else
  1874. {
  1875. SizedArray<BfIRValue, 1> llvmArgs;
  1876. llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(nullPtrType)));
  1877. //mBfIRBuilder->ClearDebugLocation_Last();
  1878. return AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1879. }
  1880. }
  1881. }
  1882. }
  1883. }
  1884. return NULL;
  1885. }
  1886. bool BfModule::TryLocalVariableInit(BfLocalVariable* localVar)
  1887. {
  1888. auto startTypeInstance = localVar->mResolvedType->ToTypeInstance();
  1889. if ((startTypeInstance == NULL) || (!startTypeInstance->IsStruct()))
  1890. return false;
  1891. auto checkTypeInstance = startTypeInstance;
  1892. while (checkTypeInstance != NULL)
  1893. {
  1894. for (auto& fieldInstance : checkTypeInstance->mFieldInstances)
  1895. {
  1896. if (fieldInstance.mMergedDataIdx != -1)
  1897. {
  1898. int64 checkMask = (int64)1 << fieldInstance.mMergedDataIdx;
  1899. if ((localVar->mUnassignedFieldFlags & checkMask) != 0)
  1900. {
  1901. // For fields added in extensions, we automatically initialize those if necessary
  1902. auto fieldDef = fieldInstance.GetFieldDef();
  1903. if (!fieldDef->mDeclaringType->IsExtension())
  1904. return false;
  1905. if ((fieldInstance.mDataIdx != -1) && (!mBfIRBuilder->mIgnoreWrites) && (!mCompiler->mIsResolveOnly) && (!mIsComptimeModule))
  1906. {
  1907. auto curInsertBlock = mBfIRBuilder->GetInsertBlock();
  1908. mBfIRBuilder->SaveDebugLocation();
  1909. if (localVar->IsParam())
  1910. mBfIRBuilder->SetInsertPointAtStart(mCurMethodState->mIRInitBlock);
  1911. else
  1912. {
  1913. BF_ASSERT(localVar->mDeclBlock);
  1914. mBfIRBuilder->SetInsertPointAtStart(localVar->mDeclBlock);
  1915. }
  1916. mBfIRBuilder->ClearDebugLocation();
  1917. BfIRValue curVal;
  1918. if (localVar->mIsThis)
  1919. curVal = mBfIRBuilder->GetArgument(0);
  1920. else
  1921. curVal = localVar->mAddr;
  1922. auto subTypeInstance = startTypeInstance;
  1923. while (subTypeInstance != checkTypeInstance)
  1924. {
  1925. curVal = mBfIRBuilder->CreateInBoundsGEP(curVal, 0, 0);
  1926. subTypeInstance = subTypeInstance->mBaseType;
  1927. }
  1928. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(curVal, 0, fieldInstance.mDataIdx);
  1929. auto defVal = GetDefaultValue(fieldInstance.mResolvedType);
  1930. auto storeInst = mBfIRBuilder->CreateStore(defVal, fieldPtr);
  1931. mBfIRBuilder->SetInsertPoint(curInsertBlock);
  1932. mBfIRBuilder->RestoreDebugLocation();
  1933. }
  1934. localVar->mUnassignedFieldFlags &= ~checkMask;
  1935. if (localVar->mUnassignedFieldFlags == 0)
  1936. localVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  1937. }
  1938. }
  1939. }
  1940. checkTypeInstance = checkTypeInstance->mBaseType;
  1941. }
  1942. return localVar->mAssignedKind != BfLocalVarAssignKind_None;
  1943. }
  1944. void BfModule::LocalVariableDone(BfLocalVariable* localVar, bool isMethodExit)
  1945. {
  1946. BfAstNode* localNameNode = localVar->mNameNode;
  1947. if (localVar->mIsThis)
  1948. {
  1949. localNameNode = mCurMethodInstance->mMethodDef->GetRefNode();
  1950. }
  1951. if (localNameNode != NULL)
  1952. {
  1953. bool isOut = false;
  1954. if (localVar->mResolvedType->IsRef())
  1955. {
  1956. auto refType = (BfRefType*)localVar->mResolvedType;
  1957. isOut = refType->mRefKind == BfRefType::RefKind_Out;
  1958. }
  1959. if ((localVar->mReadFromId == -1) || (isOut) || ((localVar->mIsThis) && (mCurTypeInstance->IsStruct())))
  1960. {
  1961. if ((localVar->mAssignedKind != BfLocalVarAssignKind_Unconditional) & (localVar->IsParam()))
  1962. TryLocalVariableInit(localVar);
  1963. // We may skip processing of local methods, so we won't know if it bind to any of our local variables or not
  1964. bool deferFullAnalysis = mCurMethodState->GetRootMethodState()->mLocalMethodCache.size() != 0;
  1965. // We may have init blocks that we aren't processing here...
  1966. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsAutocompleteMethod) && (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Ctor))
  1967. deferFullAnalysis = true;
  1968. //bool deferFullAnalysis = true;
  1969. bool deferUsageWarning = deferFullAnalysis && (mCompiler->IsAutocomplete()) &&
  1970. (mCompiler->mResolvePassData->mAutoComplete->mResolveType != BfResolveType_GetFixits);
  1971. if (((localVar->mAssignedKind != BfLocalVarAssignKind_Unconditional) || (localVar->mHadExitBeforeAssign)) &&
  1972. (!localVar->mIsImplicitParam))
  1973. {
  1974. if (deferUsageWarning)
  1975. {
  1976. // Ignore
  1977. }
  1978. else if (localVar->mIsThis)
  1979. {
  1980. bool foundFields = false;
  1981. auto checkTypeInstance = mCurTypeInstance;
  1982. while (checkTypeInstance != NULL)
  1983. {
  1984. for (auto& fieldInstance : checkTypeInstance->mFieldInstances)
  1985. {
  1986. if (fieldInstance.mMergedDataIdx == -1)
  1987. continue;
  1988. int checkMask = 1 << fieldInstance.mMergedDataIdx;
  1989. if ((localVar->mUnassignedFieldFlags & checkMask) != 0)
  1990. {
  1991. auto fieldDef = fieldInstance.GetFieldDef();
  1992. if (mCurMethodInstance->mMethodDef->mDeclaringType->mIsPartial)
  1993. {
  1994. if (mCurMethodInstance->mMethodDef->mDeclaringType != fieldInstance.GetFieldDef()->mDeclaringType)
  1995. {
  1996. // This extension is only responsible for its own fields
  1997. foundFields = true;
  1998. continue;
  1999. }
  2000. if (fieldDef->GetInitializer() != NULL)
  2001. {
  2002. // This initializer was handled in CtorNoBody
  2003. foundFields = true;
  2004. continue;
  2005. }
  2006. }
  2007. if (auto propertyDeclaration = BfNodeDynCast<BfPropertyDeclaration>(fieldDef->mFieldDeclaration))
  2008. {
  2009. String propName;
  2010. if (propertyDeclaration->mNameNode != NULL)
  2011. propertyDeclaration->mNameNode->ToString(propName);
  2012. if (checkTypeInstance == mCurTypeInstance)
  2013. {
  2014. Fail(StrFormat("Auto-implemented property '%s' must be fully assigned before control is returned to the caller",
  2015. propName.c_str()), localNameNode, deferFullAnalysis); // 0171
  2016. }
  2017. else
  2018. {
  2019. Fail(StrFormat("Auto-implemented property '%s.%s' must be fully assigned before control is returned to the caller",
  2020. TypeToString(checkTypeInstance).c_str(),
  2021. propName.c_str()), localNameNode, deferFullAnalysis); // 0171
  2022. }
  2023. }
  2024. else
  2025. {
  2026. if (checkTypeInstance == mCurTypeInstance)
  2027. {
  2028. Fail(StrFormat("Field '%s' must be fully assigned before control is returned to the caller",
  2029. fieldDef->mName.c_str()), localNameNode, deferFullAnalysis); // 0171
  2030. }
  2031. else
  2032. {
  2033. Fail(StrFormat("Field '%s.%s' must be fully assigned before control is returned to the caller",
  2034. TypeToString(checkTypeInstance).c_str(),
  2035. fieldDef->mName.c_str()), localNameNode, deferFullAnalysis); // 0171
  2036. }
  2037. }
  2038. foundFields = true;
  2039. }
  2040. }
  2041. checkTypeInstance = checkTypeInstance->mBaseType;
  2042. }
  2043. if (!foundFields)
  2044. {
  2045. if (mCurTypeInstance->mInstSize > 0)
  2046. Fail(StrFormat("The variable '%s' must be fully assigned to before control leaves the current method", localVar->mName.c_str()), localNameNode); // 0177
  2047. }
  2048. }
  2049. else if (localVar->IsParam())
  2050. Fail(StrFormat("The out parameter '%s' must be assigned to before control leaves the current method", localVar->mName.c_str()), localNameNode, deferFullAnalysis); // 0177
  2051. else if (!deferUsageWarning)
  2052. Warn(BfWarning_CS0168_VariableDeclaredButNeverUsed, StrFormat("The variable '%s' is declared but never used", localVar->mName.c_str()), localNameNode, deferFullAnalysis);
  2053. }
  2054. else if ((localVar->mReadFromId == -1) && (!localVar->IsParam()) && (!deferUsageWarning))
  2055. Warn(BfWarning_CS0168_VariableDeclaredButNeverUsed, StrFormat("The variable '%s' is assigned but its value is never used", localVar->mName.c_str()), localNameNode, deferFullAnalysis);
  2056. }
  2057. }
  2058. }
  2059. void BfModule::CreateRetValLocal()
  2060. {
  2061. if (mCurMethodState->mRetVal)
  2062. {
  2063. BfLocalVariable* localDef = new BfLocalVariable();
  2064. localDef->mName = "return";
  2065. localDef->mResolvedType = mCurMethodState->mRetVal.mType;
  2066. localDef->mAddr = mCurMethodState->mRetVal.mValue;
  2067. localDef->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  2068. AddLocalVariableDef(localDef);
  2069. }
  2070. else if (mCurMethodState->mRetValAddr)
  2071. {
  2072. BfLocalVariable* localDef = new BfLocalVariable();
  2073. localDef->mName = "return";
  2074. localDef->mResolvedType = CreateRefType(mCurMethodInstance->mReturnType);
  2075. localDef->mAddr = mCurMethodState->mRetValAddr;
  2076. localDef->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  2077. AddLocalVariableDef(localDef);
  2078. }
  2079. }
  2080. void BfModule::MarkDynStack(BfScopeData* scopeData)
  2081. {
  2082. auto checkScope = mCurMethodState->mCurScope;
  2083. while (true)
  2084. {
  2085. if (checkScope == scopeData)
  2086. break;
  2087. checkScope->mHadOuterDynStack = true;
  2088. checkScope = checkScope->mPrevScope;
  2089. }
  2090. }
  2091. void BfModule::SaveStackState(BfScopeData* scopeData)
  2092. {
  2093. // If we push a value on the stack that needs to survive until the end of scopeData, we need to make sure that no
  2094. // scopes within scopeData restore the stack
  2095. auto checkScope = mCurMethodState->mCurScope;
  2096. while (true)
  2097. {
  2098. if (checkScope == scopeData)
  2099. {
  2100. if ((!checkScope->mSavedStack) && (checkScope->mBlock) && (!checkScope->mIsScopeHead) && (!checkScope->mHadOuterDynStack))
  2101. {
  2102. if (mBfIRBuilder->mHasDebugInfo)
  2103. mBfIRBuilder->SaveDebugLocation();
  2104. auto prevPos = mBfIRBuilder->GetInsertBlock();
  2105. mBfIRBuilder->SetInsertPointAtStart(checkScope->mBlock);
  2106. checkScope->mSavedStack = mBfIRBuilder->CreateStackSave();
  2107. mBfIRBuilder->ClearDebugLocation(checkScope->mSavedStack);
  2108. mBfIRBuilder->SetInsertPoint(prevPos);
  2109. if (mBfIRBuilder->mHasDebugInfo)
  2110. mBfIRBuilder->RestoreDebugLocation();
  2111. }
  2112. break;
  2113. }
  2114. if (checkScope->mSavedStack)
  2115. {
  2116. for (auto usage : checkScope->mSavedStackUses)
  2117. mBfIRBuilder->EraseInstFromParent(usage);
  2118. checkScope->mSavedStackUses.Clear();
  2119. mBfIRBuilder->EraseInstFromParent(checkScope->mSavedStack);
  2120. checkScope->mSavedStack = BfIRValue();
  2121. }
  2122. checkScope = checkScope->mPrevScope;
  2123. }
  2124. }
  2125. BfIRValue BfModule::ValueScopeStart()
  2126. {
  2127. if (IsTargetingBeefBackend())
  2128. return mBfIRBuilder->CreateValueScopeStart();
  2129. return BfIRValue();
  2130. }
  2131. void BfModule::ValueScopeEnd(BfIRValue valueScopeStart)
  2132. {
  2133. if (valueScopeStart)
  2134. mBfIRBuilder->CreateValueScopeHardEnd(valueScopeStart);
  2135. }
  2136. BfProjectSet* BfModule::GetVisibleProjectSet()
  2137. {
  2138. if (mCurMethodState == NULL)
  2139. return NULL;
  2140. if (mCurMethodState->mVisibleProjectSet.IsEmpty())
  2141. {
  2142. HashSet<BfType*> seenTypes;
  2143. std::function<void(BfProject* project)> _AddProject = [&](BfProject* project)
  2144. {
  2145. if (mCurMethodState->mVisibleProjectSet.Add(project))
  2146. {
  2147. for (auto dep : project->mDependencies)
  2148. _AddProject(dep);
  2149. }
  2150. };
  2151. std::function<void(BfType* type)> _AddType = [&](BfType* type)
  2152. {
  2153. auto typeInstance = type->ToTypeInstance();
  2154. if (typeInstance == NULL)
  2155. {
  2156. if (type->IsSizedArray())
  2157. _AddType(type->GetUnderlyingType());
  2158. return;
  2159. }
  2160. if (typeInstance->IsTuple())
  2161. {
  2162. for (auto& fieldInst : typeInstance->mFieldInstances)
  2163. {
  2164. if (fieldInst.mDataIdx != -1)
  2165. _AddType(fieldInst.mResolvedType);
  2166. }
  2167. }
  2168. _AddProject(typeInstance->mTypeDef->mProject);
  2169. if (typeInstance->mGenericTypeInfo == NULL)
  2170. return;
  2171. for (auto type : typeInstance->mGenericTypeInfo->mTypeGenericArguments)
  2172. {
  2173. if (seenTypes.Add(type))
  2174. _AddType(type);
  2175. }
  2176. };
  2177. if (mCurTypeInstance != NULL)
  2178. _AddType(mCurTypeInstance);
  2179. auto methodState = mCurMethodState;
  2180. while (methodState != NULL)
  2181. {
  2182. if (methodState->mMethodInstance != NULL)
  2183. {
  2184. _AddProject(methodState->mMethodInstance->mMethodDef->mDeclaringType->mProject);
  2185. if (methodState->mMethodInstance->mMethodInfoEx != NULL)
  2186. {
  2187. for (auto type : methodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  2188. _AddType(type);
  2189. }
  2190. }
  2191. methodState = methodState->mPrevMethodState;
  2192. }
  2193. }
  2194. return &mCurMethodState->mVisibleProjectSet;
  2195. }
  2196. BfFileInstance* BfModule::GetFileFromNode(BfAstNode* astNode)
  2197. {
  2198. auto bfParser = astNode->GetSourceData()->ToParserData();
  2199. if (bfParser == NULL)
  2200. return NULL;
  2201. BfFileInstance** fileInstancePtr = NULL;
  2202. if (!mFileInstanceMap.TryAdd(bfParser, NULL, &fileInstancePtr))
  2203. {
  2204. return *fileInstancePtr;
  2205. }
  2206. else
  2207. {
  2208. // It's possible two parsers have the same file name (ie: mNextRevision)
  2209. BfFileInstance** namedFileInstancePtr = NULL;
  2210. if (!mNamedFileInstanceMap.TryAdd(bfParser->mFileName, NULL, &namedFileInstancePtr))
  2211. {
  2212. auto bfFileInstance = *namedFileInstancePtr;
  2213. *fileInstancePtr = bfFileInstance;
  2214. return bfFileInstance;
  2215. }
  2216. int slashPos = (int)bfParser->mFileName.LastIndexOf(DIR_SEP_CHAR);
  2217. auto bfFileInstance = new BfFileInstance();
  2218. *fileInstancePtr = bfFileInstance;
  2219. *namedFileInstancePtr = bfFileInstance;
  2220. bfFileInstance->mPrevPosition.mFileInstance = bfFileInstance;
  2221. bfFileInstance->mParser = bfParser;
  2222. BfLogSysM("GetFileFromNode new file. Mod: %p FileInstance: %p Parser: %p\n", this, bfFileInstance, bfParser);
  2223. if ((mBfIRBuilder != NULL) && (mBfIRBuilder->DbgHasLineInfo()))
  2224. {
  2225. String fileName = bfParser->mFileName;
  2226. for (int i = 0; i < (int)fileName.length(); i++)
  2227. {
  2228. if (fileName[i] == DIR_SEP_CHAR_ALT)
  2229. fileName[i] = DIR_SEP_CHAR;
  2230. }
  2231. bfFileInstance->mDIFile = mBfIRBuilder->DbgCreateFile(fileName.Substring(slashPos + 1), fileName.Substring(0, BF_MAX(slashPos, 0)), bfParser->mMD5Hash);
  2232. }
  2233. return bfFileInstance;
  2234. }
  2235. }
  2236. void BfModule::UpdateSrcPos(BfAstNode* astNode, BfSrcPosFlags flags, int debugLocOffset)
  2237. {
  2238. // We set force to true when we MUST get the line position set (for navigation purposes, for example)
  2239. if (((mBfIRBuilder->mIgnoreWrites)) && ((flags & BfSrcPosFlag_Force) == 0))
  2240. return;
  2241. BF_ASSERT((!mAwaitingInitFinish) || (mBfIRBuilder->mIgnoreWrites));
  2242. if (astNode == NULL)
  2243. return;
  2244. auto bfParser = astNode->GetSourceData()->ToParserData();
  2245. if (bfParser == NULL)
  2246. return;
  2247. if ((mCurFilePosition.mFileInstance == NULL) || (mCurFilePosition.mFileInstance->mParser != bfParser))
  2248. {
  2249. if (mCurFilePosition.mFileInstance != NULL)
  2250. {
  2251. BF_ASSERT(mFileInstanceMap.GetCount() != 0);
  2252. mCurFilePosition.mFileInstance->mPrevPosition = mCurFilePosition;
  2253. }
  2254. auto bfFileInstance = GetFileFromNode(astNode);
  2255. if (bfFileInstance->mPrevPosition.mFileInstance != NULL)
  2256. {
  2257. mCurFilePosition = bfFileInstance->mPrevPosition;
  2258. }
  2259. else
  2260. {
  2261. mCurFilePosition.mFileInstance = bfFileInstance;
  2262. mCurFilePosition.mCurLine = 0;
  2263. mCurFilePosition.mCurSrcPos = 0;
  2264. }
  2265. }
  2266. int srcPos = astNode->GetSrcStart() + debugLocOffset;
  2267. BF_ASSERT(srcPos < bfParser->mSrcLength);
  2268. auto* jumpEntry = bfParser->mJumpTable + (srcPos / PARSER_JUMPTABLE_DIVIDE);
  2269. if (jumpEntry->mCharIdx > srcPos)
  2270. jumpEntry--;
  2271. mCurFilePosition.mCurLine = jumpEntry->mLineNum;
  2272. mCurFilePosition.mCurSrcPos = jumpEntry->mCharIdx;
  2273. mCurFilePosition.mCurColumn = 0;
  2274. while (mCurFilePosition.mCurSrcPos < srcPos)
  2275. {
  2276. if (bfParser->mSrc[mCurFilePosition.mCurSrcPos] == '\n')
  2277. {
  2278. mCurFilePosition.mCurLine++;
  2279. mCurFilePosition.mCurColumn = 0;
  2280. }
  2281. else
  2282. {
  2283. mCurFilePosition.mCurColumn++;
  2284. }
  2285. mCurFilePosition.mCurSrcPos++;
  2286. }
  2287. //TODO: if we bail on the "mCurMethodState == NULL" case then we don't get it set during type declarations
  2288. if (((flags & BfSrcPosFlag_NoSetDebugLoc) == 0) && (mBfIRBuilder->DbgHasLineInfo()) && (mCurMethodState != NULL))
  2289. {
  2290. int column = mCurFilePosition.mCurColumn + 1;
  2291. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend))
  2292. {
  2293. // Set to illegal position
  2294. column = 0;
  2295. }
  2296. if (mSetIllegalSrcPosition)
  2297. column = 0;
  2298. BfIRMDNode useDIScope = mCurMethodState->mCurScope->mDIScope;
  2299. auto wantDIFile = mCurFilePosition.mFileInstance->mDIFile;
  2300. if ((wantDIFile != mCurMethodState->mDIFile) && (mCurMethodState->mDIFile))
  2301. {
  2302. // This is from a different scope...
  2303. if (wantDIFile != mCurMethodState->mCurScope->mAltDIFile)
  2304. {
  2305. mCurMethodState->mCurScope->mAltDIFile = wantDIFile;
  2306. mCurMethodState->mCurScope->mAltDIScope = mBfIRBuilder->DbgCreateLexicalBlock(mCurMethodState->mCurScope->mDIScope, wantDIFile, mCurFilePosition.mCurLine + 1, column);
  2307. }
  2308. if (mCurMethodState->mCurScope->mAltDIScope) // This may not be set if mAltDIFile is set by a mixin
  2309. useDIScope = mCurMethodState->mCurScope->mAltDIScope;
  2310. }
  2311. else
  2312. {
  2313. if (mCurMethodState->mCurScope->mAltDIFile)
  2314. {
  2315. mCurMethodState->mCurScope->mAltDIFile = BfIRMDNode();
  2316. mCurMethodState->mCurScope->mAltDIScope = BfIRMDNode();
  2317. }
  2318. }
  2319. auto inlineAt = mCurMethodState->mCurScope->mDIInlinedAt;
  2320. if (mCurMethodState->mCrossingMixin)
  2321. inlineAt = BfIRMDNode();
  2322. if ((!useDIScope) && (mIsComptimeModule))
  2323. useDIScope = wantDIFile;
  2324. if (!useDIScope)
  2325. mBfIRBuilder->ClearDebugLocation();
  2326. else
  2327. mBfIRBuilder->SetCurrentDebugLocation(mCurFilePosition.mCurLine + 1, column, useDIScope, inlineAt);
  2328. if ((flags & BfSrcPosFlag_Expression) == 0)
  2329. mBfIRBuilder->CreateStatementStart();
  2330. }
  2331. }
  2332. void BfModule::UpdateExprSrcPos(BfAstNode* astNode, BfSrcPosFlags flags)
  2333. {
  2334. // We've turned off expr src pos (for now?)
  2335. //UpdateSrcPos(astNode, (BfSrcPosFlags)(flags | BfSrcPosFlag_Expression));
  2336. }
  2337. void BfModule::UseDefaultSrcPos(BfSrcPosFlags flags, int debugLocOffset)
  2338. {
  2339. if (mCompiler->mBfObjectTypeDef != NULL)
  2340. UpdateSrcPos(mCompiler->mBfObjectTypeDef->mTypeDeclaration, flags, debugLocOffset);
  2341. SetIllegalSrcPos();
  2342. }
  2343. void BfModule::SetIllegalSrcPos(BfSrcPosFlags flags)
  2344. {
  2345. if ((mBfIRBuilder->DbgHasInfo()) && (mCurMethodState != NULL))
  2346. {
  2347. auto curScope = mCurMethodState->mCurScope->mDIScope;
  2348. if (curScope)
  2349. {
  2350. if ((mCurMethodState->mCurScope->mDIInlinedAt) && (mCompiler->mOptions.IsCodeView()))
  2351. {
  2352. // Currently, CodeView does not record column positions so we can't use an illegal column position as an "invalid" marker
  2353. mBfIRBuilder->SetCurrentDebugLocation(0, 0, curScope, mCurMethodState->mCurScope->mDIInlinedAt);
  2354. }
  2355. else
  2356. {
  2357. // Set to whatever it previously was but at column zero, which we will know to be illegal
  2358. mBfIRBuilder->SetCurrentDebugLocation(mCurFilePosition.mCurLine + 1, 0, curScope, mCurMethodState->mCurScope->mDIInlinedAt);
  2359. }
  2360. }
  2361. if ((flags & BfSrcPosFlag_Expression) == 0)
  2362. mBfIRBuilder->CreateStatementStart();
  2363. }
  2364. }
  2365. void BfModule::SetIllegalExprSrcPos(BfSrcPosFlags flags)
  2366. {
  2367. // We've turned off expr src pos (for now?)
  2368. //SetIllegalSrcPos((BfSrcPosFlags)(flags | BfSrcPosFlag_Expression));
  2369. }
  2370. bool BfModule::CheckProtection(BfProtection protection, BfTypeDef* checkType, bool allowProtected, bool allowPrivate)
  2371. {
  2372. if ((protection == BfProtection_Public) ||
  2373. (((protection == BfProtection_Protected) || (protection == BfProtection_ProtectedInternal)) && (allowProtected)) ||
  2374. ((protection == BfProtection_Private) && (allowPrivate)))
  2375. return true;
  2376. if ((mAttributeState != NULL) && (mAttributeState->mCustomAttributes != NULL) && (mAttributeState->mCustomAttributes->Contains(mCompiler->mFriendAttributeTypeDef)))
  2377. {
  2378. mAttributeState->mUsed = true;
  2379. return true;
  2380. }
  2381. if (((protection == BfProtection_Internal) || (protection == BfProtection_ProtectedInternal)) && (checkType != NULL))
  2382. {
  2383. if (CheckInternalProtection(checkType))
  2384. return true;
  2385. }
  2386. return false;
  2387. }
  2388. void BfModule::GetAccessAllowed(BfTypeInstance* checkType, bool &allowProtected, bool &allowPrivate)
  2389. {
  2390. allowPrivate = (checkType == mCurTypeInstance) || (IsInnerType(mCurTypeInstance, checkType));
  2391. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2392. {
  2393. auto mixinOwner = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  2394. allowPrivate |= (checkType == mixinOwner) || (IsInnerType(mixinOwner, checkType));
  2395. }
  2396. allowProtected = allowPrivate;
  2397. }
  2398. bool BfModule::CheckProtection(BfProtectionCheckFlags& flags, BfTypeInstance* memberOwner, BfProject* memberProject, BfProtection memberProtection, BfTypeInstance* lookupStartType)
  2399. {
  2400. if (memberProtection == BfProtection_Hidden)
  2401. return false;
  2402. if (memberProtection == BfProtection_Public)
  2403. return true;
  2404. if ((flags & BfProtectionCheckFlag_CheckedPrivate) == 0)
  2405. {
  2406. BfTypeInstance* curCheckType = mCurTypeInstance;
  2407. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2408. {
  2409. auto mixinOwner = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  2410. curCheckType = mixinOwner;
  2411. }
  2412. bool allowPrivate = (curCheckType != NULL) && (memberOwner->IsInstanceOf(curCheckType->mTypeDef));
  2413. if (curCheckType != NULL)
  2414. allowPrivate |= IsInnerType(curCheckType->mTypeDef, memberOwner->mTypeDef);
  2415. if (allowPrivate)
  2416. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_AllowPrivate | BfProtectionCheckFlag_CheckedPrivate);
  2417. else
  2418. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedPrivate);
  2419. }
  2420. if ((flags & BfProtectionCheckFlag_AllowPrivate) != 0)
  2421. return true;
  2422. if ((memberProtection == BfProtection_Protected) || (memberProtection == BfProtection_ProtectedInternal))
  2423. {
  2424. if ((flags & BfProtectionCheckFlag_CheckedProtected) == 0)
  2425. {
  2426. bool allowProtected = false;
  2427. auto memberOwnerTypeDef = memberOwner->mTypeDef;
  2428. auto curCheckType = mCurTypeInstance;
  2429. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2430. {
  2431. auto mixinOwner = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  2432. curCheckType = mixinOwner;
  2433. }
  2434. if ((flags & BfProtectionCheckFlag_InstanceLookup) != 0)
  2435. {
  2436. auto lookupCheckType = lookupStartType;
  2437. while (lookupCheckType->mInheritDepth >= curCheckType->mInheritDepth)
  2438. {
  2439. if (lookupCheckType == curCheckType)
  2440. {
  2441. allowProtected = true;
  2442. break;
  2443. }
  2444. if (lookupCheckType == memberOwner)
  2445. break;
  2446. lookupCheckType = lookupCheckType->mBaseType;
  2447. if (lookupCheckType == NULL)
  2448. break;
  2449. }
  2450. }
  2451. else
  2452. {
  2453. auto lookupCheckType = curCheckType;
  2454. while (lookupCheckType->mInheritDepth >= memberOwner->mInheritDepth)
  2455. {
  2456. if (lookupCheckType == memberOwner)
  2457. {
  2458. allowProtected = true;
  2459. break;
  2460. }
  2461. lookupCheckType = lookupCheckType->mBaseType;
  2462. if (lookupCheckType == NULL)
  2463. break;
  2464. }
  2465. }
  2466. if (!allowProtected)
  2467. {
  2468. // It's possible our outer type is derived from 'memberOwner'
  2469. while (curCheckType->mTypeDef->mNestDepth > 0)
  2470. {
  2471. curCheckType = GetOuterType(curCheckType);
  2472. if (curCheckType == NULL)
  2473. break;
  2474. auto lookupCheckType = lookupStartType;
  2475. while (lookupCheckType->mInheritDepth >= curCheckType->mInheritDepth)
  2476. {
  2477. if (lookupCheckType == curCheckType)
  2478. {
  2479. allowProtected = true;
  2480. break;
  2481. }
  2482. if (lookupCheckType == memberOwner)
  2483. break;
  2484. lookupCheckType = lookupCheckType->mBaseType;
  2485. if (lookupCheckType == NULL)
  2486. break;
  2487. }
  2488. }
  2489. }
  2490. if (allowProtected)
  2491. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedProtected | BfProtectionCheckFlag_AllowProtected);
  2492. else
  2493. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedProtected);
  2494. }
  2495. if ((flags & BfProtectionCheckFlag_AllowProtected) != 0)
  2496. return true;
  2497. }
  2498. if ((mAttributeState != NULL) && (mAttributeState->mCustomAttributes != NULL) && (mAttributeState->mCustomAttributes->Contains(mCompiler->mFriendAttributeTypeDef)))
  2499. {
  2500. mAttributeState->mUsed = true;
  2501. return true;
  2502. }
  2503. if (((memberProtection == BfProtection_Internal) || (memberProtection == BfProtection_ProtectedInternal)) && (memberOwner != NULL))
  2504. {
  2505. if (CheckInternalProtection(memberOwner->mTypeDef))
  2506. return true;
  2507. }
  2508. return false;
  2509. }
  2510. void BfModule::SetElementType(BfAstNode* astNode, BfSourceElementType elementType)
  2511. {
  2512. if (mCompiler->mResolvePassData != NULL)
  2513. {
  2514. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(astNode))
  2515. sourceClassifier->SetElementType(astNode, elementType);
  2516. }
  2517. }
  2518. bool BfModule::PreFail()
  2519. {
  2520. if (!mIgnoreErrors)
  2521. return true;
  2522. SetFail();
  2523. return false;
  2524. }
  2525. void BfModule::SetFail()
  2526. {
  2527. if (mIgnoreErrors)
  2528. {
  2529. if (mAttributeState != NULL)
  2530. mAttributeState->mFlags = (BfAttributeState::Flags)(mAttributeState->mFlags | BfAttributeState::Flag_HadError);
  2531. }
  2532. }
  2533. void BfModule::VerifyOnDemandMethods()
  2534. {
  2535. #ifdef _DEBUG
  2536. // if (mParentModule != NULL)
  2537. // {
  2538. // BF_ASSERT(mOnDemandMethodCount == 0);
  2539. // mParentModule->VerifyOnDemandMethods();
  2540. // return;
  2541. // }
  2542. //
  2543. // int onDemandCount = 0;
  2544. // for (auto type : mOwnedTypeInstances)
  2545. // {
  2546. // auto typeInst = type->ToTypeInstance();
  2547. // for (auto& methodGroup : typeInst->mMethodInstanceGroups)
  2548. // {
  2549. // if ((methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) ||
  2550. // (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference) ||
  2551. // (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl) ||
  2552. // (methodGroup.mOnDemandKind == BfMethodOnDemandKind_InWorkList))
  2553. // onDemandCount++;
  2554. // }
  2555. // }
  2556. //
  2557. // BF_ASSERT(mOnDemandMethodCount == onDemandCount);
  2558. #endif
  2559. }
  2560. bool BfModule::IsSkippingExtraResolveChecks()
  2561. {
  2562. if (mIsComptimeModule)
  2563. return false;
  2564. return mCompiler->IsSkippingExtraResolveChecks();
  2565. }
  2566. bool BfModule::AddErrorContext(StringImpl& errorString, BfAstNode* refNode, BfWhileSpecializingFlags& isWhileSpecializing, bool isWarning)
  2567. {
  2568. bool isWhileSpecializingMethod = false;
  2569. if ((mIsSpecialModule) && (mModuleName == "vdata"))
  2570. errorString += StrFormat("\n while generating vdata for project '%s'", mProject->mName.c_str());
  2571. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend))
  2572. errorString += StrFormat("\n while generating append size calculating method");
  2573. else if (refNode == NULL)
  2574. {
  2575. if (mCurTypeInstance != NULL)
  2576. errorString += StrFormat("\n while compiling '%s'", TypeToString(mCurTypeInstance, BfTypeNameFlags_None).c_str());
  2577. else if (mProject != NULL)
  2578. errorString += StrFormat("\n while compiling project '%s'", mProject->mName.c_str());
  2579. }
  2580. if (mCurTypeInstance != NULL)
  2581. {
  2582. auto _CheckMethodInstance = [&](BfMethodInstance* methodInstance)
  2583. {
  2584. // Propogate the fail all the way to the main method (assuming we're in a local method or lambda)
  2585. if (isWarning)
  2586. methodInstance->mHasWarning = true;
  2587. else
  2588. methodInstance->mHasFailed = true;
  2589. if (!methodInstance->mHasStartedDeclaration)
  2590. StartMethodDeclaration(methodInstance, NULL);
  2591. bool isSpecializedMethod = ((methodInstance != NULL) && (!methodInstance->mIsUnspecialized) && (methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mMethodGenericArguments.size() != 0));
  2592. if (isSpecializedMethod)
  2593. {
  2594. //auto unspecializedMethod = &mCurMethodInstance->mMethodInstanceGroup->mMethodSpecializationMap.begin()->second;
  2595. auto unspecializedMethod = methodInstance->mMethodInstanceGroup->mDefault;
  2596. if (unspecializedMethod == methodInstance)
  2597. {
  2598. // This is a local method inside a generic method
  2599. BF_ASSERT(methodInstance->mMethodDef->mIsLocalMethod);
  2600. }
  2601. else
  2602. {
  2603. if (isWarning)
  2604. {
  2605. if (unspecializedMethod->mHasWarning)
  2606. return false; // At least SOME error has already been reported
  2607. }
  2608. else
  2609. {
  2610. if (unspecializedMethod->mHasFailed)
  2611. return false; // At least SOME error has already been reported
  2612. }
  2613. }
  2614. }
  2615. if (isSpecializedMethod)
  2616. {
  2617. errorString += StrFormat("\n while specializing method '%s'", MethodToString(methodInstance).c_str());
  2618. isWhileSpecializing = (BfWhileSpecializingFlags)(isWhileSpecializing | BfWhileSpecializingFlag_Method);
  2619. isWhileSpecializingMethod = true;
  2620. }
  2621. else if ((methodInstance != NULL) && (methodInstance->mIsForeignMethodDef))
  2622. {
  2623. errorString += StrFormat("\n while implementing default interface method '%s'", MethodToString(methodInstance).c_str());
  2624. isWhileSpecializing = (BfWhileSpecializingFlags)(isWhileSpecializing | BfWhileSpecializingFlag_Method);
  2625. isWhileSpecializingMethod = true;
  2626. }
  2627. if ((mCurTypeInstance->IsGenericTypeInstance()) && (!mCurTypeInstance->IsUnspecializedType()))
  2628. {
  2629. errorString += StrFormat("\n while specializing type '%s'", TypeToString(mCurTypeInstance).c_str());
  2630. isWhileSpecializing = (BfWhileSpecializingFlags)(isWhileSpecializing | BfWhileSpecializingFlag_Type);
  2631. }
  2632. return true;
  2633. };
  2634. bool hadMethodInstance = false;
  2635. if (mCurMethodState != NULL)
  2636. {
  2637. auto checkMethodState = mCurMethodState;
  2638. while (checkMethodState != NULL)
  2639. {
  2640. auto methodInstance = checkMethodState->mMethodInstance;
  2641. if (methodInstance == NULL)
  2642. {
  2643. checkMethodState = checkMethodState->mPrevMethodState;
  2644. continue;
  2645. }
  2646. hadMethodInstance = true;
  2647. if (!_CheckMethodInstance(methodInstance))
  2648. return false;
  2649. checkMethodState = checkMethodState->mPrevMethodState;
  2650. }
  2651. }
  2652. if ((!hadMethodInstance) && (mCurMethodInstance != NULL))
  2653. {
  2654. if (!_CheckMethodInstance(mCurMethodInstance))
  2655. return false;
  2656. }
  2657. }
  2658. if ((!isWhileSpecializing) && (mCurTypeInstance != NULL) && ((mCurTypeInstance->IsGenericTypeInstance()) && (!mCurTypeInstance->IsUnspecializedType())))
  2659. {
  2660. errorString += StrFormat("\n while specializing type '%s'", TypeToString(mCurTypeInstance).c_str());
  2661. isWhileSpecializing = (BfWhileSpecializingFlags)(isWhileSpecializing | BfWhileSpecializingFlag_Type);
  2662. }
  2663. return true;
  2664. }
  2665. BfError* BfModule::Fail(const StringImpl& error, BfAstNode* refNode, bool isPersistent, bool deferError)
  2666. {
  2667. BP_ZONE("BfModule::Fail");
  2668. if (mIgnoreErrors)
  2669. {
  2670. mHadIgnoredError = true;
  2671. if (mAttributeState != NULL)
  2672. mAttributeState->mFlags = (BfAttributeState::Flags)(mAttributeState->mFlags | BfAttributeState::Flag_HadError);
  2673. return NULL;
  2674. }
  2675. if (!mReportErrors)
  2676. {
  2677. mCompiler->mPassInstance->SilentFail();
  2678. return NULL;
  2679. }
  2680. if (refNode != NULL)
  2681. refNode = BfNodeToNonTemporary(refNode);
  2682. //BF_ASSERT(refNode != NULL);
  2683. if (mIsComptimeModule)
  2684. {
  2685. if (auto ceDbgState = GetCeDbgState())
  2686. {
  2687. // Follow normal fail path
  2688. }
  2689. else
  2690. {
  2691. mHadBuildError = true;
  2692. if ((mCompiler->mCeMachine->mCurContext != NULL) && (mCompiler->mCeMachine->mCurContext->mCurCallSource != NULL) &&
  2693. (mCompiler->mCeMachine->mCurContext->mCurCallSource->mRefNode != NULL))
  2694. {
  2695. BfError* bfError = mCompiler->mPassInstance->Fail("Comptime method generation had errors",
  2696. mCompiler->mCeMachine->mCurContext->mCurCallSource->mRefNode);
  2697. if (bfError != NULL)
  2698. mCompiler->mPassInstance->MoreInfo(error, refNode);
  2699. return bfError;
  2700. }
  2701. return NULL;
  2702. }
  2703. }
  2704. if ((mCurMethodState != NULL) && (mCurMethodState->mConstResolveState != NULL) && (mCurMethodState->mConstResolveState->mInCalcAppend))
  2705. {
  2706. mCurMethodState->mConstResolveState->mFailed = true;
  2707. return NULL;
  2708. }
  2709. if (mCurMethodInstance != NULL)
  2710. mCurMethodInstance->mHasFailed = true;
  2711. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsUnspecializedTypeVariation()))
  2712. return NULL;
  2713. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->IsOrInUnspecializedVariation()))
  2714. return NULL; // Ignore errors on unspecialized variations, they are always dups
  2715. if (!mHadBuildError)
  2716. mHadBuildError = true;
  2717. if (mParentModule != NULL)
  2718. mParentModule->mHadBuildError = true;
  2719. if (mCurTypeInstance != NULL)
  2720. AddFailType(mCurTypeInstance);
  2721. BfLogSysM("BfModule::Fail module %p type %p %s\n", this, mCurTypeInstance, error.c_str());
  2722. String errorString = error;
  2723. BfWhileSpecializingFlags isWhileSpecializing = BfWhileSpecializingFlag_None;
  2724. if (!AddErrorContext(errorString, refNode, isWhileSpecializing, false))
  2725. return NULL;
  2726. BfError* bfError = NULL;
  2727. if (isWhileSpecializing)
  2728. deferError = true;
  2729. if (!mHadBuildError)
  2730. mHadBuildError = true;
  2731. // Check mixins
  2732. {
  2733. auto checkMethodState = mCurMethodState;
  2734. while (checkMethodState != NULL)
  2735. {
  2736. auto rootMixinState = checkMethodState->GetRootMixinState();
  2737. if (rootMixinState != NULL)
  2738. {
  2739. String mixinErr = StrFormat("Failed to inject mixin '%s'", MethodToString(rootMixinState->mMixinMethodInstance).c_str());
  2740. if (deferError)
  2741. bfError = mCompiler->mPassInstance->DeferFail(mixinErr, rootMixinState->mSource);
  2742. else
  2743. bfError = mCompiler->mPassInstance->Fail(mixinErr, rootMixinState->mSource);
  2744. if (bfError == NULL)
  2745. return NULL;
  2746. bfError->mIsWhileSpecializing = isWhileSpecializing;
  2747. mCompiler->mPassInstance->MoreInfo(errorString, refNode);
  2748. auto mixinState = checkMethodState->mMixinState;
  2749. while ((mixinState != NULL) && (mixinState->mPrevMixinState != NULL))
  2750. {
  2751. mCompiler->mPassInstance->MoreInfo(StrFormat("Injected from mixin '%s'", MethodToString(mixinState->mPrevMixinState->mMixinMethodInstance).c_str()), mixinState->mSource);
  2752. mixinState = mixinState->mPrevMixinState;
  2753. }
  2754. return bfError;
  2755. }
  2756. checkMethodState = checkMethodState->mPrevMethodState;
  2757. }
  2758. }
  2759. if (deferError)
  2760. bfError = mCompiler->mPassInstance->Fail(errorString, refNode);
  2761. else if (refNode == NULL)
  2762. bfError = mCompiler->mPassInstance->Fail(errorString);
  2763. else
  2764. bfError = mCompiler->mPassInstance->Fail(errorString, refNode);
  2765. if (bfError != NULL)
  2766. {
  2767. bfError->mIsWhileSpecializing = isWhileSpecializing;
  2768. bfError->mProject = mProject;
  2769. bfError->mIsPersistent = isPersistent;
  2770. if ((mCurMethodState != NULL) && (mCurMethodState->mDeferredCallEmitState != NULL) && (mCurMethodState->mDeferredCallEmitState->mCloseNode != NULL))
  2771. mCompiler->mPassInstance->MoreInfo("Error during deferred statement handling", mCurMethodState->mDeferredCallEmitState->mCloseNode);
  2772. else if ((mCurMethodState != NULL) && (mCurMethodState->mEmitRefNode != NULL))
  2773. mCompiler->mPassInstance->MoreInfo("Error in emitted code", mCurMethodState->mEmitRefNode);
  2774. }
  2775. return bfError;
  2776. }
  2777. BfError* BfModule::FailInternal(const StringImpl& error, BfAstNode* refNode)
  2778. {
  2779. if (mHadBuildError)
  2780. return NULL;
  2781. return Fail(error, refNode);
  2782. }
  2783. BfError* BfModule::FailAfter(const StringImpl& error, BfAstNode* refNode)
  2784. {
  2785. if (mIgnoreErrors)
  2786. return NULL;
  2787. if (refNode != NULL)
  2788. refNode = BfNodeToNonTemporary(refNode);
  2789. mHadBuildError = true;
  2790. BfError* bfError = mCompiler->mPassInstance->FailAfter(error, refNode);
  2791. if (bfError != NULL)
  2792. bfError->mProject = mProject;
  2793. return bfError;
  2794. }
  2795. BfError* BfModule::Warn(int warningNum, const StringImpl& warning, BfAstNode* refNode, bool isPersistent, bool showInSpecialized)
  2796. {
  2797. if (mIgnoreErrors || mIgnoreWarnings)
  2798. return NULL;
  2799. if (!mReportErrors)
  2800. {
  2801. mCompiler->mPassInstance->SilentFail();
  2802. return NULL;
  2803. }
  2804. BfAstNode* unwarnNode = refNode;
  2805. //
  2806. {
  2807. BfParentNodeEntry* parentNodeEntry = mParentNodeEntry;
  2808. while (parentNodeEntry != NULL)
  2809. {
  2810. if (auto block = BfNodeDynCast<BfBlock>(parentNodeEntry->mNode))
  2811. break;
  2812. unwarnNode = parentNodeEntry->mNode;
  2813. parentNodeEntry = parentNodeEntry->mPrev;
  2814. }
  2815. }
  2816. auto parser = unwarnNode->GetSourceData()->ToParserData();
  2817. if ((parser != NULL) && (parser->IsUnwarnedAt(unwarnNode)))
  2818. {
  2819. return NULL;
  2820. }
  2821. // Right now we're only warning on the unspecialized declarations, we may revisit this
  2822. if (mCurMethodInstance != NULL)
  2823. {
  2824. if (mCurMethodInstance->IsSpecializedGenericMethodOrType())
  2825. {
  2826. if (!showInSpecialized)
  2827. return NULL;
  2828. }
  2829. if (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend)
  2830. return NULL; // No ctorCalcAppend warnings
  2831. }
  2832. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsSpecializedType()))
  2833. {
  2834. if (!showInSpecialized)
  2835. return NULL;
  2836. }
  2837. if (refNode != NULL)
  2838. refNode = BfNodeToNonTemporary(refNode);
  2839. String warningString = warning;
  2840. BfWhileSpecializingFlags isWhileSpecializing = BfWhileSpecializingFlag_None;
  2841. if (!AddErrorContext(warningString, refNode, isWhileSpecializing, true))
  2842. return NULL;
  2843. bool deferWarning = isWhileSpecializing != BfWhileSpecializingFlag_None;
  2844. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2845. {
  2846. // We used to bubble up warnings into the mixin injection site, BUT
  2847. // we are now assuming any relevant warnings will be given at the declaration site
  2848. return NULL;
  2849. }
  2850. if ((mCurMethodState != NULL) && (mCurMethodState->mEmitRefNode != NULL))
  2851. {
  2852. BfError* bfError = mCompiler->mPassInstance->Warn(warningNum, "Emitted code had errors", mCurMethodState->mEmitRefNode);
  2853. if (bfError != NULL)
  2854. mCompiler->mPassInstance->MoreInfo(warningString, refNode);
  2855. return bfError;
  2856. }
  2857. BfError* bfError;
  2858. if (refNode != NULL)
  2859. bfError = mCompiler->mPassInstance->WarnAt(warningNum, warningString, refNode->GetSourceData(), refNode->GetSrcStart(), refNode->GetSrcLength());
  2860. else
  2861. bfError = mCompiler->mPassInstance->Warn(warningNum, warningString);
  2862. if (bfError != NULL)
  2863. {
  2864. bfError->mIsWhileSpecializing = isWhileSpecializing;
  2865. bfError->mProject = mProject;
  2866. AddFailType(mCurTypeInstance);
  2867. mHadBuildWarning = true;
  2868. bfError->mIsPersistent = isPersistent;
  2869. if ((mCompiler->IsAutocomplete()) && (mCompiler->mResolvePassData->mAutoComplete->CheckFixit((refNode))))
  2870. {
  2871. BfParserData* parser = refNode->GetSourceData()->ToParserData();
  2872. if (parser != NULL)
  2873. {
  2874. int fileLoc = BfFixitFinder::FindLineStartBefore(refNode);
  2875. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("fixit", StrFormat("#unwarn\tunwarn|%s|%d|#unwarn|", parser->mFileName.c_str(), fileLoc).c_str()));
  2876. if (warningNum != 0)
  2877. {
  2878. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("fixit", StrFormat("#pragma warning disable %d\t.pragma|%s|%d||#pragma warning disable %d",
  2879. warningNum, parser->mFileName.c_str(), 0, warningNum).c_str()));
  2880. }
  2881. }
  2882. }
  2883. }
  2884. return bfError;
  2885. }
  2886. void BfModule::CheckErrorAttributes(BfTypeInstance* typeInstance, BfMethodInstance* methodInstance, BfCustomAttributes* customAttributes, BfAstNode* targetSrc)
  2887. {
  2888. if (customAttributes == NULL)
  2889. return;
  2890. auto _AddDeclarationMoreInfo = [&]()
  2891. {
  2892. if (methodInstance != NULL)
  2893. {
  2894. if (methodInstance->mMethodDef->mMethodDeclaration != NULL)
  2895. mCompiler->mPassInstance->MoreInfo(
  2896. StrFormat("See method declaration '%s'", MethodToString(methodInstance).c_str()),
  2897. methodInstance->mMethodDef->GetRefNode());
  2898. }
  2899. else
  2900. {
  2901. mCompiler->mPassInstance->MoreInfo(
  2902. StrFormat("See type declaration '%s'", TypeToString(typeInstance, BfTypeNameFlag_UseUnspecializedGenericParamNames).c_str()),
  2903. typeInstance->mTypeDef->GetRefNode());
  2904. }
  2905. };
  2906. BfIRConstHolder* constHolder = typeInstance->mConstHolder;
  2907. auto customAttribute = customAttributes->Get(mCompiler->mObsoleteAttributeTypeDef);
  2908. if ((customAttribute != NULL) && (!customAttribute->mCtorArgs.IsEmpty()) && (targetSrc != NULL))
  2909. {
  2910. String err;
  2911. if (methodInstance != NULL)
  2912. err = StrFormat("'%s' is obsolete", MethodToString(methodInstance).c_str());
  2913. else
  2914. err = StrFormat("'%s' is obsolete", TypeToString(typeInstance, BfTypeNameFlag_UseUnspecializedGenericParamNames).c_str());
  2915. bool isError = false;
  2916. auto constant = constHolder->GetConstant(customAttribute->mCtorArgs[0]);
  2917. if (constant->mTypeCode == BfTypeCode_Boolean)
  2918. {
  2919. isError = constant->mBool;
  2920. }
  2921. else if (customAttribute->mCtorArgs.size() >= 2)
  2922. {
  2923. String* str = GetStringPoolString(customAttribute->mCtorArgs[0], constHolder);
  2924. if (str != NULL)
  2925. {
  2926. err += ":\n '";
  2927. err += *str;
  2928. err += "'";
  2929. }
  2930. constant = constHolder->GetConstant(customAttribute->mCtorArgs[1]);
  2931. isError = constant->mBool;
  2932. }
  2933. BfError* error = NULL;
  2934. if (isError)
  2935. error = Fail(err, targetSrc);
  2936. else
  2937. error = Warn(0, err, targetSrc, false, true);
  2938. if (error != NULL)
  2939. _AddDeclarationMoreInfo();
  2940. }
  2941. customAttribute = customAttributes->Get(mCompiler->mErrorAttributeTypeDef);
  2942. if ((customAttribute != NULL) && (!customAttribute->mCtorArgs.IsEmpty()))
  2943. {
  2944. String err;
  2945. if (methodInstance != NULL)
  2946. err += StrFormat("Method error: '", MethodToString(methodInstance).c_str());
  2947. else
  2948. err += StrFormat("Type error: '", TypeToString(typeInstance, BfTypeNameFlag_UseUnspecializedGenericParamNames).c_str());
  2949. String* str = GetStringPoolString(customAttribute->mCtorArgs[0], constHolder);
  2950. if (str != NULL)
  2951. err += *str;
  2952. err += "'";
  2953. if (Fail(err, targetSrc) != NULL)
  2954. _AddDeclarationMoreInfo();
  2955. }
  2956. customAttribute = customAttributes->Get(mCompiler->mWarnAttributeTypeDef);
  2957. if ((customAttribute != NULL) && (!customAttribute->mCtorArgs.IsEmpty()) && (targetSrc != NULL))
  2958. {
  2959. String err;
  2960. if (methodInstance != NULL)
  2961. err += StrFormat("Method warning: '", MethodToString(methodInstance).c_str());
  2962. else
  2963. err += StrFormat("Type warning: '", TypeToString(typeInstance, BfTypeNameFlag_UseUnspecializedGenericParamNames).c_str());
  2964. String* str = GetStringPoolString(customAttribute->mCtorArgs[0], constHolder);
  2965. if (str != NULL)
  2966. err += *str;
  2967. err += "'";
  2968. if (Warn(0, err, targetSrc, false, true) != NULL)
  2969. _AddDeclarationMoreInfo();
  2970. }
  2971. }
  2972. void BfModule::CheckRangeError(BfType* type, BfAstNode* refNode)
  2973. {
  2974. if (mBfIRBuilder->mOpFailed)
  2975. Fail(StrFormat("Result out of range for type '%s'", TypeToString(type).c_str()), refNode);
  2976. }
  2977. void BfModule::FatalError(const StringImpl& error, const char* file, int line)
  2978. {
  2979. static bool sHadFatalError = false;
  2980. static bool sHadReentrancy = false;
  2981. if (sHadFatalError)
  2982. {
  2983. return;
  2984. sHadReentrancy = true;
  2985. }
  2986. sHadFatalError = true;
  2987. String fullError = error;
  2988. if (file != NULL)
  2989. fullError += StrFormat(" at %s:%d", file, line);
  2990. fullError += StrFormat("\nModule: %s", mModuleName.c_str());
  2991. if (mCurTypeInstance != NULL)
  2992. fullError += StrFormat("\nType: %s", TypeToString(mCurTypeInstance).c_str());
  2993. if (mCurMethodInstance != NULL)
  2994. fullError += StrFormat("\nMethod: %s", MethodToString(mCurMethodInstance).c_str());
  2995. if ((mCurFilePosition.mFileInstance != NULL) && (mCurFilePosition.mFileInstance->mParser != NULL))
  2996. fullError += StrFormat("\nSource Location: %s:%d", mCurFilePosition.mFileInstance->mParser->mFileName.c_str(), mCurFilePosition.mCurLine + 1);
  2997. if (sHadReentrancy)
  2998. fullError += "\nError had reentrancy";
  2999. BfpSystem_FatalError(fullError.c_str(), "FATAL MODULE ERROR");
  3000. }
  3001. void BfModule::NotImpl(BfAstNode* astNode)
  3002. {
  3003. Fail("INTERNAL ERROR: Not implemented", astNode);
  3004. }
  3005. bool BfModule::CheckAccessMemberProtection(BfProtection protection, BfTypeInstance* memberType)
  3006. {
  3007. bool allowPrivate = (memberType == mCurTypeInstance) || (IsInnerType(mCurTypeInstance, memberType));
  3008. if (!allowPrivate)
  3009. allowPrivate |= memberType->IsInterface();
  3010. bool allowProtected = allowPrivate;
  3011. //TODO: We had this commented out, but this makes accessing protected properties fail
  3012. if (mCurTypeInstance != NULL)
  3013. allowProtected |= TypeIsSubTypeOf(mCurTypeInstance, memberType->ToTypeInstance());
  3014. if (!CheckProtection(protection, memberType->mTypeDef, allowProtected, allowPrivate))
  3015. {
  3016. return false;
  3017. }
  3018. return true;
  3019. }
  3020. bool BfModule::CheckDefineMemberProtection(BfProtection protection, BfType* memberType)
  3021. {
  3022. // Use 'min' - exporting a 'public' from a 'private' class is really just 'private' still
  3023. protection = std::min(protection, mCurTypeInstance->mTypeDef->mProtection);
  3024. auto memberTypeInstance = memberType->ToTypeInstance();
  3025. if (memberTypeInstance == NULL)
  3026. {
  3027. auto underlyingType = memberType->GetUnderlyingType();
  3028. if (underlyingType != NULL)
  3029. return CheckDefineMemberProtection(protection, underlyingType);
  3030. return true;
  3031. }
  3032. if (memberTypeInstance->mTypeDef->mProtection < protection)
  3033. return false;
  3034. if (memberTypeInstance->IsGenericTypeInstance())
  3035. {
  3036. // When we're a generic struct, our data layout can depend on our generic parameters as well
  3037. auto genericTypeInstance = (BfTypeInstance*) memberTypeInstance;
  3038. for (auto typeGenericArg : genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments)
  3039. {
  3040. if (!CheckDefineMemberProtection(protection, typeGenericArg))
  3041. return false;
  3042. }
  3043. }
  3044. return true;
  3045. }
  3046. void BfModule::AddDependency(BfType* usedType, BfType* userType, BfDependencyMap::DependencyFlags flags, BfDepContext* depContext)
  3047. {
  3048. if (usedType == userType)
  3049. return;
  3050. if (((flags & BfDependencyMap::DependencyFlag_ConstValue) != 0) && (mContext->mCurTypeState != NULL) && (mContext->mCurTypeState->mResolveKind == BfTypeState::ResolveKind_FieldType))
  3051. {
  3052. // This can be an `int32[UsedType.cVal]` type reference
  3053. flags = (BfDependencyMap::DependencyFlags)(flags | BfDependencyMap::DependencyFlag_ValueTypeSizeDep);
  3054. }
  3055. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsAutocompleteMethod))
  3056. {
  3057. if (userType->IsMethodRef())
  3058. {
  3059. // We cannot short-circuit dependencies because of method group ref counting
  3060. }
  3061. else
  3062. return;
  3063. }
  3064. if (usedType->IsSpecializedByAutoCompleteMethod())
  3065. {
  3066. if ((flags & (BfDependencyMap::DependencyFlag_TypeGenericArg | BfDependencyMap::DependencyFlag_OuterType | BfDependencyMap::DependencyFlag_DerivedFrom)) == 0)
  3067. return;
  3068. }
  3069. // if (usedType->IsBoxed())
  3070. // {
  3071. // NOP;
  3072. // auto underlyingType = usedType->GetUnderlyingType()->ToTypeInstance();
  3073. // if ((underlyingType != NULL) && (underlyingType->IsInstanceOf(mCompiler->mSizedArrayTypeDef)))
  3074. // {
  3075. // BfLogSysM("AddDependency UsedType:%p UserType:%p Method:%p\n", usedType, userType, mCurMethodInstance);
  3076. // }
  3077. // }
  3078. // TODO: It seems this was bogus - it kept the root array from being marked as a dependency (for example)
  3079. // BfType* origUsedType = usedType;
  3080. bool isDataAccess = ((flags & (BfDependencyMap::DependencyFlag_ReadFields | BfDependencyMap::DependencyFlag_LocalUsage | BfDependencyMap::DependencyFlag_Allocates)) != 0);
  3081. // if (isDataAccess)
  3082. // {
  3083. // while (true)
  3084. // {
  3085. // if ((usedType->IsPointer()) || (usedType->IsRef()) || (usedType->IsSizedArray()))
  3086. // usedType = usedType->GetUnderlyingType();
  3087. // else if (usedType->IsArray())
  3088. // {
  3089. // usedType = ((BfTypeInstance*)usedType)->mGenericTypeInfo->mTypeGenericArguments[0];
  3090. // }
  3091. // else
  3092. // break;
  3093. // }
  3094. // }
  3095. if ((mCurMethodState != NULL) && (mCurMethodState->mHotDataReferenceBuilder != NULL) && (usedType != mCurTypeInstance) && (isDataAccess))
  3096. {
  3097. bool addType = true;
  3098. auto checkType = usedType;
  3099. PopulateType(checkType, BfPopulateType_Data);
  3100. if (checkType->IsValuelessType())
  3101. addType = false;
  3102. else if (checkType->IsPrimitiveType())
  3103. addType = false;
  3104. else
  3105. {
  3106. auto checkTypeInst = checkType->ToTypeInstance();
  3107. if (checkTypeInst == NULL)
  3108. {
  3109. addType = false;
  3110. }
  3111. else
  3112. {
  3113. if (TypeIsSubTypeOf(mCurTypeInstance, checkTypeInst))
  3114. addType = false;
  3115. }
  3116. }
  3117. if (addType)
  3118. {
  3119. auto checkTypeInst = checkType->ToTypeInstance();
  3120. if (checkTypeInst->mHotTypeData != NULL)
  3121. {
  3122. auto hotTypeVersion = checkTypeInst->mHotTypeData->GetLatestVersion();
  3123. BF_ASSERT(hotTypeVersion != NULL);
  3124. if (hotTypeVersion != NULL)
  3125. {
  3126. bool isAllocation = ((flags & BfDependencyMap::DependencyFlag_Allocates) != 0);
  3127. if (((flags & BfDependencyMap::DependencyFlag_LocalUsage) != 0) &&
  3128. (checkType->IsComposite()))
  3129. isAllocation = true;
  3130. if (isAllocation)
  3131. {
  3132. mCurMethodState->mHotDataReferenceBuilder->mAllocatedData.Add(hotTypeVersion);
  3133. }
  3134. else
  3135. mCurMethodState->mHotDataReferenceBuilder->mUsedData.Add(hotTypeVersion);
  3136. }
  3137. }
  3138. }
  3139. }
  3140. if ((!mCompiler->mIsResolveOnly) && (mIsReified))
  3141. {
  3142. auto usingModule = userType->GetModule();
  3143. BfModule* usedModule;
  3144. if (usedType->IsFunction())
  3145. {
  3146. if (mCompiler->mFunctionTypeDef != NULL)
  3147. {
  3148. auto functionType = ResolveTypeDef(mCompiler->mFunctionTypeDef)->ToTypeInstance();
  3149. usedModule = functionType->GetModule();
  3150. }
  3151. }
  3152. else
  3153. usedModule = usedType->GetModule();
  3154. if ((usingModule != NULL) && (!usingModule->mIsSpecialModule) &&
  3155. (usedModule != NULL) && (!usedModule->mIsSpecialModule))
  3156. {
  3157. if ((flags & ~(BfDependencyMap::DependencyFlag_OuterType)) == 0)
  3158. {
  3159. // Not a 'use' dependency
  3160. }
  3161. else
  3162. {
  3163. usingModule->mModuleRefs.Add(usedModule);
  3164. }
  3165. }
  3166. }
  3167. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodInfoEx != NULL) && (flags != BfDependencyMap::DependencyFlag_MethodGenericArg))
  3168. {
  3169. // When we are specializing a method, usage of that specialized type is already handled with DependencyFlag_MethodGenericArg
  3170. for (auto genericArg : mCurMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  3171. if (genericArg == usedType)
  3172. return;
  3173. }
  3174. auto depFlag = flags;
  3175. if ((flags & (BfDependencyMap::DependencyFlag_MethodGenericArg | BfDependencyMap::DependencyFlag_TypeGenericArg)) != 0)
  3176. {
  3177. if (usedType->IsDependendType())
  3178. {
  3179. // Cause a rebuild but not an outright deletion of the type
  3180. // We can only do this if the 'usedType' can actually hold the dependency which can actually trigger a deletion chain
  3181. depFlag = BfDependencyMap::DependencyFlag_GenericArgRef;
  3182. }
  3183. }
  3184. if (usedType->IsTypeAlias())
  3185. {
  3186. auto underlyingType = usedType->GetUnderlyingType();
  3187. if (underlyingType != NULL)
  3188. {
  3189. BfDepContext newDepContext;
  3190. if (depContext == NULL)
  3191. depContext = &newDepContext;
  3192. if (++depContext->mAliasDepth > 8)
  3193. {
  3194. if (!depContext->mDeepSeenAliases.Add(underlyingType))
  3195. return; // Circular!
  3196. }
  3197. AddDependency(underlyingType, userType, depFlag);
  3198. }
  3199. }
  3200. else if (!usedType->IsGenericTypeInstance())
  3201. {
  3202. auto underlyingType = usedType->GetUnderlyingType();
  3203. if (underlyingType != NULL)
  3204. AddDependency(underlyingType, userType, depFlag);
  3205. }
  3206. BfDependedType* checkDType = usedType->ToDependedType();
  3207. if (checkDType == NULL)
  3208. return;
  3209. if ((usedType->mRebuildFlags & BfTypeRebuildFlag_AwaitingReference) != 0)
  3210. mContext->MarkAsReferenced(checkDType);
  3211. #ifdef _DEBUG
  3212. // If a MethodRef depends ON US, that means it's a local method that we own
  3213. if (userType->IsMethodRef())
  3214. {
  3215. auto methodRefType = (BfMethodRefType*)userType;
  3216. BF_ASSERT(methodRefType->mOwner == checkDType);
  3217. }
  3218. #endif
  3219. if (!checkDType->mDependencyMap.AddUsedBy(userType, flags))
  3220. return;
  3221. if ((checkDType->IsGenericTypeInstance()) && (!userType->IsMethodRef()))
  3222. {
  3223. auto genericTypeInstance = (BfTypeInstance*) checkDType;
  3224. for (auto genericArg : genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments)
  3225. {
  3226. AddDependency(genericArg, userType, depFlag);
  3227. }
  3228. }
  3229. if (checkDType->IsTuple())
  3230. {
  3231. for (auto& field : checkDType->ToTypeInstance()->mFieldInstances)
  3232. {
  3233. if (field.mDataIdx != -1)
  3234. AddDependency(field.mResolvedType, userType, depFlag);
  3235. }
  3236. }
  3237. }
  3238. void BfModule::AddDependency(BfGenericParamInstance* genericParam, BfTypeInstance* usingType)
  3239. {
  3240. if ((genericParam->mExternType != NULL) && (!genericParam->mExternType->IsGenericParam()))
  3241. AddDependency(genericParam->mExternType, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  3242. for (auto constraintTypeInst : genericParam->mInterfaceConstraints)
  3243. AddDependency(constraintTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  3244. for (auto& operatorConstraint : genericParam->mOperatorConstraints)
  3245. {
  3246. if (operatorConstraint.mLeftType != NULL)
  3247. AddDependency(operatorConstraint.mLeftType, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  3248. if (operatorConstraint.mRightType != NULL)
  3249. AddDependency(operatorConstraint.mRightType, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  3250. }
  3251. if (genericParam->mTypeConstraint != NULL)
  3252. AddDependency(genericParam->mTypeConstraint, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  3253. }
  3254. void BfModule::AddCallDependency(BfMethodInstance* methodInstance, bool devirtualized)
  3255. {
  3256. if ((mCurMethodState != NULL) && (mCurMethodState->mHotDataReferenceBuilder != NULL))
  3257. {
  3258. if (methodInstance->mHotMethod == NULL)
  3259. CheckHotMethod(methodInstance, "");
  3260. BF_ASSERT(methodInstance->mHotMethod != NULL);
  3261. if (devirtualized)
  3262. mCurMethodState->mHotDataReferenceBuilder->mDevirtualizedCalledMethods.Add(methodInstance->mHotMethod);
  3263. else
  3264. mCurMethodState->mHotDataReferenceBuilder->mCalledMethods.Add(methodInstance->mHotMethod);
  3265. }
  3266. }
  3267. bool BfModule::IsAttribute(BfTypeInstance* typeInst)
  3268. {
  3269. auto checkTypeInst = typeInst;
  3270. while (checkTypeInst != NULL)
  3271. {
  3272. if (checkTypeInst->IsInstanceOf(mCompiler->mAttributeTypeDef))
  3273. return true;
  3274. checkTypeInst = checkTypeInst->mBaseType;
  3275. }
  3276. return false;
  3277. }
  3278. void BfModule::PopulateGlobalContainersList(const BfGlobalLookup& globalLookup)
  3279. {
  3280. if (mContext->mCurTypeState == NULL)
  3281. return;
  3282. BP_ZONE("PopulateGlobalContainersList");
  3283. BfTypeDef* userTypeDef = mContext->mCurTypeState->mCurTypeDef;
  3284. if ((userTypeDef == NULL) && (mCurMethodInstance != NULL))
  3285. userTypeDef = mCurMethodInstance->mMethodDef->mDeclaringType;
  3286. if (userTypeDef == NULL)
  3287. userTypeDef = mCurTypeInstance->mTypeDef;
  3288. if (mContext->mCurTypeState->mGlobalContainerCurUserTypeDef != userTypeDef)
  3289. {
  3290. mContext->mCurTypeState->mGlobalContainers.Clear();
  3291. for (int namespaceIdx = -1; namespaceIdx < (int)userTypeDef->mNamespaceSearch.size(); namespaceIdx++)
  3292. {
  3293. BfAtomComposite findStr;
  3294. if (namespaceIdx != -1)
  3295. findStr.Reference(userTypeDef->mNamespaceSearch[namespaceIdx]);
  3296. auto typeDefItr = mSystem->mTypeDefs.TryGet(findStr);
  3297. while (typeDefItr)
  3298. {
  3299. auto typeDef = *typeDefItr;
  3300. if ((typeDef->mFullName == findStr) && (typeDef->mIsCombinedPartial) && (typeDef->IsGlobalsContainer()))
  3301. {
  3302. if (typeDef->mProject->ContainsReference(typeDef->mProject))
  3303. {
  3304. BfGlobalContainerEntry globalEntry;
  3305. globalEntry.mTypeDef = typeDef;
  3306. globalEntry.mTypeInst = NULL;
  3307. typeDef->PopulateMemberSets();
  3308. mContext->mCurTypeState->mGlobalContainers.Add(globalEntry);
  3309. }
  3310. }
  3311. else if (!typeDef->mIsPartial)
  3312. {
  3313. //break;
  3314. }
  3315. typeDefItr.MoveToNextHashMatch();
  3316. }
  3317. }
  3318. mContext->mCurTypeState->mGlobalContainerCurUserTypeDef = userTypeDef;
  3319. }
  3320. // Only create actual typeInst when we have an applicable member. This helps in keeping unused globals from
  3321. // reifing types
  3322. for (auto& globalEntry : mContext->mCurTypeState->mGlobalContainers)
  3323. {
  3324. if (globalEntry.mTypeInst == NULL)
  3325. {
  3326. bool include = false;
  3327. if (globalLookup.mKind == BfGlobalLookup::Kind_All)
  3328. include = true;
  3329. else if (globalLookup.mKind == BfGlobalLookup::Kind_Field)
  3330. {
  3331. if (globalEntry.mTypeDef->mFieldSet.ContainsWith(globalLookup.mName))
  3332. include = true;
  3333. if (globalEntry.mTypeDef->mPropertySet.ContainsWith(globalLookup.mName))
  3334. include = true;
  3335. }
  3336. else if (globalLookup.mKind == BfGlobalLookup::Kind_Method)
  3337. {
  3338. if (globalEntry.mTypeDef->mMethodSet.ContainsWith(globalLookup.mName))
  3339. include = true;
  3340. }
  3341. if (include)
  3342. {
  3343. auto type = ResolveTypeDef(globalEntry.mTypeDef);
  3344. if (type != NULL)
  3345. globalEntry.mTypeInst = type->ToTypeInstance();
  3346. }
  3347. }
  3348. }
  3349. }
  3350. BfStaticSearch* BfModule::GetStaticSearch()
  3351. {
  3352. auto activeTypeDef = GetActiveTypeDef();
  3353. BfStaticSearch* staticSearch = NULL;
  3354. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->mStaticSearchMap.TryGetValue(activeTypeDef, &staticSearch)))
  3355. return staticSearch;
  3356. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mStaticSearchMap.TryGetValue(activeTypeDef, &staticSearch)))
  3357. return staticSearch;
  3358. return NULL;
  3359. }
  3360. BfInternalAccessSet* BfModule::GetInternalAccessSet()
  3361. {
  3362. auto activeTypeDef = GetActiveTypeDef();
  3363. BfInternalAccessSet* internalAccessSet = NULL;
  3364. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->mInternalAccessMap.TryGetValue(activeTypeDef, &internalAccessSet)))
  3365. return internalAccessSet;
  3366. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mInternalAccessMap.TryGetValue(activeTypeDef, &internalAccessSet)))
  3367. return internalAccessSet;
  3368. return NULL;
  3369. }
  3370. bool BfModule::CheckInternalProtection(BfTypeDef* usingTypeDef)
  3371. {
  3372. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsSpecializedType()))
  3373. return true;
  3374. if ((mCurMethodInstance != NULL) &&
  3375. ((mCurMethodInstance->mIsUnspecializedVariation) || (mCurMethodInstance->IsSpecializedGenericMethod())))
  3376. return true;
  3377. auto internalAccessSet = GetInternalAccessSet();
  3378. if (internalAccessSet == NULL)
  3379. return false;
  3380. for (auto& nameComposite : internalAccessSet->mNamespaces)
  3381. {
  3382. if (usingTypeDef->mNamespace.StartsWith(nameComposite))
  3383. return true;
  3384. }
  3385. for (auto internalType : internalAccessSet->mTypes)
  3386. {
  3387. auto checkTypeDef = usingTypeDef->GetDefinition();
  3388. while (checkTypeDef != NULL)
  3389. {
  3390. if (checkTypeDef == internalType->mTypeDef->GetDefinition())
  3391. return true;
  3392. checkTypeDef = checkTypeDef->mOuterType;
  3393. }
  3394. }
  3395. return false;
  3396. }
  3397. void PrintUsers(llvm::MDNode* md);
  3398. BfModuleOptions BfModule::GetModuleOptions()
  3399. {
  3400. if (mIsScratchModule)
  3401. return BfModuleOptions();
  3402. if (mModuleOptions != NULL)
  3403. return *mModuleOptions;
  3404. BfModuleOptions moduleOptions;
  3405. moduleOptions.mEmitDebugInfo = mCompiler->mOptions.mEmitDebugInfo ? 1 : mCompiler->mOptions.mEmitLineInfo ? 2 : 0;
  3406. if (mProject != NULL)
  3407. {
  3408. moduleOptions.mSIMDSetting = mProject->mCodeGenOptions.mSIMDSetting;
  3409. moduleOptions.mOptLevel = mProject->mCodeGenOptions.mOptLevel;
  3410. }
  3411. auto headModule = this;
  3412. while (headModule->mParentModule != NULL)
  3413. headModule = headModule->mParentModule;
  3414. BF_ASSERT((headModule->mOwnedTypeInstances.size() > 0) || (mModuleName == "vdata") || mIsSpecialModule);
  3415. if (headModule->mOwnedTypeInstances.size() > 0)
  3416. {
  3417. auto typeInst = headModule->mOwnedTypeInstances[0];
  3418. if (typeInst->mTypeOptionsIdx == -2)
  3419. PopulateType(typeInst);
  3420. if (typeInst->mTypeOptionsIdx != -1)
  3421. {
  3422. auto typeOptions = mSystem->GetTypeOptions(typeInst->mTypeOptionsIdx);
  3423. moduleOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)moduleOptions.mSIMDSetting, typeOptions->mSIMDSetting);
  3424. moduleOptions.mEmitDebugInfo = BfTypeOptions::Apply(moduleOptions.mEmitDebugInfo, typeOptions->mEmitDebugInfo);
  3425. moduleOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)moduleOptions.mOptLevel, (int)typeOptions->mOptimizationLevel);
  3426. }
  3427. }
  3428. return moduleOptions;
  3429. }
  3430. BfCheckedKind BfModule::GetDefaultCheckedKind()
  3431. {
  3432. if ((mCurMethodState != NULL) && (mCurMethodState->mDisableChecks))
  3433. return BfCheckedKind_Unchecked;
  3434. bool runtimeChecks = mCompiler->mOptions.mRuntimeChecks;
  3435. auto typeOptions = GetTypeOptions();
  3436. if (typeOptions != NULL)
  3437. runtimeChecks = typeOptions->Apply(runtimeChecks, BfOptionFlags_RuntimeChecks);
  3438. return runtimeChecks ? BfCheckedKind_Checked : BfCheckedKind_Unchecked;
  3439. }
  3440. void BfModule::AddFailType(BfTypeInstance* typeInstance)
  3441. {
  3442. BF_ASSERT(typeInstance != NULL);
  3443. if ((typeInstance->mRebuildFlags & BfTypeRebuildFlag_InFailTypes) != 0)
  3444. return;
  3445. typeInstance->mRebuildFlags = (BfTypeRebuildFlags)(typeInstance->mRebuildFlags | BfTypeRebuildFlag_InFailTypes);
  3446. mContext->mFailTypes.Add(typeInstance);
  3447. }
  3448. void BfModule::DeferRebuildType(BfTypeInstance* typeInstance)
  3449. {
  3450. if ((typeInstance->mRebuildFlags & BfTypeRebuildFlag_RebuildQueued) != 0)
  3451. return;
  3452. mCompiler->mHasQueuedTypeRebuilds = true;
  3453. typeInstance->mRebuildFlags = (BfTypeRebuildFlags)(typeInstance->mRebuildFlags | BfTypeRebuildFlag_RebuildQueued);
  3454. AddFailType(typeInstance);
  3455. }
  3456. void BfModule::CheckAddFailType()
  3457. {
  3458. //TODO: We removed this line, because failures in resolve-only generic method can occur in non-owning modules
  3459. // but we still need to add the owning type to the FailTypes list
  3460. //.. OLD:
  3461. // While we're inlining, it's possible that mCurTypeInstance belongs to another module, ignore it
  3462. /*if (mCurTypeInstance->mModule != this)
  3463. return;*/
  3464. // Using mHadBuildWarning to insert into mFailTypes is our core of our strategy for reasserting
  3465. // warnings on rebuilds where otherwise the warnings wouldn't be generated because no code was
  3466. // being recompiled. This forces types with warnings to be recompiled.
  3467. // We had this 'mIsResolveOnly' check for speed in resolveOnly, but we removed it so the IDE can be
  3468. // constantly warning-aware
  3469. if ((mHadBuildError) ||
  3470. (mHadBuildWarning /*&& !mCompiler->mIsResolveOnly*/))
  3471. {
  3472. //mContext->mFailTypes.Add(mCurTypeInstance);
  3473. }
  3474. }
  3475. void BfModule::MarkDerivedDirty(BfTypeInstance* typeInst)
  3476. {
  3477. if (!mCompiler->IsHotCompile())
  3478. return;
  3479. typeInst->mDirty = true;
  3480. for (auto& dep : typeInst->mDependencyMap)
  3481. {
  3482. auto depType = dep.mKey;
  3483. auto depFlags = dep.mValue.mFlags;
  3484. if ((depFlags & BfDependencyMap::DependencyFlag_DerivedFrom) != 0)
  3485. {
  3486. MarkDerivedDirty(depType->ToTypeInstance());
  3487. }
  3488. }
  3489. }
  3490. void BfModule::CreateStaticField(BfFieldInstance* fieldInstance, bool isThreadLocal)
  3491. {
  3492. auto fieldType = fieldInstance->GetResolvedType();
  3493. auto field = fieldInstance->GetFieldDef();
  3494. if (fieldType->IsVar())
  3495. return;
  3496. BfIRValue initValue;
  3497. if (field->mIsConst)
  3498. {
  3499. if (fieldType->IsPointer())
  3500. fieldType = fieldType->GetUnderlyingType();
  3501. }
  3502. BfIRStorageKind storageKind = BfIRStorageKind_Normal;
  3503. if ((fieldInstance->mCustomAttributes != NULL) && (fieldInstance->mCustomAttributes->Get(mCompiler->mExportAttributeTypeDef)))
  3504. storageKind = BfIRStorageKind_Export;
  3505. else if ((fieldInstance->mCustomAttributes != NULL) && (fieldInstance->mCustomAttributes->Get(mCompiler->mImportAttributeTypeDef)))
  3506. storageKind = BfIRStorageKind_Import;
  3507. if ((!field->mIsExtern) && (storageKind != BfIRStorageKind_Import))
  3508. initValue = GetDefaultValue(fieldType);
  3509. if (fieldInstance->mOwner->IsUnspecializedType())
  3510. {
  3511. // Placeholder
  3512. auto ptrVal = CreatePointerType(fieldType);
  3513. mStaticFieldRefs[fieldInstance] = GetDefaultValue(ptrVal);
  3514. }
  3515. else
  3516. {
  3517. BfLogSysM("Creating static field Module:%p Type:%p\n", this, fieldType);
  3518. StringT<4096> staticVarName;
  3519. BfMangler::Mangle(staticVarName, mCompiler->GetMangleKind(), fieldInstance);
  3520. if ((!fieldType->IsValuelessType()) && (!staticVarName.StartsWith("#")))
  3521. {
  3522. BfIRType irType;
  3523. if (fieldInstance->IsAppendedObject())
  3524. {
  3525. irType = mBfIRBuilder->MapTypeInst(fieldType->ToTypeInstance(), BfIRPopulateType_Eventually_Full);
  3526. initValue = mBfIRBuilder->CreateConstAggZero(irType);
  3527. }
  3528. else
  3529. irType = mBfIRBuilder->MapType(fieldType, BfIRPopulateType_Eventually_Full);
  3530. BfIRValue globalVar = mBfIRBuilder->CreateGlobalVariable(
  3531. irType,
  3532. false,
  3533. BfIRLinkageType_External,
  3534. initValue,
  3535. staticVarName,
  3536. isThreadLocal);
  3537. mBfIRBuilder->GlobalVar_SetAlignment(globalVar, fieldType->mAlign);
  3538. if (storageKind != BfIRStorageKind_Normal)
  3539. mBfIRBuilder->GlobalVar_SetStorageKind(globalVar, storageKind);
  3540. BF_ASSERT(globalVar);
  3541. mStaticFieldRefs[fieldInstance] = globalVar;
  3542. }
  3543. }
  3544. }
  3545. void BfModule::ResolveConstField(BfTypeInstance* typeInstance, BfFieldInstance* fieldInstance, BfFieldDef* fieldDef, bool forceResolve)
  3546. {
  3547. bool autoCompleteOnly = mCompiler->IsAutocomplete();
  3548. BfType* fieldType = NULL;
  3549. if (fieldInstance != NULL)
  3550. {
  3551. fieldType = fieldInstance->GetResolvedType();
  3552. if (fieldType == NULL)
  3553. fieldType = ResolveTypeRef(fieldDef->mTypeRef);
  3554. }
  3555. else
  3556. {
  3557. BF_ASSERT(mCompiler->IsAutocomplete());
  3558. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3559. if ((typeInstance->IsEnum()) && (fieldDef->mTypeRef == NULL))
  3560. {
  3561. fieldType = typeInstance;
  3562. }
  3563. else
  3564. {
  3565. auto isLet = (fieldDef->mTypeRef != NULL) && (fieldDef->mTypeRef->IsExact<BfLetTypeReference>());
  3566. auto isVar = (fieldDef->mTypeRef != NULL) && (fieldDef->mTypeRef->IsExact<BfVarTypeReference>());
  3567. if (isLet || isVar)
  3568. fieldType = GetPrimitiveType(BfTypeCode_Var);
  3569. else
  3570. fieldType = ResolveTypeRef(fieldDef->mTypeRef, BfPopulateType_Identity, BfResolveTypeRefFlag_AllowInferredSizedArray);
  3571. if (fieldType == NULL)
  3572. fieldType = mContext->mBfObjectType;
  3573. }
  3574. }
  3575. if ((fieldInstance != NULL) && (fieldInstance->mConstIdx != -1) && (!forceResolve))
  3576. return;
  3577. if (mContext->mFieldResolveReentrys.size() > 1)
  3578. {
  3579. if (mContext->mFieldResolveReentrys.IndexOf(fieldInstance, 1) != -1)
  3580. {
  3581. String failStr = "Circular data reference detected between the following fields:";
  3582. for (int i = 1; i < (int)mContext->mFieldResolveReentrys.size(); i++)
  3583. {
  3584. if (i > 1)
  3585. failStr += ",";
  3586. failStr += "\n '" + TypeToString(typeInstance) + "." + mContext->mFieldResolveReentrys[i]->GetFieldDef()->mName + "'";
  3587. }
  3588. BfError* err = Fail(failStr, fieldDef->mFieldDeclaration);
  3589. if (err)
  3590. err->mIsPersistent = true;
  3591. return;
  3592. }
  3593. }
  3594. mContext->mFieldResolveReentrys.push_back(fieldInstance);
  3595. AutoPopBack<decltype (mContext->mFieldResolveReentrys)> popTypeResolveReentry(&mContext->mFieldResolveReentrys);
  3596. if (fieldInstance == NULL)
  3597. popTypeResolveReentry.Pop();
  3598. auto typeDef = typeInstance->mTypeDef;
  3599. BfIRValue constValue;
  3600. if (fieldDef->mIsExtern)
  3601. {
  3602. if (!fieldDef->mTypeRef->IsA<BfPointerTypeRef>())
  3603. {
  3604. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3605. Fail("Extern consts must be pointer types", fieldDef->mTypeRef);
  3606. }
  3607. if (fieldDef->GetInitializer() != NULL)
  3608. {
  3609. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3610. Fail("Extern consts cannot have initializers", fieldDef->GetNameNode());
  3611. }
  3612. }
  3613. else if (fieldDef->GetInitializer() == NULL)
  3614. {
  3615. if (fieldDef->IsEnumCaseEntry())
  3616. {
  3617. if (typeInstance->IsTypedPrimitive())
  3618. {
  3619. BfFieldInstance* prevFieldInstance = NULL;
  3620. for (int i = fieldDef->mIdx - 1; i >= 0; i--)
  3621. {
  3622. BfFieldInstance* checkFieldInst = &typeInstance->mFieldInstances[i];
  3623. if (checkFieldInst->GetFieldDef()->IsEnumCaseEntry())
  3624. {
  3625. prevFieldInstance = checkFieldInst;
  3626. break;
  3627. }
  3628. }
  3629. if (prevFieldInstance == NULL)
  3630. constValue = GetConstValue(0, typeInstance);
  3631. else
  3632. {
  3633. ResolveConstField(typeInstance, prevFieldInstance, prevFieldInstance->GetFieldDef());
  3634. if (prevFieldInstance->mConstIdx == -1)
  3635. {
  3636. if (!mCompiler->IsAutocomplete())
  3637. AssertErrorState();
  3638. constValue = GetConstValue(0, typeInstance);
  3639. }
  3640. else
  3641. {
  3642. auto prevConstant = ConstantToCurrent(typeInstance->mConstHolder->GetConstantById(prevFieldInstance->mConstIdx), typeInstance->mConstHolder, typeInstance);
  3643. constValue = mBfIRBuilder->CreateAdd(prevConstant, GetConstValue(1, typeInstance));
  3644. }
  3645. }
  3646. }
  3647. }
  3648. else
  3649. {
  3650. Fail("Const requires initializer", fieldDef->GetNameNode());
  3651. }
  3652. }
  3653. else if (mBfIRBuilder != NULL)
  3654. {
  3655. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3656. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  3657. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL);
  3658. BfMethodState methodState;
  3659. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  3660. methodState.mTempKind = BfMethodState::TempKind_Static;
  3661. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  3662. if ((fieldType->IsVar()) || (fieldType->IsUndefSizedArray()))
  3663. {
  3664. auto initValue = GetFieldInitializerValue(fieldInstance, fieldDef->GetInitializer(), fieldDef, fieldType);
  3665. if (!initValue)
  3666. {
  3667. AssertErrorState();
  3668. initValue = GetDefaultTypedValue(mContext->mBfObjectType);
  3669. }
  3670. if (fieldInstance != NULL)
  3671. {
  3672. if (fieldType->IsUndefSizedArray())
  3673. {
  3674. if ((initValue.mType->IsSizedArray()) && (initValue.mType->GetUnderlyingType() == fieldType->GetUnderlyingType()))
  3675. {
  3676. fieldInstance->mResolvedType = initValue.mType;
  3677. }
  3678. }
  3679. else
  3680. fieldInstance->mResolvedType = initValue.mType;
  3681. }
  3682. constValue = initValue.mValue;
  3683. }
  3684. else
  3685. {
  3686. auto uncastedInitValue = GetFieldInitializerValue(fieldInstance, fieldDef->GetInitializer(), fieldDef, fieldType);
  3687. constValue = uncastedInitValue.mValue;
  3688. }
  3689. if ((mCurTypeInstance->IsPayloadEnum()) && (fieldDef->IsEnumCaseEntry()))
  3690. {
  3691. // Illegal
  3692. constValue = BfIRValue();
  3693. }
  3694. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  3695. }
  3696. if (fieldInstance != NULL)
  3697. {
  3698. fieldType = fieldInstance->GetResolvedType();
  3699. if ((fieldType == NULL) || (fieldType->IsVar()))
  3700. {
  3701. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  3702. AssertErrorState();
  3703. // Default const type is 'int'
  3704. BfTypedValue initValue = GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr));
  3705. if (fieldInstance != NULL)
  3706. {
  3707. fieldInstance->mResolvedType = initValue.mType;
  3708. }
  3709. constValue = initValue.mValue;
  3710. }
  3711. if ((constValue) && (fieldInstance->mConstIdx == -1))
  3712. {
  3713. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3714. CurrentAddToConstHolder(constValue);
  3715. fieldInstance->mConstIdx = constValue.mId;
  3716. }
  3717. }
  3718. }
  3719. BfType* BfModule::ResolveVarFieldType(BfTypeInstance* typeInstance, BfFieldInstance* fieldInstance, BfFieldDef* field)
  3720. {
  3721. bool isDeclType = (field->mFieldDeclaration != NULL) && BfNodeDynCastExact<BfExprModTypeRef>(field->mTypeRef) != NULL;
  3722. auto fieldType = fieldInstance->GetResolvedType();
  3723. if ((field->mIsConst) && (!isDeclType))
  3724. {
  3725. ResolveConstField(typeInstance, fieldInstance, field);
  3726. return fieldInstance->GetResolvedType();
  3727. }
  3728. bool staticOnly = (field->mIsStatic) && (!isDeclType);
  3729. if (!fieldInstance->mIsInferredType)
  3730. return fieldType;
  3731. if ((!fieldType->IsVar()) && (!fieldType->IsUndefSizedArray()))
  3732. return fieldType;
  3733. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3734. BfTypeState typeState(mCurTypeInstance, mContext->mCurTypeState);
  3735. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState, mContext->mCurTypeState->mType != typeInstance);
  3736. auto typeDef = typeInstance->mTypeDef;
  3737. if ((!field->mIsStatic) && (typeDef->mIsStatic))
  3738. {
  3739. AssertErrorState();
  3740. return fieldType;
  3741. }
  3742. bool hadInferenceCycle = false;
  3743. if (mContext->mFieldResolveReentrys.size() > 1)
  3744. {
  3745. if (mContext->mFieldResolveReentrys.IndexOf(fieldInstance, 1) != -1)
  3746. {
  3747. for (int i = 1; i < (int)mContext->mFieldResolveReentrys.size(); i++)
  3748. {
  3749. auto fieldInst = mContext->mFieldResolveReentrys[i];
  3750. auto fieldDef = fieldInst->GetFieldDef();
  3751. auto fieldOwner = fieldInst->mOwner;
  3752. auto fieldModule = fieldOwner->mModule;
  3753. SetAndRestoreValue<bool> prevIgnoreError(fieldModule->mIgnoreErrors, false);
  3754. fieldModule->Fail(StrFormat("Field '%s.%s' creates a type inference cycle", TypeToString(fieldOwner).c_str(), fieldDef->mName.c_str()), fieldDef->mTypeRef, true);
  3755. }
  3756. return fieldType;
  3757. }
  3758. }
  3759. mContext->mFieldResolveReentrys.push_back(fieldInstance);
  3760. AutoPopBack<decltype (mContext->mFieldResolveReentrys)> popTypeResolveReentry(&mContext->mFieldResolveReentrys);
  3761. SetAndRestoreValue<bool> prevResolvingVar(typeInstance->mResolvingVarField, true);
  3762. SetAndRestoreValue<bool> prevCtxResolvingVar(mContext->mResolvingVarField, true);
  3763. if ((field->GetInitializer() == NULL) && (!isDeclType))
  3764. {
  3765. if ((field->mTypeRef->IsA<BfVarTypeReference>()) || (field->mTypeRef->IsA<BfLetTypeReference>()))
  3766. Fail("Implicitly-typed fields must be initialized", field->GetRefNode());
  3767. return fieldType;
  3768. }
  3769. BfType* resolvedType = NULL;
  3770. if (!hadInferenceCycle)
  3771. {
  3772. BfTypeState typeState;
  3773. typeState.mPrevState = mContext->mCurTypeState;
  3774. typeState.mType = typeInstance;
  3775. typeState.mCurFieldDef = field;
  3776. typeState.mResolveKind = BfTypeState::ResolveKind_ResolvingVarType;
  3777. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  3778. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  3779. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL/*ctorMethod.mMethodInstance*/);
  3780. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  3781. BfMethodState methodState;
  3782. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  3783. methodState.mTempKind = staticOnly ? BfMethodState::TempKind_Static : BfMethodState::TempKind_NonStatic;
  3784. if (!staticOnly)
  3785. {
  3786. //BfLocalVariable localVar;
  3787. //methodState.mLocals.push_back(localVar);
  3788. }
  3789. if (isDeclType)
  3790. {
  3791. auto fieldDef = fieldInstance->GetFieldDef();
  3792. resolvedType = ResolveTypeRef(fieldDef->mTypeRef, BfPopulateType_Identity);
  3793. }
  3794. else
  3795. {
  3796. BfTypedValue valueFromExpr;
  3797. valueFromExpr = GetFieldInitializerValue(fieldInstance);
  3798. FixIntUnknown(valueFromExpr);
  3799. if (fieldType->IsUndefSizedArray())
  3800. {
  3801. if ((valueFromExpr.mType != NULL) && (valueFromExpr.mType->IsSizedArray()) && (valueFromExpr.mType->GetUnderlyingType() == fieldType->GetUnderlyingType()))
  3802. resolvedType = valueFromExpr.mType;
  3803. }
  3804. else
  3805. resolvedType = valueFromExpr.mType;
  3806. }
  3807. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  3808. }
  3809. if (resolvedType == NULL)
  3810. return fieldType;
  3811. fieldInstance->SetResolvedType(resolvedType);
  3812. if (field->mIsStatic)
  3813. {
  3814. }
  3815. else if (fieldInstance->mDataIdx >= 0)
  3816. {
  3817. }
  3818. else
  3819. {
  3820. BF_ASSERT(typeInstance->IsIncomplete());
  3821. }
  3822. return resolvedType;
  3823. }
  3824. void BfModule::MarkFieldInitialized(BfFieldInstance* fieldInstance)
  3825. {
  3826. BF_ASSERT(fieldInstance->mOwner == mCurTypeInstance);
  3827. auto fieldType = fieldInstance->GetResolvedType();
  3828. if ((fieldInstance->mMergedDataIdx != -1) && (mCurMethodState != NULL))
  3829. {
  3830. int fieldIdx = 0;
  3831. int fieldCount = 0;
  3832. fieldInstance->GetDataRange(fieldIdx, fieldCount);
  3833. fieldIdx--;
  3834. int count = fieldCount;
  3835. if (fieldIdx == -1)
  3836. count = 1;
  3837. //TODO: Under what circumstances could 'thisVariable' be NULL?
  3838. auto thisVariable = GetThisVariable();
  3839. if (thisVariable != NULL)
  3840. {
  3841. for (int i = 0; i < count; i++)
  3842. mCurMethodState->LocalDefined(thisVariable, fieldIdx + i);
  3843. }
  3844. }
  3845. }
  3846. bool BfModule::IsThreadLocal(BfFieldInstance * fieldInstance)
  3847. {
  3848. if (fieldInstance->mCustomAttributes == NULL)
  3849. return false;
  3850. auto fieldDef = fieldInstance->GetFieldDef();
  3851. if (!fieldDef->mIsStatic)
  3852. return false;
  3853. bool isThreadLocal = false;
  3854. if (fieldInstance->mCustomAttributes != NULL)
  3855. {
  3856. for (auto customAttr : fieldInstance->mCustomAttributes->mAttributes)
  3857. {
  3858. if (customAttr.mType->ToTypeInstance()->IsInstanceOf(mCompiler->mThreadStaticAttributeTypeDef))
  3859. return true;
  3860. }
  3861. }
  3862. return false;
  3863. }
  3864. BfTypedValue BfModule::GetFieldInitializerValue(BfFieldInstance* fieldInstance, BfExpression* initializer, BfFieldDef* fieldDef, BfType* fieldType, bool doStore)
  3865. {
  3866. if (fieldDef == NULL)
  3867. fieldDef = fieldInstance->GetFieldDef();
  3868. if (fieldType == NULL)
  3869. fieldType = fieldInstance->GetResolvedType();
  3870. if (initializer == NULL)
  3871. {
  3872. if (fieldDef == NULL)
  3873. return BfTypedValue();
  3874. initializer = fieldDef->GetInitializer();
  3875. }
  3876. BfTypedValue staticVarRef;
  3877. BfTypedValue result;
  3878. if (initializer == NULL)
  3879. {
  3880. result = GetDefaultTypedValue(fieldInstance->mResolvedType);
  3881. }
  3882. else
  3883. {
  3884. if (mCompiler->mIsResolveOnly)
  3885. {
  3886. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(initializer))
  3887. {
  3888. sourceClassifier->SetElementType(initializer, BfSourceElementType_Normal);
  3889. sourceClassifier->VisitChildNoRef(initializer);
  3890. }
  3891. }
  3892. if ((mCurTypeInstance->IsPayloadEnum()) && (fieldDef->IsEnumCaseEntry()))
  3893. {
  3894. Fail("Enums with payloads cannot have explicitly-defined discriminators", initializer);
  3895. BfConstResolver constResolver(this);
  3896. constResolver.Resolve(initializer);
  3897. return GetDefaultTypedValue(fieldType);
  3898. }
  3899. else if (mCurTypeInstance->IsUnspecializedTypeVariation())
  3900. {
  3901. return GetDefaultTypedValue(fieldType);
  3902. }
  3903. else if (fieldDef->mIsConst)
  3904. {
  3905. int ceExecuteId = -1;
  3906. if (mCompiler->mCeMachine != NULL)
  3907. ceExecuteId = mCompiler->mCeMachine->mExecuteId;
  3908. BfTypeState typeState;
  3909. typeState.mType = mCurTypeInstance;
  3910. typeState.mCurTypeDef = fieldDef->mDeclaringType;
  3911. typeState.mCurFieldDef = fieldDef;
  3912. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  3913. BfConstResolver constResolver(this);
  3914. if (fieldType->IsVar())
  3915. return constResolver.Resolve(initializer);
  3916. else
  3917. {
  3918. BfConstResolveFlags resolveFlags = BfConstResolveFlag_None;
  3919. if ((mCompiler->mResolvePassData != NULL) && (mCurTypeInstance->IsEnum()) && (fieldDef->IsEnumCaseEntry()) &&
  3920. (mCompiler->mResolvePassData->mAutoCompleteTempTypes.Contains(fieldDef->mDeclaringType)))
  3921. {
  3922. // We avoid doing the cast here because the value we're typing may not be in the range of the current
  3923. // auto-created underlying type and it will cause an 'error flash'. We defer errors until the full resolve for that purpose
  3924. resolveFlags = BfConstResolveFlag_NoCast;
  3925. }
  3926. UpdateSrcPos(initializer);
  3927. auto result = constResolver.Resolve(initializer, fieldType, resolveFlags);
  3928. if ((mCompiler->mCeMachine != NULL) && (fieldInstance != NULL))
  3929. {
  3930. if (mCompiler->mCeMachine->mExecuteId != ceExecuteId)
  3931. fieldInstance->mHadConstEval = true;
  3932. }
  3933. return result;
  3934. }
  3935. }
  3936. BfExprEvaluator exprEvaluator(this);
  3937. if (doStore)
  3938. {
  3939. staticVarRef = ReferenceStaticField(fieldInstance);
  3940. exprEvaluator.mReceivingValue = &staticVarRef;
  3941. }
  3942. if (fieldType->IsVar())
  3943. result = CreateValueFromExpression(exprEvaluator, initializer, NULL, (BfEvalExprFlags)(BfEvalExprFlags_NoValueAddr | BfEvalExprFlags_FieldInitializer));
  3944. else
  3945. result = CreateValueFromExpression(exprEvaluator, initializer, fieldType, (BfEvalExprFlags)(BfEvalExprFlags_NoValueAddr | BfEvalExprFlags_FieldInitializer));
  3946. if (doStore)
  3947. {
  3948. if (exprEvaluator.mReceivingValue == NULL)
  3949. doStore = false; // Already stored
  3950. }
  3951. }
  3952. if (fieldInstance != NULL)
  3953. MarkFieldInitialized(fieldInstance);
  3954. if ((doStore) && (result))
  3955. {
  3956. if (fieldInstance->mResolvedType->IsUndefSizedArray())
  3957. {
  3958. if ((!mBfIRBuilder->mIgnoreWrites) && (!mCompiler->mFastFinish))
  3959. AssertErrorState();
  3960. }
  3961. else
  3962. {
  3963. result = LoadValue(result);
  3964. if (!result.mType->IsValuelessType())
  3965. mBfIRBuilder->CreateAlignedStore(result.mValue, staticVarRef.mValue, result.mType->mAlign);
  3966. }
  3967. }
  3968. return result;
  3969. }
  3970. void BfModule::AppendedObjectInit(BfFieldInstance* fieldInst)
  3971. {
  3972. BfExprEvaluator exprEvaluator(this);
  3973. bool failed = false;
  3974. auto fieldDef = fieldInst->GetFieldDef();
  3975. auto initializer = fieldDef->GetInitializer();
  3976. BfResolvedArgs resolvedArgs;
  3977. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(initializer))
  3978. {
  3979. bool isDot = false;
  3980. if (auto memberRefExpr = BfNodeDynCast<BfMemberReferenceExpression>(invocationExpr->mTarget))
  3981. isDot = (memberRefExpr->mTarget == NULL) && (memberRefExpr->mMemberName == NULL);
  3982. if (!isDot)
  3983. {
  3984. auto resolvedType = ResolveTypeRef(invocationExpr->mTarget, {});
  3985. if ((resolvedType == NULL) || (resolvedType != fieldInst->mResolvedType))
  3986. failed = true;
  3987. }
  3988. SetAndRestoreValue<BfType*> prevExpectingType(exprEvaluator.mExpectingType, fieldInst->mResolvedType);
  3989. resolvedArgs.Init(invocationExpr->mOpenParen, &invocationExpr->mArguments, &invocationExpr->mCommas, invocationExpr->mCloseParen);
  3990. exprEvaluator.ResolveArgValues(resolvedArgs, BfResolveArgsFlag_DeferParamEval);
  3991. }
  3992. else if (initializer != NULL)
  3993. {
  3994. GetFieldInitializerValue(fieldInst);
  3995. failed = true;
  3996. }
  3997. if (failed)
  3998. Fail("Append fields can only be initialized with a call to their constructor", initializer);
  3999. auto intType = GetPrimitiveType(BfTypeCode_IntPtr);
  4000. auto int8Type = mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8);
  4001. auto ptrType = mBfIRBuilder->GetPointerTo(int8Type);
  4002. auto ptrPtrType = mBfIRBuilder->GetPointerTo(ptrType);
  4003. auto fieldTypeInst = fieldInst->mResolvedType->ToTypeInstance();
  4004. BfIRValue fieldAddr;
  4005. if (fieldDef->mIsStatic)
  4006. {
  4007. fieldAddr = ReferenceStaticField(fieldInst).mValue;
  4008. }
  4009. else
  4010. fieldAddr = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, fieldInst->mDataIdx);
  4011. auto thisValue = BfTypedValue(mBfIRBuilder->CreateBitCast(fieldAddr, mBfIRBuilder->MapType(fieldInst->mResolvedType)), fieldInst->mResolvedType);
  4012. auto indexVal = BfTypedValue(CreateAlloca(intType), CreateRefType(intType));
  4013. auto intThisVal = mBfIRBuilder->CreatePtrToInt(thisValue.mValue, (intType->mSize == 4) ? BfTypeCode_Int32 : BfTypeCode_Int64);
  4014. auto curValPtr = mBfIRBuilder->CreateAdd(intThisVal, GetConstValue(fieldTypeInst->mInstSize, intType));
  4015. mBfIRBuilder->CreateStore(curValPtr, indexVal.mValue);
  4016. auto vObjectAddr = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, 0);
  4017. auto vDataRef = CreateClassVDataGlobal(fieldInst->mResolvedType->ToTypeInstance());
  4018. auto destAddr = mBfIRBuilder->CreateBitCast(vObjectAddr, ptrPtrType);
  4019. auto srcVal = mBfIRBuilder->CreateBitCast(vDataRef, ptrType);
  4020. mBfIRBuilder->CreateStore(srcVal, destAddr);
  4021. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  4022. {
  4023. auto int8Type = mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8);
  4024. auto ptrType = mBfIRBuilder->GetPointerTo(int8Type);
  4025. auto thisFlagsPtr = mBfIRBuilder->CreateBitCast(thisValue.mValue, ptrType);
  4026. mBfIRBuilder->CreateStore(GetConstValue8(BfObjectFlag_AppendAlloc), thisFlagsPtr);
  4027. }
  4028. exprEvaluator.MatchConstructor(fieldDef->GetNameNode(), NULL, thisValue, fieldInst->mResolvedType->ToTypeInstance(), resolvedArgs, false, true, &indexVal);
  4029. }
  4030. void BfModule::CheckInterfaceMethod(BfMethodInstance* methodInstance)
  4031. {
  4032. }
  4033. void BfModule::FindSubTypes(BfTypeInstance* classType, SizedArrayImpl<int>* outVals, SizedArrayImpl<BfTypeInstance*>* exChecks, bool isInterfacePass)
  4034. {
  4035. PopulateType(classType);
  4036. if (isInterfacePass)
  4037. {
  4038. for (auto ifaceInst : classType->mInterfaces)
  4039. {
  4040. if (exChecks->Contains(ifaceInst.mInterfaceType))
  4041. continue;
  4042. if (outVals->Contains(ifaceInst.mInterfaceType->mTypeId))
  4043. continue;
  4044. if (ifaceInst.mDeclaringType->IsExtension())
  4045. {
  4046. bool needsExCheck = false;
  4047. if (ifaceInst.mDeclaringType->mProject != classType->mTypeDef->mProject)
  4048. {
  4049. PopulateType(ifaceInst.mInterfaceType, BfPopulateType_DataAndMethods);
  4050. if (ifaceInst.mInterfaceType->mVirtualMethodTableSize > 0)
  4051. {
  4052. exChecks->push_back(ifaceInst.mInterfaceType);
  4053. continue;
  4054. }
  4055. else
  4056. {
  4057. // We can only do an 'exCheck' if we're actually going to slot this interface
  4058. }
  4059. }
  4060. }
  4061. outVals->push_back(ifaceInst.mInterfaceType->mTypeId);
  4062. }
  4063. }
  4064. else
  4065. {
  4066. outVals->push_back(classType->mTypeId);
  4067. }
  4068. if (classType->mBaseType != NULL)
  4069. {
  4070. FindSubTypes(classType->mBaseType, outVals, exChecks, isInterfacePass);
  4071. }
  4072. }
  4073. void BfModule::CreateDynamicCastMethod()
  4074. {
  4075. auto objType = mContext->mBfObjectType;
  4076. if ((mCompiler->mIsResolveOnly) || (!mIsReified))
  4077. {
  4078. // The main reason to punt on this method for ResolveOnly is because types can be created
  4079. // and destroyed quickly during autocomplete and the typeId creep can generate lots of
  4080. // entries in the LLVM ConstantInt pool, primarily from the FindSubTypes call. We can
  4081. // remove this punt when we recycle typeId's
  4082. mBfIRBuilder->CreateRet(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(objType)));
  4083. mCurMethodState->mHadReturn = true;
  4084. return;
  4085. }
  4086. bool isInterfacePass = mCurMethodInstance->mMethodDef->mName == BF_METHODNAME_DYNAMICCAST_INTERFACE;
  4087. auto func = mCurMethodState->mIRFunction;
  4088. auto thisValue = mBfIRBuilder->GetArgument(0);
  4089. auto typeIdValue = mBfIRBuilder->GetArgument(1);
  4090. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  4091. auto int32Type = GetPrimitiveType(BfTypeCode_Int32);
  4092. typeIdValue = CastToValue(NULL, BfTypedValue(typeIdValue, intPtrType), int32Type, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_SilentFail));
  4093. auto thisObject = mBfIRBuilder->CreateBitCast(thisValue, mBfIRBuilder->MapType(objType));
  4094. auto trueBB = mBfIRBuilder->CreateBlock("check.true");
  4095. //auto falseBB = mBfIRBuilder->CreateBlock("check.false");
  4096. auto exitBB = mBfIRBuilder->CreateBlock("exit");
  4097. SizedArray<int, 8> typeMatches;
  4098. SizedArray<BfTypeInstance*, 8> exChecks;
  4099. FindSubTypes(mCurTypeInstance, &typeMatches, &exChecks, isInterfacePass);
  4100. if ((mCurTypeInstance->IsGenericTypeInstance()) && (!mCurTypeInstance->IsUnspecializedType()))
  4101. {
  4102. // Add 'unbound' type id to cast list so things like "List<int> is List<>" work
  4103. auto genericTypeInst = mCurTypeInstance->mTypeDef;
  4104. BfTypeVector genericArgs;
  4105. for (int i = 0; i < (int) genericTypeInst->mGenericParamDefs.size(); i++)
  4106. genericArgs.push_back(GetGenericParamType(BfGenericParamKind_Type, i));
  4107. auto unboundType = ResolveTypeDef(mCurTypeInstance->mTypeDef->GetDefinition(), genericArgs, BfPopulateType_Declaration);
  4108. typeMatches.push_back(unboundType->mTypeId);
  4109. }
  4110. if (mCurTypeInstance->IsBoxed())
  4111. {
  4112. BfBoxedType* boxedType = (BfBoxedType*)mCurTypeInstance;
  4113. BfTypeInstance* innerType = boxedType->mElementType->ToTypeInstance();
  4114. FindSubTypes(innerType, &typeMatches, &exChecks, isInterfacePass);
  4115. if (innerType->IsTypedPrimitive())
  4116. {
  4117. auto underlyingType = innerType->GetUnderlyingType();
  4118. typeMatches.push_back(underlyingType->mTypeId);
  4119. }
  4120. auto innerTypeInst = innerType->ToTypeInstance();
  4121. if ((innerTypeInst->IsInstanceOf(mCompiler->mSizedArrayTypeDef)) ||
  4122. (innerTypeInst->IsInstanceOf(mCompiler->mPointerTTypeDef)) ||
  4123. (innerTypeInst->IsInstanceOf(mCompiler->mMethodRefTypeDef)))
  4124. {
  4125. PopulateType(innerTypeInst);
  4126. //TODO: What case was this supposed to handle?
  4127. //typeMatches.push_back(innerTypeInst->mFieldInstances[0].mResolvedType->mTypeId);
  4128. }
  4129. }
  4130. auto curBlock = mBfIRBuilder->GetInsertBlock();
  4131. BfIRValue vDataPtr;
  4132. if (!exChecks.empty())
  4133. {
  4134. BfType* intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  4135. auto ptrPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(intPtrType)));
  4136. auto vDataPtrPtr = mBfIRBuilder->CreateBitCast(thisValue, ptrPtrType);
  4137. vDataPtr = FixClassVData(mBfIRBuilder->CreateLoad(vDataPtrPtr/*, "vtable"*/));
  4138. }
  4139. auto switchStatement = mBfIRBuilder->CreateSwitch(typeIdValue, exitBB, (int)typeMatches.size() + (int)exChecks.size());
  4140. for (auto typeMatch : typeMatches)
  4141. mBfIRBuilder->AddSwitchCase(switchStatement, GetConstValue32(typeMatch), trueBB);
  4142. Array<BfIRValue> incomingFalses;
  4143. for (auto ifaceTypeInst : exChecks)
  4144. {
  4145. BfIRBlock nextBB = mBfIRBuilder->CreateBlock("exCheck", true);
  4146. mBfIRBuilder->AddSwitchCase(switchStatement, GetConstValue32(ifaceTypeInst->mTypeId), nextBB);
  4147. mBfIRBuilder->SetInsertPoint(nextBB);
  4148. BfIRValue slotOfs = GetInterfaceSlotNum(ifaceTypeInst);
  4149. auto ifacePtrPtr = mBfIRBuilder->CreateInBoundsGEP(vDataPtr, slotOfs/*, "iface"*/);
  4150. auto ifacePtr = mBfIRBuilder->CreateLoad(ifacePtrPtr);
  4151. auto cmpResult = mBfIRBuilder->CreateCmpNE(ifacePtr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0));
  4152. mBfIRBuilder->CreateCondBr(cmpResult, trueBB, exitBB);
  4153. incomingFalses.push_back(nextBB);
  4154. }
  4155. mBfIRBuilder->AddBlock(trueBB);
  4156. mBfIRBuilder->SetInsertPoint(trueBB);
  4157. mBfIRBuilder->CreateBr(exitBB);
  4158. mBfIRBuilder->AddBlock(exitBB);
  4159. mBfIRBuilder->SetInsertPoint(exitBB);
  4160. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapTypeInstPtr(objType), 2);
  4161. mBfIRBuilder->AddPhiIncoming(phi, thisObject, trueBB);
  4162. auto nullValue = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(objType));
  4163. for (auto incomingFalseBlock : incomingFalses)
  4164. mBfIRBuilder->AddPhiIncoming(phi, nullValue, incomingFalseBlock);
  4165. mBfIRBuilder->AddPhiIncoming(phi, nullValue, curBlock);
  4166. mBfIRBuilder->CreateRet(phi);
  4167. mCurMethodState->mHadReturn = true;
  4168. }
  4169. void BfModule::EmitEquals(BfTypedValue leftValue, BfTypedValue rightValue, BfIRBlock exitBB, bool strictEquals)
  4170. {
  4171. BfExprEvaluator exprEvaluator(this);
  4172. exprEvaluator.mExpectingType = mCurMethodInstance->mReturnType;
  4173. auto typeInst = rightValue.mType->ToTypeInstance();
  4174. exprEvaluator.PerformBinaryOperation((BfAstNode*)NULL, (BfAstNode*)NULL, strictEquals ? BfBinaryOp_StrictEquality : BfBinaryOp_Equality, NULL, BfBinOpFlag_IgnoreOperatorWithWrongResult, leftValue, rightValue);
  4175. BfTypedValue result = exprEvaluator.GetResult();
  4176. if (result.mType != GetPrimitiveType(BfTypeCode_Boolean))
  4177. {
  4178. // Fail?
  4179. }
  4180. if ((result) && (!result.mType->IsVar()))
  4181. {
  4182. auto nextBB = mBfIRBuilder->CreateBlock("next");
  4183. mBfIRBuilder->CreateCondBr(result.mValue, nextBB, exitBB);
  4184. mBfIRBuilder->AddBlock(nextBB);
  4185. mBfIRBuilder->SetInsertPoint(nextBB);
  4186. }
  4187. }
  4188. void BfModule::CreateFakeCallerMethod(const String& funcName)
  4189. {
  4190. if (mCurMethodInstance->mHasFailed)
  4191. return;
  4192. if (mCurMethodInstance->mMethodDef->mIsSkipCall)
  4193. return;
  4194. BF_ASSERT(mCurMethodInstance->mIRFunction);
  4195. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  4196. SizedArray<BfIRType, 4> paramTypes;
  4197. BfIRFunctionType funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  4198. BfIRFunction func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_Internal, "FORCELINK_" + funcName);
  4199. mBfIRBuilder->SetActiveFunction(func);
  4200. auto entryBlock = mBfIRBuilder->CreateBlock("main", true);
  4201. mBfIRBuilder->SetInsertPoint(entryBlock);
  4202. BfMethodState methodState;
  4203. methodState.mIRHeadBlock = entryBlock;
  4204. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  4205. SizedArray<BfIRValue, 8> args;
  4206. BfExprEvaluator exprEvaluator(this);
  4207. if (mCurMethodInstance->GetStructRetIdx() == 0)
  4208. {
  4209. auto retPtrType = CreatePointerType(mCurMethodInstance->mReturnType);
  4210. exprEvaluator.PushArg(GetDefaultTypedValue(retPtrType, true, BfDefaultValueKind_Const), args);
  4211. }
  4212. if (mCurMethodInstance->HasThis())
  4213. {
  4214. auto thisValue = GetDefaultTypedValue(mCurMethodInstance->GetOwner(), true, mCurTypeInstance->IsComposite() ? BfDefaultValueKind_Addr : BfDefaultValueKind_Const);
  4215. exprEvaluator.PushThis(NULL, thisValue, mCurMethodInstance, args);
  4216. }
  4217. if (mCurMethodInstance->GetStructRetIdx() == 1)
  4218. {
  4219. auto retPtrType = CreatePointerType(mCurMethodInstance->mReturnType);
  4220. exprEvaluator.PushArg(GetDefaultTypedValue(retPtrType, true, BfDefaultValueKind_Const), args);
  4221. }
  4222. for (int paramIdx = 0; paramIdx < mCurMethodInstance->GetParamCount(); paramIdx++)
  4223. {
  4224. auto paramType = mCurMethodInstance->GetParamType(paramIdx);
  4225. if (paramType->IsValuelessType())
  4226. continue;
  4227. exprEvaluator.PushArg(GetDefaultTypedValue(paramType, true, paramType->IsComposite() ? BfDefaultValueKind_Addr : BfDefaultValueKind_Const), args);
  4228. }
  4229. mBfIRBuilder->CreateCall(mCurMethodInstance->mIRFunction, args);
  4230. mBfIRBuilder->CreateRetVoid();
  4231. }
  4232. void BfModule::CreateDelegateEqualsMethod()
  4233. {
  4234. if (mBfIRBuilder->mIgnoreWrites)
  4235. return;
  4236. auto refNode = mCurTypeInstance->mTypeDef->GetRefNode();
  4237. if (refNode == NULL)
  4238. refNode = mCompiler->mValueTypeTypeDef->GetRefNode();
  4239. UpdateSrcPos(refNode);
  4240. SetIllegalSrcPos();
  4241. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  4242. auto resultVal = CreateAlloca(boolType);
  4243. mBfIRBuilder->CreateStore(GetConstValue(0, boolType), resultVal);
  4244. auto exitBB = mBfIRBuilder->CreateBlock("exit");
  4245. auto delegateType = ResolveTypeDef(mCompiler->mDelegateTypeDef)->ToTypeInstance();
  4246. mBfIRBuilder->PopulateType(delegateType);
  4247. BfExprEvaluator exprEvaluator(this);
  4248. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  4249. BfTypedValue lhsDelegate = BfTypedValue(mBfIRBuilder->CreateBitCast(leftTypedVal.mValue, mBfIRBuilder->MapType(delegateType)), delegateType);
  4250. BfTypedValue rhsDelegate = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  4251. rhsDelegate = LoadValue(rhsDelegate);
  4252. BfTypedValue rightTypedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(rhsDelegate.mValue, mBfIRBuilder->MapType(mCurTypeInstance)), mCurTypeInstance);
  4253. auto& targetFieldInstance = delegateType->mFieldInstances[0];
  4254. BfTypedValue leftValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(lhsDelegate.mValue, 0, targetFieldInstance.mDataIdx), targetFieldInstance.mResolvedType, true);
  4255. BfTypedValue rightValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(rhsDelegate.mValue, 0, targetFieldInstance.mDataIdx), targetFieldInstance.mResolvedType, true);
  4256. leftValue = LoadValue(leftValue);
  4257. rightValue = LoadValue(rightValue);
  4258. EmitEquals(leftValue, rightValue, exitBB, false);
  4259. bool hadComparison = false;
  4260. for (auto& fieldRef : mCurTypeInstance->mFieldInstances)
  4261. {
  4262. BfFieldInstance* fieldInstance = &fieldRef;
  4263. if (fieldInstance->mDataOffset == -1)
  4264. continue;
  4265. auto fieldType = fieldInstance->mResolvedType;
  4266. if (fieldType->IsValuelessType())
  4267. continue;
  4268. if (fieldType->IsVar())
  4269. continue;
  4270. if (fieldType->IsMethodRef())
  4271. continue;
  4272. if (fieldType->IsRef())
  4273. fieldType = CreatePointerType(fieldType->GetUnderlyingType());
  4274. BfTypedValue leftValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(leftTypedVal.mValue, 0, fieldInstance->mDataIdx), fieldType, true);
  4275. BfTypedValue rightValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(rightTypedVal.mValue, 0, fieldInstance->mDataIdx), fieldType, true);
  4276. if (!fieldInstance->mResolvedType->IsComposite())
  4277. {
  4278. leftValue = LoadValue(leftValue);
  4279. rightValue = LoadValue(rightValue);
  4280. }
  4281. EmitEquals(leftValue, rightValue, exitBB, false);
  4282. }
  4283. mBfIRBuilder->CreateStore(GetConstValue(1, boolType), resultVal);
  4284. mBfIRBuilder->CreateBr(exitBB);
  4285. mBfIRBuilder->AddBlock(exitBB);
  4286. mBfIRBuilder->SetInsertPoint(exitBB);
  4287. auto loadedResult = mBfIRBuilder->CreateLoad(resultVal);
  4288. ClearLifetimeEnds();
  4289. mBfIRBuilder->CreateRet(loadedResult);
  4290. mCurMethodState->mHadReturn = true;
  4291. }
  4292. void BfModule::CreateValueTypeEqualsMethod(bool strictEquals)
  4293. {
  4294. if (mCurMethodInstance->mIsUnspecialized)
  4295. return;
  4296. if (mBfIRBuilder->mIgnoreWrites)
  4297. return;
  4298. BF_ASSERT(!mCurTypeInstance->IsBoxed());
  4299. auto compareType = mCurMethodInstance->mParams[0].mResolvedType;
  4300. bool isValid = true;
  4301. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  4302. if (compareType->IsValuelessType())
  4303. {
  4304. mBfIRBuilder->CreateRet(GetDefaultValue(boolType));
  4305. return;
  4306. }
  4307. if (compareType->IsTypedPrimitive())
  4308. {
  4309. BfExprEvaluator exprEvaluator(this);
  4310. BfTypedValue leftTypedVal = LoadValue(exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]));
  4311. BfTypedValue rightTypedVal = LoadValue(exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]));
  4312. auto cmpResult = mBfIRBuilder->CreateCmpEQ(leftTypedVal.mValue, rightTypedVal.mValue);
  4313. mBfIRBuilder->CreateRet(cmpResult);
  4314. return;
  4315. }
  4316. auto compareDType = compareType->ToDependedType();
  4317. BfTypeInstance* compareTypeInst = compareType->ToTypeInstance();
  4318. if (compareTypeInst != NULL)
  4319. {
  4320. if (compareType->IsPrimitiveType())
  4321. compareTypeInst = GetWrappedStructType(compareType);
  4322. if ((compareTypeInst == NULL) || (!compareTypeInst->IsValueType()))
  4323. {
  4324. isValid = false;
  4325. }
  4326. mBfIRBuilder->PopulateType(compareTypeInst);
  4327. }
  4328. if (!isValid)
  4329. {
  4330. ClearLifetimeEnds();
  4331. mBfIRBuilder->CreateRet(GetDefaultValue(boolType));
  4332. return;
  4333. }
  4334. AddDependency(compareDType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  4335. auto refNode = mCurTypeInstance->mTypeDef->GetRefNode();
  4336. if (refNode == NULL)
  4337. refNode = mCompiler->mValueTypeTypeDef->GetRefNode();
  4338. UpdateSrcPos(refNode);
  4339. SetIllegalSrcPos();
  4340. auto resultVal = CreateAlloca(boolType);
  4341. mBfIRBuilder->CreateStore(GetConstValue(0, boolType), resultVal);
  4342. auto exitBB = mBfIRBuilder->CreateBlock("exit");
  4343. if (compareType->IsValuelessType())
  4344. {
  4345. // Always equal, nothing to do
  4346. }
  4347. else if (compareType->IsSizedArray())
  4348. {
  4349. auto sizedArrayType = (BfSizedArrayType*)compareType;
  4350. auto _SizedIndex = [&](BfIRValue target, BfIRValue index)
  4351. {
  4352. BfTypedValue result;
  4353. auto indexResult = CreateIndexedValue(sizedArrayType->mElementType, target, index, true);
  4354. result = BfTypedValue(indexResult, sizedArrayType->mElementType, BfTypedValueKind_Addr);
  4355. if (!result.mType->IsValueType())
  4356. result = LoadValue(result);
  4357. return result;
  4358. };
  4359. if (sizedArrayType->mElementCount > 6)
  4360. {
  4361. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  4362. auto itr = CreateAlloca(intPtrType);
  4363. mBfIRBuilder->CreateStore(GetDefaultValue(intPtrType), itr);
  4364. auto loopBB = mBfIRBuilder->CreateBlock("loop", true);
  4365. auto bodyBB = mBfIRBuilder->CreateBlock("body", true);
  4366. auto doneBB = mBfIRBuilder->CreateBlock("done", true);
  4367. mBfIRBuilder->CreateBr(loopBB);
  4368. mBfIRBuilder->SetInsertPoint(loopBB);
  4369. auto loadedItr = mBfIRBuilder->CreateLoad(itr);
  4370. auto cmpRes = mBfIRBuilder->CreateCmpGTE(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)sizedArrayType->mElementCount), true);
  4371. mBfIRBuilder->CreateCondBr(cmpRes, doneBB, bodyBB);
  4372. mBfIRBuilder->SetInsertPoint(bodyBB);
  4373. BfTypedValue leftValue = _SizedIndex(mCurMethodState->mLocals[0]->mValue, loadedItr);
  4374. BfTypedValue rightValue = _SizedIndex(mCurMethodState->mLocals[1]->mValue, loadedItr);
  4375. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4376. auto incValue = mBfIRBuilder->CreateAdd(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  4377. mBfIRBuilder->CreateStore(incValue, itr);
  4378. mBfIRBuilder->CreateBr(loopBB);
  4379. mBfIRBuilder->SetInsertPoint(doneBB);
  4380. }
  4381. else
  4382. {
  4383. for (int dataIdx = 0; dataIdx < sizedArrayType->mElementCount; dataIdx++)
  4384. {
  4385. BfTypedValue leftValue = _SizedIndex(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, dataIdx));
  4386. BfTypedValue rightValue = _SizedIndex(mCurMethodState->mLocals[1]->mValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, dataIdx));
  4387. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4388. }
  4389. }
  4390. }
  4391. else if (compareType->IsMethodRef())
  4392. {
  4393. auto methodRefType = (BfMethodRefType*)compareType;
  4394. BfMethodInstance* methodInstance = methodRefType->mMethodRef;
  4395. BfExprEvaluator exprEvaluator(this);
  4396. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  4397. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  4398. // We only need to compare the 'this' capture. The rationale is that it's impossible to capture any other non-matching
  4399. // values for the same method reference -- they will always refer back to the same local variables.
  4400. int dataIdx = methodRefType->GetDataIdxFromParamIdx(-1);
  4401. if (dataIdx != -1)
  4402. {
  4403. bool failed = false;
  4404. BfTypedValue leftValue = exprEvaluator.DoImplicitArgCapture(NULL, methodInstance, methodRefType->GetParamIdxFromDataIdx(dataIdx), failed, BfImplicitParamKind_General, leftTypedVal);
  4405. BfTypedValue rightValue = exprEvaluator.DoImplicitArgCapture(NULL, methodInstance, methodRefType->GetParamIdxFromDataIdx(dataIdx), failed, BfImplicitParamKind_General, rightTypedVal);
  4406. BF_ASSERT(!failed);
  4407. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4408. }
  4409. }
  4410. else if (compareTypeInst->IsEnum())
  4411. {
  4412. //auto intType = GetPrimitiveType(BfTypeCode_Int32);
  4413. BfExprEvaluator exprEvaluator(this);
  4414. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  4415. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  4416. auto dscrType = compareTypeInst->GetDiscriminatorType();
  4417. BfTypedValue leftValue = ExtractValue(leftTypedVal, NULL, 2);
  4418. leftValue = LoadValue(leftValue);
  4419. BfTypedValue rightValue = ExtractValue(rightTypedVal, NULL, 2);
  4420. rightValue = LoadValue(rightValue);
  4421. BfTypedValue leftPayload = ExtractValue(leftTypedVal, NULL, 1);
  4422. BfTypedValue rightPayload = ExtractValue(rightTypedVal, NULL, 1);
  4423. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4424. int enumCount = 0;
  4425. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  4426. {
  4427. BfFieldInstance* fieldInstance = &fieldRef;
  4428. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  4429. if ((fieldDef != NULL) && (fieldDef->IsEnumCaseEntry()))
  4430. {
  4431. enumCount = -fieldInstance->mDataIdx;
  4432. }
  4433. }
  4434. if (enumCount > 0)
  4435. {
  4436. BfIRBlock matchedBlock = mBfIRBuilder->CreateBlock("matched");
  4437. auto switchVal = mBfIRBuilder->CreateSwitch(leftValue.mValue, exitBB, enumCount);
  4438. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  4439. {
  4440. BfFieldInstance* fieldInstance = &fieldRef;
  4441. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  4442. if ((fieldDef != NULL) && (fieldDef->IsEnumCaseEntry()))
  4443. {
  4444. int enumIdx = -fieldInstance->mDataIdx - 1;
  4445. if (fieldInstance->mResolvedType->mSize == 0)
  4446. {
  4447. mBfIRBuilder->AddSwitchCase(switchVal, mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, enumIdx), matchedBlock);
  4448. }
  4449. else
  4450. {
  4451. auto caseBlock = mBfIRBuilder->CreateBlock("case", true);
  4452. mBfIRBuilder->SetInsertPoint(caseBlock);
  4453. auto tuplePtr = CreatePointerType(fieldInstance->mResolvedType);
  4454. BfTypedValue leftTuple;
  4455. BfTypedValue rightTuple;
  4456. if (leftPayload.IsAddr())
  4457. {
  4458. leftTuple = BfTypedValue(mBfIRBuilder->CreateBitCast(leftPayload.mValue, mBfIRBuilder->MapType(tuplePtr)), fieldInstance->mResolvedType, true);
  4459. rightTuple = BfTypedValue(mBfIRBuilder->CreateBitCast(rightPayload.mValue, mBfIRBuilder->MapType(tuplePtr)), fieldInstance->mResolvedType, true);
  4460. }
  4461. else
  4462. {
  4463. leftTuple = Cast(NULL, leftPayload, fieldInstance->mResolvedType, BfCastFlags_Force);
  4464. rightTuple = Cast(NULL, rightPayload, fieldInstance->mResolvedType, BfCastFlags_Force);
  4465. }
  4466. EmitEquals(leftTuple, rightTuple, exitBB, strictEquals);
  4467. mBfIRBuilder->CreateBr(matchedBlock);
  4468. mBfIRBuilder->AddSwitchCase(switchVal, mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, enumIdx), caseBlock);
  4469. }
  4470. }
  4471. }
  4472. mBfIRBuilder->AddBlock(matchedBlock);
  4473. mBfIRBuilder->SetInsertPoint(matchedBlock);
  4474. }
  4475. }
  4476. else if (compareTypeInst->IsUnion())
  4477. {
  4478. auto innerType = compareTypeInst->GetUnionInnerType();
  4479. if (!innerType->IsValuelessType())
  4480. {
  4481. BfExprEvaluator exprEvaluator(this);
  4482. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  4483. leftTypedVal = AggregateSplat(leftTypedVal);
  4484. BfTypedValue leftUnionTypedVal = ExtractValue(leftTypedVal, NULL, 1);
  4485. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  4486. rightTypedVal = AggregateSplat(rightTypedVal);
  4487. BfTypedValue rightUnionTypedVal = ExtractValue(rightTypedVal, NULL, 1);
  4488. EmitEquals(leftUnionTypedVal, rightUnionTypedVal, exitBB, strictEquals);
  4489. }
  4490. }
  4491. else
  4492. {
  4493. BfExprEvaluator exprEvaluator(this);
  4494. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  4495. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  4496. bool hadComparison = false;
  4497. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  4498. {
  4499. BfFieldInstance* fieldInstance = &fieldRef;
  4500. if (fieldInstance->mDataOffset == -1)
  4501. continue;
  4502. if (fieldInstance->mResolvedType->IsValuelessType())
  4503. continue;
  4504. if (fieldInstance->mResolvedType->IsVar())
  4505. continue;
  4506. BfTypedValue leftValue = ExtractValue(leftTypedVal, fieldInstance, fieldInstance->mDataIdx);
  4507. BfTypedValue rightValue = ExtractValue(rightTypedVal, fieldInstance, fieldInstance->mDataIdx);
  4508. if (!fieldInstance->mResolvedType->IsComposite())
  4509. {
  4510. leftValue = LoadValue(leftValue);
  4511. rightValue = LoadValue(rightValue);
  4512. }
  4513. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4514. }
  4515. auto baseTypeInst = compareTypeInst->mBaseType;
  4516. if ((baseTypeInst != NULL) && (baseTypeInst->mTypeDef != mCompiler->mValueTypeTypeDef))
  4517. {
  4518. BfTypedValue leftValue = Cast(NULL, leftTypedVal, baseTypeInst);
  4519. BfTypedValue rightValue = Cast(NULL, rightTypedVal, baseTypeInst);
  4520. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  4521. }
  4522. }
  4523. mBfIRBuilder->CreateStore(GetConstValue(1, boolType), resultVal);
  4524. mBfIRBuilder->CreateBr(exitBB);
  4525. mBfIRBuilder->AddBlock(exitBB);
  4526. mBfIRBuilder->SetInsertPoint(exitBB);
  4527. auto loadedResult = mBfIRBuilder->CreateLoad(resultVal);
  4528. ClearLifetimeEnds();
  4529. mBfIRBuilder->CreateRet(loadedResult);
  4530. mCurMethodState->mHadReturn = true;
  4531. }
  4532. BfIRValue BfModule::CreateClassVDataGlobal(BfTypeInstance* typeInstance, int* outNumElements, String* outMangledName)
  4533. {
  4534. if (mBfIRBuilder->mIgnoreWrites)
  4535. return mBfIRBuilder->GetFakeVal();
  4536. PopulateType(typeInstance, mIsComptimeModule ? BfPopulateType_Data : BfPopulateType_DataAndMethods);
  4537. BfType* classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  4538. if (mIsComptimeModule)
  4539. {
  4540. auto idVal = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, typeInstance->mTypeId);
  4541. return mBfIRBuilder->CreateIntToPtr(idVal, mBfIRBuilder->MapType(CreatePointerType(classVDataType)));
  4542. }
  4543. BfIRValue* globalVariablePtr = NULL;
  4544. mClassVDataRefs.TryGetValue(typeInstance, &globalVariablePtr);
  4545. int numElements = 1;
  4546. if ((outNumElements != NULL) || (globalVariablePtr == NULL))
  4547. {
  4548. numElements += mCompiler->mMaxInterfaceSlots;
  4549. auto maxIFaceVirtIdx = 0;
  4550. if (!typeInstance->IsInterface())
  4551. {
  4552. int dynCastDataElems = 1 + mCompiler->mMaxInterfaceSlots;
  4553. numElements += ((dynCastDataElems * 4) + mSystem->mPtrSize - 1) / mSystem->mPtrSize;
  4554. numElements += typeInstance->GetOrigVTableSize();
  4555. int ifaceMethodLen = typeInstance->GetIFaceVMethodSize();
  4556. if (typeInstance->mHotTypeData != NULL)
  4557. {
  4558. if (typeInstance->mHotTypeData->mOrigInterfaceMethodsLength != -1)
  4559. ifaceMethodLen = typeInstance->mHotTypeData->mOrigInterfaceMethodsLength;
  4560. }
  4561. numElements += ifaceMethodLen;
  4562. }
  4563. if (outNumElements != NULL)
  4564. *outNumElements = numElements;
  4565. }
  4566. StringT<128> classVDataName;
  4567. String memberName = "sBfClassVData";
  4568. if ((typeInstance->mHotTypeData != NULL) && ((typeInstance->mHotTypeData->mHadDataChange) || (typeInstance->mHotTypeData->mPendingDataChange)))
  4569. {
  4570. auto curVersion = typeInstance->mHotTypeData->GetLatestVersion();
  4571. memberName += "_";
  4572. memberName += BfTypeUtils::HashEncode64(curVersion->mDataHash.mLow);
  4573. memberName += BfTypeUtils::HashEncode64(curVersion->mDataHash.mHigh);
  4574. }
  4575. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), typeInstance, memberName, classVDataType);
  4576. if (outMangledName != NULL)
  4577. *outMangledName = classVDataName;
  4578. /*if (itr != mClassVDataRefs.end())
  4579. {
  4580. globalVariable = itr->second;
  4581. }*/
  4582. BfIRValue globalVariable;
  4583. if (globalVariablePtr != NULL)
  4584. {
  4585. globalVariable = *globalVariablePtr;
  4586. }
  4587. else
  4588. {
  4589. BfLogSysM("Creating VData %s\n", classVDataName.c_str());
  4590. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), numElements);
  4591. globalVariable = mBfIRBuilder->CreateGlobalVariable(
  4592. arrayType,
  4593. true,
  4594. BfIRLinkageType_External,
  4595. BfIRValue(),
  4596. classVDataName);
  4597. mClassVDataRefs[typeInstance] = globalVariable;
  4598. }
  4599. return globalVariable;
  4600. }
  4601. BfIRValue BfModule::GetClassVDataPtr(BfTypeInstance* typeInstance)
  4602. {
  4603. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  4604. if (mIsComptimeModule)
  4605. return mBfIRBuilder->Comptime_GetBfType(typeInstance->mTypeId, mBfIRBuilder->MapType(CreatePointerType(classVDataType)));
  4606. return mBfIRBuilder->CreateBitCast(CreateClassVDataGlobal(typeInstance), mBfIRBuilder->MapType(CreatePointerType(classVDataType)));
  4607. }
  4608. BfIRValue BfModule::CreateClassVDataExtGlobal(BfTypeInstance* declTypeInst, BfTypeInstance* implTypeInst, int startVirtIdx)
  4609. {
  4610. if (mBfIRBuilder->mIgnoreWrites)
  4611. return mBfIRBuilder->GetFakeVal();
  4612. int numElements = declTypeInst->GetSelfVTableSize() - declTypeInst->GetOrigSelfVTableSize();
  4613. BF_ASSERT(numElements >= 0);
  4614. if (numElements <= 0)
  4615. return BfIRValue();
  4616. BF_ASSERT(implTypeInst->mVirtualMethodTable[startVirtIdx].mDeclaringMethod.mMethodNum == -1);
  4617. BF_ASSERT(implTypeInst->mVirtualMethodTable[startVirtIdx].mDeclaringMethod.mTypeInstance == declTypeInst);
  4618. if (declTypeInst->mInheritDepth == implTypeInst->mInheritDepth)
  4619. BF_ASSERT(declTypeInst == implTypeInst);
  4620. else
  4621. BF_ASSERT(implTypeInst->mInheritDepth > declTypeInst->mInheritDepth);
  4622. if (declTypeInst != implTypeInst)
  4623. {
  4624. BfTypeInstance* highestImpl = declTypeInst;
  4625. for (int virtIdx = startVirtIdx + 1; virtIdx < (int)declTypeInst->mVirtualMethodTable.size(); virtIdx++)
  4626. {
  4627. if (implTypeInst->mVirtualMethodTable[virtIdx].mDeclaringMethod.mMethodNum == -1)
  4628. break; // Start of an ext entry for another type
  4629. auto checkImplTypeInst = implTypeInst->mVirtualMethodTable[virtIdx].mImplementingMethod.mTypeInstance;
  4630. if ((checkImplTypeInst != NULL) && (checkImplTypeInst->mInheritDepth > highestImpl->mInheritDepth))
  4631. highestImpl = checkImplTypeInst;
  4632. }
  4633. if (highestImpl != implTypeInst)
  4634. return CreateClassVDataExtGlobal(declTypeInst, highestImpl, startVirtIdx);
  4635. }
  4636. BfVDataExtEntry mapEntry;
  4637. mapEntry.mDeclTypeInst = declTypeInst;
  4638. mapEntry.mImplTypeInst = implTypeInst;
  4639. BfIRValue* irValuePtr = NULL;
  4640. if (mClassVDataExtRefs.TryGetValue(mapEntry, &irValuePtr))
  4641. return *irValuePtr;
  4642. PopulateType(declTypeInst, BfPopulateType_DataAndMethods);
  4643. PopulateType(implTypeInst, BfPopulateType_DataAndMethods);
  4644. StringT<512> classVDataName;
  4645. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), implTypeInst, "bf_hs_replace_VDataExt");
  4646. if (declTypeInst != implTypeInst)
  4647. {
  4648. classVDataName += StrFormat("_%d", implTypeInst->mInheritDepth - declTypeInst->mInheritDepth);
  4649. }
  4650. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  4651. auto voidPtrIRType = mBfIRBuilder->MapType(voidPtrType);
  4652. SizedArray<BfIRValue, 32> vData;
  4653. auto voidPtrNull = GetDefaultValue(voidPtrType);
  4654. for (int virtIdx = startVirtIdx + declTypeInst->GetOrigSelfVTableSize(); virtIdx < (int)declTypeInst->mVirtualMethodTable.size(); virtIdx++)
  4655. {
  4656. if (implTypeInst->mVirtualMethodTable[virtIdx].mDeclaringMethod.mMethodNum == -1)
  4657. break; // Start of an ext entry for another type
  4658. BfIRValue vValue;
  4659. auto& entry = implTypeInst->mVirtualMethodTable[virtIdx];
  4660. BfMethodInstance* declaringMethodInstance = (BfMethodInstance*)entry.mDeclaringMethod;
  4661. if ((declaringMethodInstance != NULL) && (declaringMethodInstance->mMethodInstanceGroup->IsImplemented()) && (declaringMethodInstance->mIsReified))
  4662. {
  4663. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].IsImplemented());
  4664. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].mDefault->mIsReified);
  4665. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  4666. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  4667. {
  4668. BF_ASSERT(implTypeInst->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject));
  4669. auto moduleMethodInst = GetMethodInstanceAtIdx(methodInstance->mMethodInstanceGroup->mOwner, methodInstance->mMethodInstanceGroup->mMethodIdx, NULL, BfGetMethodInstanceFlag_NoInline);
  4670. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  4671. vValue = funcPtr;
  4672. }
  4673. }
  4674. if (!vValue)
  4675. vValue = voidPtrNull;
  4676. vData.Add(vValue);
  4677. }
  4678. BF_ASSERT((int)vData.size() == numElements);
  4679. BfLogSysM("Creating VDataExt %s\n", classVDataName.c_str());
  4680. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), numElements);
  4681. auto globalVariable = mBfIRBuilder->CreateGlobalVariable(arrayType, true,
  4682. BfIRLinkageType_External, BfIRValue(), classVDataName);
  4683. BfIRType extVTableType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)vData.size());
  4684. BfIRValue extVTableConst = mBfIRBuilder->CreateConstAgg_Value(extVTableType, vData);
  4685. mBfIRBuilder->GlobalVar_SetInitializer(globalVariable, extVTableConst);
  4686. mClassVDataExtRefs[mapEntry] = globalVariable;
  4687. return globalVariable;
  4688. }
  4689. BfIRValue BfModule::CreateTypeDataRef(BfType* type)
  4690. {
  4691. if (mBfIRBuilder->mIgnoreWrites)
  4692. {
  4693. return mBfIRBuilder->CreateTypeOf(type);
  4694. }
  4695. if (mIsComptimeModule)
  4696. {
  4697. auto typeTypeDef = ResolveTypeDef(mCompiler->mTypeTypeDef);
  4698. auto typeTypeInst = typeTypeDef->ToTypeInstance();
  4699. return mBfIRBuilder->Comptime_GetReflectType(type->mTypeId, mBfIRBuilder->MapType(typeTypeInst));
  4700. }
  4701. PopulateType(type);
  4702. BfIRValue globalVariable;
  4703. BfIRValue* globalVariablePtr = NULL;
  4704. if (mTypeDataRefs.TryGetValue(type, &globalVariablePtr))
  4705. {
  4706. if (*globalVariablePtr)
  4707. return mBfIRBuilder->CreateTypeOf(type, *globalVariablePtr);
  4708. }
  4709. auto typeTypeDef = ResolveTypeDef(mCompiler->mTypeTypeDef);
  4710. auto typeTypeInst = typeTypeDef->ToTypeInstance();
  4711. auto typeInstance = type->ToTypeInstance();
  4712. StringT<4096> typeDataName;
  4713. if (typeInstance != NULL)
  4714. {
  4715. BfMangler::MangleStaticFieldName(typeDataName, mCompiler->GetMangleKind(), typeInstance, "sBfTypeData");
  4716. }
  4717. else
  4718. {
  4719. typeDataName += "sBfTypeData.";
  4720. BfMangler::Mangle(typeDataName, mCompiler->GetMangleKind(), type, this);
  4721. }
  4722. BfLogSysM("Creating TypeData %s\n", typeDataName.c_str());
  4723. globalVariable = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(typeTypeInst, BfIRPopulateType_Full), true, BfIRLinkageType_External, BfIRValue(), typeDataName);
  4724. mBfIRBuilder->SetReflectTypeData(mBfIRBuilder->MapType(type), globalVariable);
  4725. mTypeDataRefs[type] = globalVariable;
  4726. return mBfIRBuilder->CreateTypeOf(type, globalVariable);
  4727. }
  4728. void BfModule::EncodeAttributeData(BfTypeInstance* typeInstance, BfType* argType, BfIRValue arg, SizedArrayImpl<uint8>& data, Dictionary<int, int>& usedStringIdMap)
  4729. {
  4730. #define PUSH_INT8(val) data.push_back((uint8)val)
  4731. #define PUSH_INT16(val) { data.push_back(val & 0xFF); data.push_back((val >> 8) & 0xFF); }
  4732. #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); }
  4733. #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); \
  4734. data.push_back((val >> 32) & 0xFF); data.push_back((val >> 40) & 0xFF); data.push_back((val >> 48) & 0xFF); data.push_back((val >> 56) & 0xFF); }
  4735. auto constant = typeInstance->mConstHolder->GetConstant(arg);
  4736. bool handled = false;
  4737. if (constant == NULL)
  4738. {
  4739. Fail(StrFormat("Unhandled attribute constant data in '%s'", TypeToString(typeInstance).c_str()));
  4740. return;
  4741. }
  4742. if (argType->IsObject())
  4743. {
  4744. if (argType->IsInstanceOf(mCompiler->mStringTypeDef))
  4745. {
  4746. int stringId = constant->mInt32;
  4747. int* orderedIdPtr;
  4748. if (usedStringIdMap.TryAdd(stringId, NULL, &orderedIdPtr))
  4749. {
  4750. *orderedIdPtr = (int)usedStringIdMap.size() - 1;
  4751. }
  4752. GetStringObjectValue(stringId, true, true);
  4753. PUSH_INT8(0xFF); // String
  4754. PUSH_INT32(*orderedIdPtr);
  4755. return;
  4756. }
  4757. }
  4758. if (argType->IsPointer())
  4759. {
  4760. if (argType->GetUnderlyingType() == GetPrimitiveType(BfTypeCode_Char8))
  4761. {
  4762. if (constant->mTypeCode == BfTypeCode_StringId)
  4763. {
  4764. int stringId = constant->mInt32;
  4765. int* orderedIdPtr;
  4766. if (usedStringIdMap.TryAdd(stringId, NULL, &orderedIdPtr))
  4767. {
  4768. *orderedIdPtr = (int)usedStringIdMap.size() - 1;
  4769. }
  4770. GetStringObjectValue(stringId, true, true);
  4771. PUSH_INT8(0xFF); // String
  4772. PUSH_INT32(*orderedIdPtr);
  4773. return;
  4774. }
  4775. }
  4776. }
  4777. PUSH_INT8(constant->mTypeCode);
  4778. if ((constant->mTypeCode == BfTypeCode_Int64) ||
  4779. (constant->mTypeCode == BfTypeCode_UInt64) ||
  4780. (constant->mTypeCode == BfTypeCode_Double))
  4781. {
  4782. PUSH_INT64(constant->mInt64);
  4783. }
  4784. else if ((constant->mTypeCode == BfTypeCode_Int32) ||
  4785. (constant->mTypeCode == BfTypeCode_UInt32) ||
  4786. (constant->mTypeCode == BfTypeCode_Char32))
  4787. {
  4788. PUSH_INT32(constant->mInt32);
  4789. }
  4790. else if (constant->mTypeCode == BfTypeCode_Float)
  4791. {
  4792. float val = (float)constant->mDouble;
  4793. PUSH_INT32(*(int*)&val);
  4794. }
  4795. else if ((constant->mTypeCode == BfTypeCode_Int16) ||
  4796. (constant->mTypeCode == BfTypeCode_UInt16) ||
  4797. (constant->mTypeCode == BfTypeCode_Char16))
  4798. {
  4799. PUSH_INT16(constant->mInt16);
  4800. }
  4801. else if ((constant->mTypeCode == BfTypeCode_Int8) ||
  4802. (constant->mTypeCode == BfTypeCode_UInt8) ||
  4803. (constant->mTypeCode == BfTypeCode_Boolean) ||
  4804. (constant->mTypeCode == BfTypeCode_Char8))
  4805. {
  4806. PUSH_INT8(constant->mInt8);
  4807. }
  4808. else if (constant->mConstType == BfConstType_TypeOf)
  4809. {
  4810. auto typeOf = (BfTypeOf_Const*)constant;
  4811. PUSH_INT32(typeOf->mType->mTypeId);
  4812. }
  4813. else if (constant->mConstType == BfConstType_AggZero)
  4814. {
  4815. for (int i = 0; i < argType->mSize; i++)
  4816. data.Add(0);
  4817. }
  4818. // else if (constant->mConstType == BfConstType_Agg)
  4819. // {
  4820. // BF_ASSERT(argType->IsComposite());
  4821. // if (argType->IsSizedArray())
  4822. // {
  4823. // auto argSizedArrayType = (BfSizedArrayType*)argType;
  4824. // }
  4825. // else
  4826. // {
  4827. // auto argTypeInstance = argType->ToTypeInstance();
  4828. // }
  4829. // }
  4830. else
  4831. {
  4832. Fail(StrFormat("Unhandled attribute constant data in '%s'", TypeToString(typeInstance).c_str()));
  4833. }
  4834. }
  4835. BfIRValue BfModule::CreateFieldData(BfFieldInstance* fieldInstance, int customAttrIdx)
  4836. {
  4837. bool isComptimeArg = mBfIRBuilder->mIgnoreWrites;
  4838. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  4839. auto typeInstance = fieldInstance->mOwner;
  4840. BfType* intType = GetPrimitiveType(BfTypeCode_Int32);
  4841. BfType* intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  4842. BfType* shortType = GetPrimitiveType(BfTypeCode_Int16);
  4843. BfType* typeIdType = intType;
  4844. BfTypeInstance* reflectFieldDataType = ResolveTypeDef(mCompiler->mReflectFieldDataDef)->ToTypeInstance();
  4845. BfIRValue emptyValueType = mBfIRBuilder->mIgnoreWrites ?
  4846. mBfIRBuilder->CreateConstAgg(mBfIRBuilder->MapTypeInst(reflectFieldDataType->mBaseType), SizedArray<BfIRValue, 1>()) :
  4847. mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldDataType->mBaseType), SizedArray<BfIRValue, 1>());
  4848. BfIRValue fieldNameConst = GetStringObjectValue(fieldDef->mName, !mIsComptimeModule);
  4849. bool is32Bit = mCompiler->mSystem->mPtrSize == 4;
  4850. int typeId = 0;
  4851. auto fieldType = fieldInstance->GetResolvedType();
  4852. if (fieldType->IsGenericParam())
  4853. {
  4854. //TODO:
  4855. }
  4856. else
  4857. typeId = fieldType->mTypeId;
  4858. BfFieldFlags fieldFlags = (BfFieldFlags)0;
  4859. if (fieldDef->mProtection == BfProtection_Protected)
  4860. fieldFlags = (BfFieldFlags)(fieldFlags | BfFieldFlags_Protected);
  4861. if (fieldDef->mProtection == BfProtection_Public)
  4862. fieldFlags = (BfFieldFlags)(fieldFlags | BfFieldFlags_Public);
  4863. if (fieldDef->mIsStatic)
  4864. fieldFlags = (BfFieldFlags)(fieldFlags | BfFieldFlags_Static);
  4865. if (fieldDef->mIsConst)
  4866. fieldFlags = (BfFieldFlags)(fieldFlags | BfFieldFlags_Const);
  4867. if (fieldDef->IsEnumCaseEntry())
  4868. fieldFlags = (BfFieldFlags)(fieldFlags | BfFieldFlags_EnumCase);
  4869. if (fieldDef->mIsReadOnly)
  4870. fieldFlags = (BfFieldFlags)(fieldFlags | BfFieldFlags_ReadOnly);
  4871. if (fieldInstance->IsAppendedObject())
  4872. fieldFlags = (BfFieldFlags)(fieldFlags | BfFieldFlags_Appended);
  4873. BfIRValue constValue;
  4874. BfIRValue constValue2;
  4875. if (fieldInstance->GetFieldDef()->mIsConst)
  4876. {
  4877. if (fieldInstance->mConstIdx != -1)
  4878. {
  4879. auto constant = typeInstance->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  4880. uint64 val = constant->mUInt64;
  4881. if (constant->mTypeCode == BfTypeCode_Float)
  4882. {
  4883. float f = (float)*(double*)&val;
  4884. val = *(uint32*)&f;
  4885. }
  4886. constValue = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, val);
  4887. if (is32Bit)
  4888. constValue2 = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, val >> 32);
  4889. }
  4890. }
  4891. else if (fieldInstance->GetFieldDef()->mIsStatic)
  4892. {
  4893. BfTypedValue refVal;
  4894. if (!mIsComptimeModule) // This can create circular reference issues for a `Self` static
  4895. refVal = ReferenceStaticField(fieldInstance);
  4896. if (refVal.mValue.IsConst())
  4897. {
  4898. auto constant = mBfIRBuilder->GetConstant(refVal.mValue);
  4899. if (constant->mConstType == BfConstType_GlobalVar)
  4900. {
  4901. auto globalVar = (BfGlobalVar*)constant;
  4902. if (globalVar->mName[0] == '#')
  4903. refVal = BfTypedValue();
  4904. }
  4905. }
  4906. if (!isComptimeArg)
  4907. {
  4908. if (refVal.IsAddr())
  4909. constValue = mBfIRBuilder->CreatePtrToInt(refVal.mValue, BfTypeCode_IntPtr);
  4910. else if (fieldInstance->IsAppendedObject())
  4911. constValue = mBfIRBuilder->CreatePtrToInt(refVal.mValue, BfTypeCode_IntPtr);
  4912. }
  4913. }
  4914. if (!constValue)
  4915. constValue = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, fieldInstance->mDataOffset);
  4916. BfIRValue result;
  4917. if (is32Bit)
  4918. {
  4919. if (!constValue2)
  4920. constValue2 = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0);
  4921. SizedArray<BfIRValue, 8> fieldVals =
  4922. {
  4923. emptyValueType,
  4924. fieldNameConst, // mName
  4925. GetConstValue(typeId, typeIdType), // mFieldTypeId
  4926. constValue, // mData
  4927. constValue2, // mDataHi
  4928. GetConstValue(fieldFlags, shortType), // mFlags
  4929. GetConstValue((isComptimeArg || mIsComptimeModule) ? fieldInstance->mFieldIdx : customAttrIdx, intType), // mCustomAttributesIdx
  4930. };
  4931. FixConstValueParams(reflectFieldDataType, fieldVals, isComptimeArg);
  4932. result = isComptimeArg ?
  4933. mBfIRBuilder->CreateConstAgg(mBfIRBuilder->MapTypeInst(reflectFieldDataType, BfIRPopulateType_Full), fieldVals) :
  4934. mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldDataType, BfIRPopulateType_Full), fieldVals);
  4935. }
  4936. else
  4937. {
  4938. SizedArray<BfIRValue, 8> fieldVals =
  4939. {
  4940. emptyValueType,
  4941. fieldNameConst, // mName
  4942. GetConstValue(typeId, typeIdType), // mFieldTypeId
  4943. constValue, // mData
  4944. GetConstValue(fieldFlags, shortType), // mFlags
  4945. GetConstValue((isComptimeArg || mIsComptimeModule) ? fieldInstance->mFieldIdx : customAttrIdx, intType), // mCustomAttributesIdx
  4946. };
  4947. FixConstValueParams(reflectFieldDataType, fieldVals, isComptimeArg);
  4948. result = isComptimeArg ?
  4949. mBfIRBuilder->CreateConstAgg(mBfIRBuilder->MapTypeInst(reflectFieldDataType, BfIRPopulateType_Full), fieldVals) :
  4950. mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldDataType, BfIRPopulateType_Full), fieldVals);
  4951. }
  4952. return result;
  4953. }
  4954. BfIRValue BfModule::CreateTypeData(BfType* type, Dictionary<int, int>& usedStringIdMap, bool forceReflectFields, bool needsTypeData, bool needsTypeNames, bool needsVData)
  4955. {
  4956. if ((IsHotCompile()) && (!type->mDirty))
  4957. return BfIRValue();
  4958. BfIRValue* irValuePtr = NULL;
  4959. if (mTypeDataRefs.TryGetValue(type, &irValuePtr))
  4960. {
  4961. return *irValuePtr;
  4962. }
  4963. BfTypeInstance* typeInstance = type->ToTypeInstance();
  4964. BfType* typeInstanceType = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef);
  4965. mBfIRBuilder->PopulateType(typeInstanceType, BfIRPopulateType_Full_ForceDefinition);
  4966. if (typeInstanceType == NULL)
  4967. {
  4968. AssertErrorState();
  4969. return BfIRValue();
  4970. }
  4971. BfIRValue typeTypeData;
  4972. int typeFlags = 0;
  4973. if (needsTypeData)
  4974. {
  4975. BfTypeInstance* typeInstanceTypeInstance = typeInstanceType->ToTypeInstance();
  4976. BfTypeInstance* typeDataSource = NULL;
  4977. if (typeInstance != NULL)
  4978. {
  4979. if (typeInstance->IsUnspecializedType())
  4980. {
  4981. typeDataSource = ResolveTypeDef(mCompiler->mReflectUnspecializedGenericType)->ToTypeInstance();
  4982. typeFlags |= BfTypeFlags_UnspecializedGeneric;
  4983. }
  4984. else if (typeInstance->IsArray())
  4985. {
  4986. typeDataSource = ResolveTypeDef(mCompiler->mReflectArrayType)->ToTypeInstance();
  4987. typeFlags |= BfTypeFlags_Array;
  4988. }
  4989. else if (typeInstance->IsGenericTypeInstance())
  4990. {
  4991. typeDataSource = ResolveTypeDef(mCompiler->mReflectSpecializedGenericType)->ToTypeInstance();
  4992. typeFlags |= BfTypeFlags_SpecializedGeneric;
  4993. }
  4994. else
  4995. typeDataSource = typeInstanceTypeInstance;
  4996. }
  4997. else if (type->IsPointer())
  4998. typeDataSource = ResolveTypeDef(mCompiler->mReflectPointerType)->ToTypeInstance();
  4999. else if (type->IsRef())
  5000. typeDataSource = ResolveTypeDef(mCompiler->mReflectRefType)->ToTypeInstance();
  5001. else if (type->IsSizedArray())
  5002. typeDataSource = ResolveTypeDef(mCompiler->mReflectSizedArrayType)->ToTypeInstance();
  5003. else if (type->IsConstExprValue())
  5004. typeDataSource = ResolveTypeDef(mCompiler->mReflectConstExprType)->ToTypeInstance();
  5005. else if (type->IsGenericParam())
  5006. {
  5007. typeFlags |= BfTypeFlags_GenericParam;
  5008. typeDataSource = ResolveTypeDef(mCompiler->mReflectGenericParamType)->ToTypeInstance();
  5009. }
  5010. else
  5011. typeDataSource = mContext->mBfTypeType;
  5012. if ((!mTypeDataRefs.ContainsKey(typeDataSource)) && (typeDataSource != type) && (!mIsComptimeModule))
  5013. {
  5014. CreateTypeData(typeDataSource, usedStringIdMap, false, true, needsTypeNames, true);
  5015. }
  5016. typeTypeData = CreateClassVDataGlobal(typeDataSource);
  5017. }
  5018. else
  5019. typeTypeData = CreateClassVDataGlobal(typeInstanceType->ToTypeInstance());
  5020. BfType* longType = GetPrimitiveType(BfTypeCode_Int64);
  5021. BfType* intType = GetPrimitiveType(BfTypeCode_Int32);
  5022. BfType* intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  5023. BfType* shortType = GetPrimitiveType(BfTypeCode_Int16);
  5024. BfType* byteType = GetPrimitiveType(BfTypeCode_Int8);
  5025. BfType* typeIdType = intType;
  5026. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  5027. auto voidPtrIRType = mBfIRBuilder->MapType(voidPtrType);
  5028. auto voidPtrPtrIRType = mBfIRBuilder->GetPointerTo(voidPtrIRType);
  5029. auto voidPtrNull = GetDefaultValue(voidPtrType);
  5030. SizedArray<BfIRValue, 4> typeValueParams;
  5031. GetConstClassValueParam(typeTypeData, typeValueParams);
  5032. FixConstValueParams(mContext->mBfObjectType, typeValueParams);
  5033. BfIRValue objectData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(mContext->mBfObjectType, BfIRPopulateType_Full), typeValueParams);
  5034. StringT<512> typeDataName;
  5035. if ((typeInstance != NULL) && (!typeInstance->IsTypeAlias()))
  5036. {
  5037. BfMangler::MangleStaticFieldName(typeDataName, mCompiler->GetMangleKind(), typeInstance, "sBfTypeData");
  5038. if (typeInstance->mTypeDef->IsGlobalsContainer())
  5039. typeDataName += "`G`" + typeInstance->mTypeDef->mProject->mName;
  5040. }
  5041. else
  5042. {
  5043. typeDataName += "sBfTypeData.";
  5044. BfMangler::Mangle(typeDataName, mCompiler->GetMangleKind(), type, mContext->mScratchModule);
  5045. }
  5046. int typeCode = BfTypeCode_None;
  5047. if (typeInstance != NULL)
  5048. {
  5049. BF_ASSERT((type->mDefineState >= BfTypeDefineState_DefinedAndMethodsSlotted) || mIsComptimeModule);
  5050. typeCode = typeInstance->mTypeDef->mTypeCode;
  5051. }
  5052. else if (type->IsPrimitiveType())
  5053. {
  5054. BfPrimitiveType* primType = (BfPrimitiveType*)type;
  5055. typeCode = primType->mTypeDef->mTypeCode;
  5056. }
  5057. else if (type->IsPointer())
  5058. {
  5059. typeCode = BfTypeCode_Pointer;
  5060. typeFlags |= BfTypeFlags_Pointer;
  5061. }
  5062. else if (type->IsRef())
  5063. {
  5064. typeCode = BfTypeCode_Pointer;
  5065. typeFlags |= BfTypeFlags_Pointer;
  5066. }
  5067. if (type->IsObject())
  5068. {
  5069. typeFlags |= BfTypeFlags_Object;
  5070. if (typeInstance->mDefineState >= BfTypeDefineState_DefinedAndMethodsSlotted)
  5071. {
  5072. BfMethodInstance* methodInstance = typeInstance->mVirtualMethodTable[mCompiler->GetVTableMethodOffset() + 0].mImplementingMethod;
  5073. if (methodInstance->GetOwner() != mContext->mBfObjectType)
  5074. typeFlags |= BfTypeFlags_HasDestructor;
  5075. }
  5076. }
  5077. if (type->IsStruct())
  5078. typeFlags |= BfTypeFlags_Struct;
  5079. if (type->IsInterface())
  5080. typeFlags |= BfTypeFlags_Interface;
  5081. if (type->IsBoxed())
  5082. {
  5083. typeFlags |= BfTypeFlags_Boxed;
  5084. if (((BfBoxedType*)type)->IsBoxedStructPtr())
  5085. typeFlags |= BfTypeFlags_Pointer;
  5086. }
  5087. if (type->IsPrimitiveType())
  5088. typeFlags |= BfTypeFlags_Primitive;
  5089. if (type->IsTypedPrimitive())
  5090. typeFlags |= BfTypeFlags_TypedPrimitive;
  5091. if (type->IsTuple())
  5092. typeFlags |= BfTypeFlags_Tuple;
  5093. if (type->IsNullable())
  5094. typeFlags |= BfTypeFlags_Nullable;
  5095. if (type->IsSizedArray())
  5096. typeFlags |= BfTypeFlags_SizedArray;
  5097. if (type->IsConstExprValue())
  5098. typeFlags |= BfTypeFlags_ConstExpr;
  5099. if (type->IsSplattable())
  5100. typeFlags |= BfTypeFlags_Splattable;
  5101. if (type->IsUnion())
  5102. typeFlags |= BfTypeFlags_Union;
  5103. if (type->IsDelegate())
  5104. typeFlags |= BfTypeFlags_Delegate;
  5105. if (type->IsFunction())
  5106. typeFlags |= BfTypeFlags_Function;
  5107. if ((type->mDefineState != BfTypeDefineState_CETypeInit) && (type->WantsGCMarking()))
  5108. typeFlags |= BfTypeFlags_WantsMarking;
  5109. int virtSlotIdx = -1;
  5110. if ((typeInstance != NULL) && (typeInstance->mSlotNum >= 0))
  5111. virtSlotIdx = typeInstance->mSlotNum + 1 + mCompiler->GetDynCastVDataCount();
  5112. int memberDataOffset = 0;
  5113. if (type->IsInterface())
  5114. memberDataOffset = virtSlotIdx * mSystem->mPtrSize;
  5115. else if (typeInstance != NULL)
  5116. {
  5117. for (auto& fieldInstance : typeInstance->mFieldInstances)
  5118. {
  5119. if (fieldInstance.mDataOffset != -1)
  5120. {
  5121. memberDataOffset = fieldInstance.mDataOffset;
  5122. break;
  5123. }
  5124. }
  5125. }
  5126. int boxedTypeId = 0;
  5127. if ((type->IsValueType()) || (type->IsWrappableType()))
  5128. {
  5129. auto boxedType = CreateBoxedType(type, false);
  5130. if ((boxedType != NULL) && (boxedType->mIsReified))
  5131. boxedTypeId = boxedType->mTypeId;
  5132. }
  5133. int stackCount = 0;
  5134. if ((typeInstance != NULL) && (typeInstance->mTypeOptionsIdx != -1))
  5135. {
  5136. auto typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  5137. if (typeOptions->mAllocStackTraceDepth != -1)
  5138. stackCount = BF_MIN(0xFF, BF_MAX(0x01, typeOptions->mAllocStackTraceDepth));
  5139. }
  5140. SizedArray<BfIRValue, 9> typeDataParams =
  5141. {
  5142. objectData,
  5143. GetConstValue(type->mSize, intType), // mSize
  5144. GetConstValue(type->mTypeId, typeIdType), // mTypeId
  5145. GetConstValue(boxedTypeId, typeIdType), // mBoxedType
  5146. GetConstValue(typeFlags, intType), // mTypeFlags
  5147. GetConstValue(memberDataOffset, intType), // mMemberDataOffset
  5148. GetConstValue(typeCode, byteType), // mTypeCode
  5149. GetConstValue(type->mAlign, byteType), // mAlign
  5150. GetConstValue(stackCount, byteType), // mAllocStackCountOverride
  5151. };
  5152. FixConstValueParams(mContext->mBfTypeType, typeDataParams);
  5153. auto typeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(mContext->mBfTypeType, BfIRPopulateType_Full), typeDataParams);
  5154. if (typeInstance == NULL)
  5155. {
  5156. BfIRValue typeDataVar;
  5157. if (needsTypeData)
  5158. {
  5159. if (type->IsPointer())
  5160. {
  5161. auto pointerType = (BfPointerType*)type;
  5162. SizedArray<BfIRValue, 3> pointerTypeDataParms =
  5163. {
  5164. typeData,
  5165. GetConstValue(pointerType->mElementType->mTypeId, typeIdType),
  5166. };
  5167. auto reflectPointerType = ResolveTypeDef(mCompiler->mReflectPointerType)->ToTypeInstance();
  5168. FixConstValueParams(reflectPointerType, pointerTypeDataParms);
  5169. auto pointerTypeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectPointerType, BfIRPopulateType_Full), pointerTypeDataParms);
  5170. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectPointerType), true,
  5171. BfIRLinkageType_External, pointerTypeData, typeDataName);
  5172. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5173. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  5174. }
  5175. else if (type->IsRef())
  5176. {
  5177. auto refType = (BfRefType*)type;
  5178. SizedArray<BfIRValue, 3> refTypeDataParms =
  5179. {
  5180. typeData,
  5181. GetConstValue(refType->mElementType->mTypeId, typeIdType),
  5182. GetConstValue((int8)refType->mRefKind, byteType),
  5183. };
  5184. auto reflectRefType = ResolveTypeDef(mCompiler->mReflectRefType)->ToTypeInstance();
  5185. FixConstValueParams(reflectRefType, refTypeDataParms);
  5186. auto refTypeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectRefType, BfIRPopulateType_Full), refTypeDataParms);
  5187. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectRefType), true,
  5188. BfIRLinkageType_External, refTypeData, typeDataName);
  5189. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5190. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  5191. }
  5192. else if (type->IsSizedArray())
  5193. {
  5194. auto sizedArrayType = (BfSizedArrayType*)type;
  5195. SizedArray<BfIRValue, 3> sizedArrayTypeDataParms =
  5196. {
  5197. typeData,
  5198. GetConstValue(sizedArrayType->mElementType->mTypeId, typeIdType),
  5199. GetConstValue(sizedArrayType->mElementCount, intType)
  5200. };
  5201. auto reflectSizedArrayType = ResolveTypeDef(mCompiler->mReflectSizedArrayType)->ToTypeInstance();
  5202. FixConstValueParams(reflectSizedArrayType, sizedArrayTypeDataParms);
  5203. auto sizedArrayTypeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectSizedArrayType, BfIRPopulateType_Full), sizedArrayTypeDataParms);
  5204. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectSizedArrayType), true,
  5205. BfIRLinkageType_External, sizedArrayTypeData, typeDataName);
  5206. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5207. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  5208. }
  5209. else if (type->IsConstExprValue())
  5210. {
  5211. auto constExprType = (BfConstExprValueType*)type;
  5212. SizedArray<BfIRValue, 3> constExprTypeDataParms =
  5213. {
  5214. typeData,
  5215. GetConstValue(constExprType->mType->mTypeId, typeIdType),
  5216. GetConstValue(constExprType->mValue.mInt64, longType)
  5217. };
  5218. auto reflectConstExprType = ResolveTypeDef(mCompiler->mReflectConstExprType)->ToTypeInstance();
  5219. FixConstValueParams(reflectConstExprType, constExprTypeDataParms);
  5220. auto ConstExprTypeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectConstExprType, BfIRPopulateType_Full), constExprTypeDataParms);
  5221. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectConstExprType), true,
  5222. BfIRLinkageType_External, ConstExprTypeData, typeDataName);
  5223. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5224. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  5225. }
  5226. else if (type->IsGenericParam())
  5227. {
  5228. auto genericParamType = (BfGenericParamType*)type;
  5229. SizedArray<BfIRValue, 3> genericParamTypeDataParms =
  5230. {
  5231. typeData
  5232. };
  5233. auto reflectGenericParamType = ResolveTypeDef(mCompiler->mReflectGenericParamType)->ToTypeInstance();
  5234. FixConstValueParams(reflectGenericParamType, genericParamTypeDataParms);
  5235. auto genericParamTypeData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectGenericParamType, BfIRPopulateType_Full), genericParamTypeDataParms);
  5236. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectGenericParamType), true,
  5237. BfIRLinkageType_External, genericParamTypeData, typeDataName);
  5238. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5239. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  5240. }
  5241. else
  5242. {
  5243. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(mContext->mBfTypeType), true,
  5244. BfIRLinkageType_External, typeData, typeDataName);
  5245. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5246. }
  5247. }
  5248. else
  5249. typeDataVar = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(mContext->mBfTypeType));
  5250. mTypeDataRefs[type] = typeDataVar;
  5251. return typeDataVar;
  5252. }
  5253. // Reserve position
  5254. mTypeDataRefs[typeInstance] = BfIRValue();
  5255. if ((typeInstance->IsReified()) && (!mIsComptimeModule))
  5256. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  5257. BfTypeDef* typeDef = typeInstance->mTypeDef;
  5258. StringT<512> mangledName;
  5259. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), typeInstance, typeInstance->mModule);
  5260. if (!mIsComptimeModule)
  5261. {
  5262. for (int methodIdx = 0; methodIdx < (int)typeDef->mMethods.size(); methodIdx++)
  5263. {
  5264. auto methodDef = typeDef->mMethods[methodIdx];
  5265. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  5266. if (methodInstance == NULL)
  5267. continue;
  5268. if (typeInstance->IsUnspecializedType())
  5269. continue;
  5270. if (!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, mProject))
  5271. {
  5272. if (methodInstance->mChainType == BfMethodChainType_ChainMember)
  5273. {
  5274. BF_ASSERT(!methodInstance->GetOwner()->IsUnspecializedType());
  5275. // We need to create an empty thunk for this chained method
  5276. BfIRFunction func = CreateFunctionFrom(methodInstance, false, methodInstance->mAlwaysInline);
  5277. mBfIRBuilder->SetActiveFunction(func);
  5278. auto block = mBfIRBuilder->CreateBlock("entry", true);
  5279. mBfIRBuilder->SetInsertPoint(block);
  5280. mBfIRBuilder->CreateRetVoid();
  5281. mBfIRBuilder->SetActiveFunction(BfIRFunction());
  5282. }
  5283. }
  5284. }
  5285. }
  5286. SizedArray<BfIRValue, 32> vData;
  5287. BfIRValue classVDataVar;
  5288. String classVDataName;
  5289. if (typeInstance->mSlotNum >= 0)
  5290. {
  5291. // For interfaces we ONLY emit the slot num
  5292. StringT<512> slotVarName;
  5293. BfMangler::MangleStaticFieldName(slotVarName, mCompiler->GetMangleKind(), typeInstance, "sBfSlotOfs");
  5294. auto intType = GetPrimitiveType(BfTypeCode_Int32);
  5295. auto slotNumVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(intType), true, BfIRLinkageType_External,
  5296. GetConstValue32(virtSlotIdx), slotVarName);
  5297. }
  5298. else if ((typeInstance->IsObject()) && (!typeInstance->IsUnspecializedType()) && (needsVData))
  5299. {
  5300. int dynCastDataElems = 0;
  5301. int numElements = 1;
  5302. int vDataOfs = 1; // The number of intptrs before the iface slot map
  5303. numElements += mCompiler->mMaxInterfaceSlots;
  5304. if (!typeInstance->IsInterface())
  5305. {
  5306. dynCastDataElems = 1 + mCompiler->mMaxInterfaceSlots;
  5307. numElements += mCompiler->GetDynCastVDataCount();
  5308. numElements += typeInstance->mVirtualMethodTableSize;
  5309. }
  5310. int expectNumElements = 0;
  5311. if (!typeDef->mIsStatic)
  5312. {
  5313. classVDataVar = CreateClassVDataGlobal(typeInstance, &expectNumElements, &classVDataName);
  5314. }
  5315. vData.push_back(BfIRValue()); // Type*
  5316. SizedArray<BfIRValue, 1> extVTableData;
  5317. SizedArrayImpl<BfIRValue>* vFuncDataExt = &extVTableData;
  5318. if (!typeInstance->IsInterface())
  5319. {
  5320. Array<int32> dynCastData;
  5321. if (typeInstance->IsBoxed())
  5322. {
  5323. auto underlyingType = typeInstance->GetUnderlyingType()->ToTypeInstance();
  5324. dynCastData.Add(underlyingType->mInheritanceId);
  5325. }
  5326. else
  5327. dynCastData.Add(typeInstance->mInheritanceId);
  5328. for (int i = 0; i < mCompiler->mMaxInterfaceSlots; i++)
  5329. dynCastData.Add(0);
  5330. dynCastData.Add(0);
  5331. auto checkTypeInst = typeInstance;
  5332. while (checkTypeInst != NULL)
  5333. {
  5334. for (auto&& interfaceEntry : checkTypeInst->mInterfaces)
  5335. {
  5336. if (interfaceEntry.mInterfaceType->mSlotNum >= 0)
  5337. {
  5338. if (dynCastData[interfaceEntry.mInterfaceType->mSlotNum + 1] == 0)
  5339. dynCastData[interfaceEntry.mInterfaceType->mSlotNum + 1] = interfaceEntry.mInterfaceType->mTypeId;
  5340. }
  5341. }
  5342. checkTypeInst = checkTypeInst->GetImplBaseType();
  5343. }
  5344. if (mSystem->mPtrSize == 8)
  5345. {
  5346. int intPtrCount = (dynCastDataElems + 1) / 2;
  5347. vDataOfs += intPtrCount;
  5348. uint64* intPtrData = (uint64*)&dynCastData[0];
  5349. for (int i = 0; i < intPtrCount; i++)
  5350. {
  5351. uint64 val = intPtrData[i];
  5352. if (val == 0)
  5353. {
  5354. vData.push_back(voidPtrNull);
  5355. }
  5356. else
  5357. {
  5358. auto intPtrVal = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, val);
  5359. vData.push_back(mBfIRBuilder->CreateBitCast(intPtrVal, voidPtrIRType));
  5360. }
  5361. }
  5362. }
  5363. else
  5364. {
  5365. int intPtrCount = dynCastDataElems;
  5366. vDataOfs += intPtrCount;
  5367. uint32* intPtrData = (uint32*)&dynCastData[0];
  5368. for (int i = 0; i < intPtrCount; i++)
  5369. {
  5370. uint32 val = intPtrData[i];
  5371. if (val == 0)
  5372. {
  5373. vData.push_back(voidPtrNull);
  5374. }
  5375. else
  5376. {
  5377. auto intPtrVal = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (int)val);
  5378. vData.push_back(mBfIRBuilder->CreateBitCast(intPtrVal, voidPtrIRType));
  5379. }
  5380. }
  5381. }
  5382. }
  5383. for (int iSlotIdx = 0; iSlotIdx < mCompiler->mMaxInterfaceSlots; iSlotIdx++)
  5384. vData.push_back(voidPtrNull);
  5385. struct _InterfaceMatchEntry
  5386. {
  5387. BfTypeInterfaceEntry* mEntry;
  5388. BfTypeInstance* mEntrySource;
  5389. Array<BfTypeInterfaceEntry*> mAmbiguousEntries;
  5390. };
  5391. int highestIFaceVirtIdx = 0;
  5392. Dictionary<BfTypeInstance*, _InterfaceMatchEntry> interfaceMap;
  5393. auto checkTypeInst = typeInstance;
  5394. bool forceInterfaceSet = false;
  5395. while (checkTypeInst != NULL)
  5396. {
  5397. for (auto&& interfaceEntry : checkTypeInst->mInterfaces)
  5398. {
  5399. highestIFaceVirtIdx = BF_MAX(highestIFaceVirtIdx, interfaceEntry.mStartVirtualIdx + interfaceEntry.mInterfaceType->mVirtualMethodTableSize);
  5400. if ((!mIsComptimeModule) && (!typeInstance->IsTypeMemberAccessible(interfaceEntry.mDeclaringType, mProject)))
  5401. continue;
  5402. _InterfaceMatchEntry* matchEntry = NULL;
  5403. if (interfaceMap.TryGetValue(interfaceEntry.mInterfaceType, &matchEntry))
  5404. {
  5405. BfTypeInstance* compareCheckTypeInst = checkTypeInst;
  5406. if (compareCheckTypeInst->IsBoxed())
  5407. compareCheckTypeInst = compareCheckTypeInst->GetUnderlyingType()->ToTypeInstance();
  5408. BfTypeInstance* compareEntrySource = matchEntry->mEntrySource;
  5409. if (compareEntrySource->IsBoxed())
  5410. compareEntrySource = compareEntrySource->GetUnderlyingType()->ToTypeInstance();
  5411. auto prevEntry = matchEntry->mEntry;
  5412. bool isBetter = TypeIsSubTypeOf(compareCheckTypeInst, compareEntrySource);
  5413. bool isWorse = TypeIsSubTypeOf(compareEntrySource, compareCheckTypeInst);
  5414. if ((!isBetter) && (!isWorse))
  5415. {
  5416. // Unboxed comparison to Object fix
  5417. if (compareCheckTypeInst == mContext->mBfObjectType)
  5418. isWorse = true;
  5419. else if (compareEntrySource == mContext->mBfObjectType)
  5420. isBetter = true;
  5421. }
  5422. if (forceInterfaceSet)
  5423. {
  5424. isBetter = true;
  5425. isWorse = false;
  5426. }
  5427. if (isBetter == isWorse)
  5428. CompareDeclTypes(interfaceEntry.mDeclaringType, prevEntry->mDeclaringType, isBetter, isWorse);
  5429. if (isBetter == isWorse)
  5430. {
  5431. if (matchEntry->mAmbiguousEntries.empty())
  5432. matchEntry->mAmbiguousEntries.push_back(prevEntry);
  5433. matchEntry->mAmbiguousEntries.push_back(&interfaceEntry);
  5434. continue;
  5435. }
  5436. else if (isBetter)
  5437. {
  5438. matchEntry->mEntry = &interfaceEntry;
  5439. matchEntry->mEntrySource = checkTypeInst;
  5440. matchEntry->mAmbiguousEntries.Clear();
  5441. }
  5442. else
  5443. continue;
  5444. }
  5445. else
  5446. {
  5447. _InterfaceMatchEntry matchEntry;
  5448. matchEntry.mEntry = &interfaceEntry;
  5449. matchEntry.mEntrySource = checkTypeInst;
  5450. interfaceMap[interfaceEntry.mInterfaceType] = matchEntry;
  5451. }
  5452. }
  5453. checkTypeInst = checkTypeInst->GetImplBaseType();
  5454. }
  5455. for (auto interfacePair : interfaceMap)
  5456. {
  5457. auto& interfaceMatchEntry = interfacePair.mValue;
  5458. if (!interfaceMatchEntry.mAmbiguousEntries.empty())
  5459. {
  5460. 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());
  5461. if (error != NULL)
  5462. {
  5463. for (auto ambiguiousEntry : interfaceMatchEntry.mAmbiguousEntries)
  5464. mCompiler->mPassInstance->MoreInfo("See other declaration", ambiguiousEntry->mDeclaringType->GetRefNode());
  5465. }
  5466. }
  5467. }
  5468. if ((!mIsComptimeModule) && (!typeInstance->IsInterface()) && (typeInstance->mVirtualMethodTableSize > 0) && (needsVData))
  5469. {
  5470. int startTabIdx = (int)vData.size();
  5471. SizedArray<BfTypeInstance*, 8> origVirtTypeStack;
  5472. BfTypeInstance* checkTypeInst = typeInstance;
  5473. while (checkTypeInst != NULL)
  5474. {
  5475. origVirtTypeStack.push_back(checkTypeInst);
  5476. checkTypeInst = checkTypeInst->GetImplBaseType();
  5477. }
  5478. Array<BfVirtualMethodEntry> origVTable;
  5479. int origVirtIdx = 0;
  5480. if (typeInstance->mTypeDef->mIsCombinedPartial)
  5481. {
  5482. HashSet<String> reslotNames;
  5483. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  5484. {
  5485. auto& entry = typeInstance->mVirtualMethodTable[virtIdx];
  5486. if (entry.mDeclaringMethod.mMethodNum == -1)
  5487. continue;
  5488. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  5489. if ((methodInstance == NULL) ||
  5490. ((!mIsComptimeModule) && (!typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject))))
  5491. {
  5492. if (origVTable.empty())
  5493. origVTable = typeInstance->mVirtualMethodTable;
  5494. BfMethodInstance* declMethodInstance = entry.mDeclaringMethod;
  5495. if ((mIsComptimeModule) || (typeInstance->IsTypeMemberAccessible(declMethodInstance->mMethodDef->mDeclaringType, mProject)))
  5496. {
  5497. // Prepare to reslot...
  5498. entry.mImplementingMethod = entry.mDeclaringMethod;
  5499. reslotNames.Add(declMethodInstance->mMethodDef->mName);
  5500. }
  5501. else
  5502. {
  5503. // Decl isn't accessible, null out entry
  5504. entry.mImplementingMethod = BfMethodRef();
  5505. }
  5506. }
  5507. }
  5508. if (!reslotNames.IsEmpty())
  5509. {
  5510. BfAmbiguityContext ambiguityContext;
  5511. ambiguityContext.mTypeInstance = typeInstance;
  5512. ambiguityContext.mModule = this;
  5513. ambiguityContext.mIsProjectSpecific = true;
  5514. ambiguityContext.mIsReslotting = true;
  5515. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  5516. for (auto& methodGroup : typeInstance->mMethodInstanceGroups)
  5517. {
  5518. auto methodInstance = methodGroup.mDefault;
  5519. if ((methodInstance == NULL) || (!methodInstance->mMethodDef->mIsOverride))
  5520. continue;
  5521. if (!reslotNames.Contains(methodInstance->mMethodDef->mName))
  5522. continue;
  5523. if ((!mIsComptimeModule) && (!typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject)))
  5524. continue;
  5525. if ((methodInstance->mChainType != BfMethodChainType_None) && (methodInstance->mChainType != BfMethodChainType_ChainHead))
  5526. continue;
  5527. SlotVirtualMethod(methodInstance, &ambiguityContext);
  5528. }
  5529. ambiguityContext.Finish();
  5530. }
  5531. }
  5532. bool isInExts = false;
  5533. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  5534. {
  5535. BfIRValue vValue = voidPtrNull;
  5536. auto& entry = typeInstance->mVirtualMethodTable[virtIdx];
  5537. BfModuleMethodInstance moduleMethodInst;
  5538. if (entry.mDeclaringMethod.mMethodNum == -1)
  5539. {
  5540. // mMethodNum of -1 indicates a vExt slot rather than an actual method reference
  5541. isInExts = true;
  5542. BfIRValue vExt = CreateClassVDataExtGlobal(entry.mDeclaringMethod.mTypeInstance, typeInstance, virtIdx);
  5543. if (vExt)
  5544. vValue = mBfIRBuilder->CreateBitCast(vExt, voidPtrIRType);
  5545. }
  5546. else
  5547. {
  5548. BfMethodInstance* declaringMethodInstance = (BfMethodInstance*)entry.mDeclaringMethod;
  5549. if ((declaringMethodInstance != NULL) && (declaringMethodInstance->mMethodInstanceGroup->IsImplemented()) && (declaringMethodInstance->mIsReified))
  5550. {
  5551. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].IsImplemented());
  5552. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].mDefault->mIsReified);
  5553. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  5554. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  5555. {
  5556. BF_ASSERT((mIsComptimeModule) || typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject));
  5557. moduleMethodInst = GetMethodInstanceAtIdx(methodInstance->mMethodInstanceGroup->mOwner, methodInstance->mMethodInstanceGroup->mMethodIdx, NULL, BfGetMethodInstanceFlag_NoInline);
  5558. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  5559. vValue = funcPtr;
  5560. }
  5561. }
  5562. }
  5563. while (origVirtTypeStack.size() != 0)
  5564. {
  5565. BfTypeInstance* useTypeInst = origVirtTypeStack[origVirtTypeStack.size() - 1];
  5566. if (virtIdx >= useTypeInst->mVirtualMethodTableSize)
  5567. {
  5568. // Moved past current base vtable size
  5569. origVirtTypeStack.pop_back();
  5570. continue;
  5571. }
  5572. if (origVirtIdx < useTypeInst->GetOrigVTableSize())
  5573. {
  5574. // We are within the original vtable size
  5575. int idx = startTabIdx + origVirtIdx;
  5576. origVirtIdx++;
  5577. vData.push_back(vValue);
  5578. }
  5579. else
  5580. {
  5581. // This is a new entry, it only gets added to the ext
  5582. BF_ASSERT(isInExts);
  5583. }
  5584. break;
  5585. }
  5586. }
  5587. if (!origVTable.empty())
  5588. typeInstance->mVirtualMethodTable = origVTable;
  5589. }
  5590. int ifaceMethodExtStart = (int)typeInstance->GetIFaceVMethodSize();
  5591. if (typeInstance->mHotTypeData != NULL)
  5592. {
  5593. if (typeInstance->mHotTypeData->mOrigInterfaceMethodsLength != -1)
  5594. ifaceMethodExtStart = typeInstance->mHotTypeData->mOrigInterfaceMethodsLength;
  5595. }
  5596. SizedArray<BfIRValue, 32> ifaceMethodExtData;
  5597. int iFaceMethodStartIdx = (int)vData.size();
  5598. vData.resize(iFaceMethodStartIdx + ifaceMethodExtStart);
  5599. for (int i = iFaceMethodStartIdx; i < iFaceMethodStartIdx + ifaceMethodExtStart; i++)
  5600. vData[i] = voidPtrNull;
  5601. if (expectNumElements != 0)
  5602. BF_ASSERT(expectNumElements == vData.size());
  5603. //BF_ASSERT(vData.size() == expectNumElements);
  5604. // for (int i = 0; i < (int)typeInstance->mInterfaceMethodTable.size() - ifaceMethodExtStart; i++)
  5605. // ifaceMethodExtData.Add(voidPtrNull);
  5606. int ifaceEntryIdx = iFaceMethodStartIdx;
  5607. for (auto& interfacePair : interfaceMap)
  5608. {
  5609. auto interfaceEntry = interfacePair.mValue.mEntry;
  5610. if (typeInstance->mDefineState < BfTypeDefineState_DefinedAndMethodsSlotted)
  5611. {
  5612. BF_ASSERT(mIsComptimeModule);
  5613. break;
  5614. }
  5615. bool makeEmpty = false;
  5616. if ((!mIsComptimeModule) && (!typeInstance->IsTypeMemberAccessible(interfaceEntry->mDeclaringType, mProject)))
  5617. makeEmpty = true;
  5618. int endVirtualIdx = interfaceEntry->mStartVirtualIdx + interfaceEntry->mInterfaceType->mVirtualMethodTableSize;
  5619. bool useExt = endVirtualIdx > ifaceMethodExtStart;
  5620. for (int methodIdx = 0; methodIdx < (int)interfaceEntry->mInterfaceType->mMethodInstanceGroups.size(); methodIdx++)
  5621. {
  5622. BfIRValue pushValue;
  5623. BfMethodInstance* ifaceMethodInstance = interfaceEntry->mInterfaceType->mMethodInstanceGroups[methodIdx].mDefault;
  5624. if ((ifaceMethodInstance == NULL) || (ifaceMethodInstance->mVirtualTableIdx == -1))
  5625. continue;
  5626. if ((!ifaceMethodInstance->mIsReified) || (!ifaceMethodInstance->mMethodInstanceGroup->IsImplemented()))
  5627. continue;
  5628. if (makeEmpty)
  5629. {
  5630. pushValue = voidPtrNull;
  5631. }
  5632. else
  5633. {
  5634. auto& methodRef = typeInstance->mInterfaceMethodTable[interfaceEntry->mStartInterfaceTableIdx + methodIdx].mMethodRef;
  5635. auto methodInstance = (BfMethodInstance*)methodRef;
  5636. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  5637. {
  5638. BF_ASSERT(methodInstance->mIsReified);
  5639. // This doesn't work because we may have FOREIGN methods from implicit interface methods
  5640. //auto moduleMethodInst = GetMethodInstanceAtIdx(methodRef.mTypeInstance, methodRef.mMethodNum);
  5641. auto moduleMethodInst = ReferenceExternalMethodInstance(methodInstance, BfGetMethodInstanceFlag_NoInline);
  5642. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  5643. pushValue = funcPtr;
  5644. }
  5645. else
  5646. {
  5647. pushValue = voidPtrNull;
  5648. }
  5649. }
  5650. int idx = interfaceEntry->mStartVirtualIdx + ifaceMethodInstance->mVirtualTableIdx;
  5651. if (idx < ifaceMethodExtStart)
  5652. {
  5653. BF_ASSERT(iFaceMethodStartIdx + idx < (int)vData.size());
  5654. vData[iFaceMethodStartIdx + idx] = pushValue;
  5655. }
  5656. else
  5657. {
  5658. BF_ASSERT(useExt);
  5659. int extIdx = idx - ifaceMethodExtStart;
  5660. while (extIdx >= ifaceMethodExtData.size())
  5661. ifaceMethodExtData.Add(voidPtrNull);
  5662. ifaceMethodExtData[extIdx] = pushValue;
  5663. }
  5664. }
  5665. }
  5666. if (typeInstance->IsBoxed())
  5667. {
  5668. BfBoxedType* boxedType = (BfBoxedType*)typeInstance;
  5669. if (boxedType->IsBoxedStructPtr())
  5670. {
  5671. // Force override of GetHashCode so we use the pointer address as the hash code
  5672. checkTypeInst = CreateBoxedType(ResolveTypeDef(mCompiler->mPointerTypeDef));
  5673. // Force override of GetHashCode so we use the pointer address as the hash code
  5674. for (auto& checkIFace : checkTypeInst->mInterfaces)
  5675. {
  5676. for (int methodIdx = 0; methodIdx < (int)checkIFace.mInterfaceType->mMethodInstanceGroups.size(); methodIdx++)
  5677. {
  5678. BfIRValue pushValue;
  5679. BfMethodInstance* ifaceMethodInstance = checkIFace.mInterfaceType->mMethodInstanceGroups[methodIdx].mDefault;
  5680. if ((ifaceMethodInstance == NULL) || (ifaceMethodInstance->mVirtualTableIdx == -1))
  5681. continue;
  5682. if ((!ifaceMethodInstance->mIsReified) || (!ifaceMethodInstance->mMethodInstanceGroup->IsImplemented()))
  5683. continue;
  5684. auto& methodRef = checkTypeInst->mInterfaceMethodTable[checkIFace.mStartInterfaceTableIdx + methodIdx].mMethodRef;
  5685. auto methodInstance = (BfMethodInstance*)methodRef;
  5686. BF_ASSERT(methodInstance->mIsReified);
  5687. // This doesn't work because we may have FOREIGN methods from implicit interface methods
  5688. //auto moduleMethodInst = GetMethodInstanceAtIdx(methodRef.mTypeInstance, methodRef.mMethodNum);
  5689. auto moduleMethodInst = ReferenceExternalMethodInstance(methodInstance, BfGetMethodInstanceFlag_NoInline);
  5690. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  5691. int idx = checkIFace.mStartVirtualIdx + ifaceMethodInstance->mVirtualTableIdx;
  5692. vData[iFaceMethodStartIdx + idx] = funcPtr;
  5693. }
  5694. }
  5695. }
  5696. }
  5697. if ((needsVData) && (!typeInstance->mTypeDef->mIsStatic) && (!mIsComptimeModule))
  5698. {
  5699. BfIRValue ifaceMethodExtVar;
  5700. if ((!ifaceMethodExtData.IsEmpty()) && (!mIsComptimeModule))
  5701. {
  5702. StringT<512> classVDataName;
  5703. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), typeInstance, "bf_hs_replace_IFaceExt");
  5704. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), (int)ifaceMethodExtData.size());
  5705. ifaceMethodExtVar = mBfIRBuilder->CreateGlobalVariable(arrayType, true,
  5706. BfIRLinkageType_External, BfIRValue(), classVDataName);
  5707. BfIRType extVTableType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)ifaceMethodExtData.size());
  5708. BfIRValue extVTableConst = mBfIRBuilder->CreateConstAgg_Value(extVTableType, ifaceMethodExtData);
  5709. mBfIRBuilder->GlobalVar_SetInitializer(ifaceMethodExtVar, extVTableConst);
  5710. }
  5711. for (auto& ifaceInstPair : interfaceMap)
  5712. {
  5713. auto interfaceEntry = ifaceInstPair.mValue.mEntry;
  5714. int slotNum = interfaceEntry->mInterfaceType->mSlotNum;
  5715. if (slotNum >= 0)
  5716. {
  5717. BfIRValue vtablePtr;
  5718. int idx = interfaceEntry->mStartVirtualIdx;
  5719. int endVirtualIdx = interfaceEntry->mStartVirtualIdx + interfaceEntry->mInterfaceType->mVirtualMethodTableSize;
  5720. if ((endVirtualIdx > ifaceMethodExtStart) && (ifaceMethodExtVar))
  5721. vtablePtr = mBfIRBuilder->CreateInBoundsGEP(ifaceMethodExtVar, 0, interfaceEntry->mStartVirtualIdx - ifaceMethodExtStart);
  5722. else
  5723. vtablePtr = mBfIRBuilder->CreateInBoundsGEP(classVDataVar, 0, iFaceMethodStartIdx + interfaceEntry->mStartVirtualIdx);
  5724. int slotVirtIdx = slotNum + vDataOfs;
  5725. if (vData[slotVirtIdx] == voidPtrNull)
  5726. {
  5727. vData[slotVirtIdx] = mBfIRBuilder->CreateBitCast(vtablePtr, voidPtrIRType);
  5728. }
  5729. else
  5730. {
  5731. if (mCompiler->IsHotCompile())
  5732. Fail("Interface slot collision error. Restart program or undo interface changes.", typeDef->GetRefNode());
  5733. else
  5734. Fail("Interface slot collision error", typeDef->GetRefNode());
  5735. }
  5736. }
  5737. }
  5738. }
  5739. }
  5740. BfIRValue typeNameConst;
  5741. BfIRValue namespaceConst;
  5742. if (needsTypeNames)
  5743. {
  5744. typeNameConst = GetStringObjectValue(typeDef->mName->mString, !mIsComptimeModule);
  5745. namespaceConst = GetStringObjectValue(typeDef->mNamespace.ToString(), !mIsComptimeModule);
  5746. }
  5747. else
  5748. {
  5749. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  5750. typeNameConst = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(stringType));
  5751. namespaceConst = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(stringType));
  5752. }
  5753. int baseTypeId = 0;
  5754. if (typeInstance->mBaseType != NULL)
  5755. {
  5756. baseTypeId = typeInstance->mBaseType->mTypeId;
  5757. }
  5758. BfTypeOptions* typeOptions = NULL;
  5759. if (typeInstance->mTypeOptionsIdx >= 0)
  5760. typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  5761. SizedArray<BfIRValue, 16> customAttrs;
  5762. BfTypeInstance* attributeType = mContext->mUnreifiedModule->ResolveTypeDef(mCompiler->mAttributeTypeDef)->ToTypeInstance();
  5763. BfIRValue castedClassVData;
  5764. if (classVDataVar)
  5765. castedClassVData = mBfIRBuilder->CreateBitCast(classVDataVar, mBfIRBuilder->MapType(mContext->mBfClassVDataPtrType));
  5766. else
  5767. castedClassVData = GetDefaultValue(mContext->mBfClassVDataPtrType);
  5768. bool freflectIncludeTypeData = false;
  5769. bool reflectIncludeAllFields = false;
  5770. bool reflectIncludeAllMethods = false;
  5771. if (TypeIsSubTypeOf(typeInstance, attributeType))
  5772. {
  5773. reflectIncludeAllFields = true;
  5774. reflectIncludeAllMethods = true;
  5775. }
  5776. BfReflectKind reflectKind = BfReflectKind_Type;
  5777. auto _GetReflectUserFromDirective = [&](BfAttributeDirective* attributesDirective, BfAttributeTargets attrTarget)
  5778. {
  5779. BfReflectKind reflectKind = BfReflectKind_None;
  5780. auto customAttrs = GetCustomAttributes(attributesDirective, attrTarget);
  5781. if (customAttrs != NULL)
  5782. {
  5783. for (auto& attr : customAttrs->mAttributes)
  5784. {
  5785. reflectKind = (BfReflectKind)(reflectKind | GetUserReflectKind(attr.mType));
  5786. }
  5787. delete customAttrs;
  5788. }
  5789. return reflectKind;
  5790. };
  5791. reflectKind = GetReflectKind(reflectKind, typeInstance);
  5792. // Fields
  5793. BfType* reflectFieldDataType = ResolveTypeDef(mCompiler->mReflectFieldDataDef);
  5794. BfIRValue emptyValueType = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance()->mBaseType), SizedArray<BfIRValue, 1>());
  5795. auto _HandleCustomAttrs = [&](BfCustomAttributes* customAttributes)
  5796. {
  5797. if (customAttributes == NULL)
  5798. return -1;
  5799. Array<BfCustomAttribute*> reflectAttributes;
  5800. for (auto& attr : customAttributes->mAttributes)
  5801. {
  5802. bool wantAttribute = false;
  5803. if (attr.mType->mCustomAttributes != NULL)
  5804. {
  5805. auto usageAttribute = attr.mType->mCustomAttributes->Get(mCompiler->mAttributeUsageAttributeTypeDef);
  5806. if (usageAttribute != NULL)
  5807. {
  5808. // Check for Flags arg
  5809. if (usageAttribute->mCtorArgs.size() < 2)
  5810. continue;
  5811. auto constant = attr.mType->mConstHolder->GetConstant(usageAttribute->mCtorArgs[1]);
  5812. if (constant == NULL)
  5813. continue;
  5814. if (constant->mTypeCode == BfTypeCode_Boolean)
  5815. continue;
  5816. if ((constant->mInt8 & BfCustomAttributeFlags_ReflectAttribute) != 0)
  5817. wantAttribute = true;
  5818. }
  5819. }
  5820. if ((wantAttribute) && (attr.mType->mIsReified))
  5821. {
  5822. reflectAttributes.Add(&attr);
  5823. }
  5824. }
  5825. if (reflectAttributes.size() == 0)
  5826. return -1;
  5827. #define PUSH_INT8(val) data.push_back((uint8)val)
  5828. #define PUSH_INT16(val) { data.push_back(val & 0xFF); data.push_back((val >> 8) & 0xFF); }
  5829. #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); }
  5830. SizedArray<uint8, 16> data;
  5831. int customAttrIdx = (int)customAttrs.size();
  5832. data.push_back((uint8)reflectAttributes.size());
  5833. for (auto attr : reflectAttributes)
  5834. {
  5835. // Size prefix
  5836. int sizeIdx = (int)data.size();
  5837. PUSH_INT16(0); // mSize
  5838. PUSH_INT32(attr->mType->mTypeId); // mType
  5839. int ctorIdx = -1;
  5840. int ctorCount = 0;
  5841. attr->mType->mTypeDef->PopulateMemberSets();
  5842. BfMemberSetEntry* entry;
  5843. if (attr->mType->mTypeDef->mMethodSet.TryGetWith(String("__BfCtor"), &entry))
  5844. {
  5845. BfMethodDef* nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  5846. while (nextMethodDef != NULL)
  5847. {
  5848. if (nextMethodDef == attr->mCtor)
  5849. ctorIdx = ctorCount;
  5850. nextMethodDef = nextMethodDef->mNextWithSameName;
  5851. ctorCount++;
  5852. }
  5853. }
  5854. BF_ASSERT(ctorIdx != -1);
  5855. if (ctorIdx != -1)
  5856. ctorIdx = (ctorCount - 1) - ctorIdx;
  5857. PUSH_INT16(ctorIdx);
  5858. auto ctorMethodInstance = GetRawMethodInstanceAtIdx(attr->mType, attr->mCtor->mIdx);
  5859. int argIdx = 0;
  5860. for (auto arg : attr->mCtorArgs)
  5861. {
  5862. auto argType = ctorMethodInstance->GetParamType(argIdx);
  5863. EncodeAttributeData(typeInstance, argType, arg, data, usedStringIdMap);
  5864. argIdx++;
  5865. }
  5866. int size = (int)data.size() - sizeIdx;
  5867. *((uint16*)&data[sizeIdx]) = size;
  5868. }
  5869. #undef PUSH_INT8
  5870. #undef PUSH_INT16
  5871. #undef PUSH_INT32
  5872. SizedArray<BfIRValue, 16> dataValues;
  5873. for (uint8 val : data)
  5874. dataValues.push_back(GetConstValue8(val));
  5875. auto dataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(byteType), (int)data.size());
  5876. auto customAttrConst = mBfIRBuilder->CreateConstAgg_Value(dataArrayType, dataValues);
  5877. BfIRValue customAttrArray = mBfIRBuilder->CreateGlobalVariable(dataArrayType, true, BfIRLinkageType_Internal,
  5878. customAttrConst, typeDataName + StrFormat(".customAttr%d", customAttrIdx));
  5879. BfIRValue customAttrArrayPtr = mBfIRBuilder->CreateBitCast(customAttrArray, voidPtrIRType);
  5880. customAttrs.push_back(customAttrArrayPtr);
  5881. return customAttrIdx;
  5882. };
  5883. int typeCustomAttrIdx = _HandleCustomAttrs(typeInstance->mCustomAttributes);
  5884. SizedArray<int, 16> reflectFieldIndices;
  5885. for (int pass = 0; pass < 2; pass++)
  5886. {
  5887. bool skippedField = false;
  5888. reflectFieldIndices.clear();
  5889. for (int fieldIdx = 0; fieldIdx < (int)typeInstance->mFieldInstances.size(); fieldIdx++)
  5890. {
  5891. BfFieldInstance* fieldInstance = &typeInstance->mFieldInstances[fieldIdx];
  5892. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  5893. if (fieldDef == NULL)
  5894. continue;
  5895. auto fieldReflectKind = (BfReflectKind)(reflectKind & ~BfReflectKind_User);
  5896. bool includeField = reflectIncludeAllFields;
  5897. if (fieldInstance->mCustomAttributes != NULL)
  5898. {
  5899. for (auto& customAttr : fieldInstance->mCustomAttributes->mAttributes)
  5900. {
  5901. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  5902. {
  5903. includeField = true;
  5904. }
  5905. else
  5906. {
  5907. auto userReflectKind = GetUserReflectKind(customAttr.mType);
  5908. fieldReflectKind = (BfReflectKind)(fieldReflectKind | userReflectKind);
  5909. }
  5910. }
  5911. }
  5912. if ((fieldReflectKind & BfReflectKind_User) != 0)
  5913. includeField = true;
  5914. if ((!fieldDef->mIsStatic) && ((fieldReflectKind & BfReflectKind_NonStaticFields) != 0))
  5915. includeField = true;
  5916. if ((fieldDef->mIsStatic) && ((fieldReflectKind & BfReflectKind_StaticFields) != 0))
  5917. includeField = true;
  5918. if ((!fieldDef->mIsStatic) && (typeOptions != NULL))
  5919. includeField = typeOptions->Apply(includeField, BfOptionFlags_ReflectNonStaticFields);
  5920. if ((fieldDef->mIsStatic) && (typeOptions != NULL))
  5921. includeField = typeOptions->Apply(includeField, BfOptionFlags_ReflectStaticFields);
  5922. includeField |= forceReflectFields;
  5923. if (!includeField)
  5924. {
  5925. skippedField = true;
  5926. continue;
  5927. }
  5928. reflectFieldIndices.Add(fieldIdx);
  5929. }
  5930. // For a splattable type, we need to either include all fields or zero fields. This is to allow us to correctly splat
  5931. // params for reflected method calls even if we don't have reflection field info for the splatted type. This is
  5932. // possible because we write out a SplatData structure containing just TypeIds in that case
  5933. if (pass == 0)
  5934. {
  5935. if (!typeInstance->IsSplattable())
  5936. break;
  5937. if (!skippedField)
  5938. break;
  5939. if (reflectFieldIndices.size() == 0)
  5940. break;
  5941. }
  5942. }
  5943. SizedArray<BfIRValue, 16> fieldTypes;
  5944. bool is32Bit = mCompiler->mSystem->mPtrSize == 4;
  5945. if ((typeInstance->IsPayloadEnum()) && (!typeInstance->IsBoxed()))
  5946. {
  5947. BfType* payloadType = typeInstance->GetUnionInnerType();
  5948. if (!payloadType->IsValuelessType())
  5949. {
  5950. BfIRValue payloadNameConst = GetStringObjectValue("$payload", !mIsComptimeModule);
  5951. SizedArray<BfIRValue, 8> payloadFieldVals;
  5952. if (is32Bit)
  5953. {
  5954. payloadFieldVals =
  5955. {
  5956. emptyValueType,
  5957. payloadNameConst, // mName
  5958. GetConstValue(payloadType->mTypeId, typeIdType), // mFieldTypeId
  5959. GetConstValue(0, intPtrType), // mData
  5960. GetConstValue(0, intPtrType), // mDataHi
  5961. GetConstValue(BfFieldFlags_SpecialName | BfFieldFlags_EnumPayload, shortType), // mFlags
  5962. GetConstValue(-1, intType), // mCustomAttributesIdx
  5963. };
  5964. }
  5965. else
  5966. {
  5967. payloadFieldVals =
  5968. {
  5969. emptyValueType,
  5970. payloadNameConst, // mName
  5971. GetConstValue(payloadType->mTypeId, typeIdType), // mFieldTypeId
  5972. GetConstValue(0, intPtrType), // mData
  5973. GetConstValue(BfFieldFlags_SpecialName | BfFieldFlags_EnumPayload, shortType), // mFlags
  5974. GetConstValue(-1, intType), // mCustomAttributesIdx
  5975. };
  5976. }
  5977. FixConstValueParams(reflectFieldDataType->ToTypeInstance(), payloadFieldVals);
  5978. auto payloadFieldData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance(), BfIRPopulateType_Full), payloadFieldVals);
  5979. fieldTypes.push_back(payloadFieldData);
  5980. }
  5981. BfType* dscrType = typeInstance->GetDiscriminatorType();
  5982. BfIRValue dscrNameConst = GetStringObjectValue("$discriminator", !mIsComptimeModule);
  5983. SizedArray<BfIRValue, 8> dscrFieldVals;
  5984. if (is32Bit)
  5985. {
  5986. dscrFieldVals =
  5987. {
  5988. emptyValueType,
  5989. dscrNameConst, // mName
  5990. GetConstValue(dscrType->mTypeId, typeIdType), // mFieldTypeId
  5991. GetConstValue(BF_ALIGN(payloadType->mSize, dscrType->mAlign), intPtrType), // mData
  5992. GetConstValue(0, intPtrType), // mDataHi
  5993. GetConstValue(BfFieldFlags_SpecialName | BfFieldFlags_EnumDiscriminator, shortType), // mFlags
  5994. GetConstValue(-1, intType), // mCustomAttributesIdx
  5995. };
  5996. }
  5997. else
  5998. {
  5999. dscrFieldVals =
  6000. {
  6001. emptyValueType,
  6002. dscrNameConst, // mName
  6003. GetConstValue(dscrType->mTypeId, typeIdType), // mFieldTypeId
  6004. GetConstValue(BF_ALIGN(payloadType->mSize, dscrType->mAlign), intPtrType), // mData
  6005. GetConstValue(BfFieldFlags_SpecialName | BfFieldFlags_EnumDiscriminator, shortType), // mFlags
  6006. GetConstValue(-1, intType), // mCustomAttributesIdx
  6007. };
  6008. }
  6009. auto dscrFieldData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance(), BfIRPopulateType_Full), dscrFieldVals);
  6010. fieldTypes.push_back(dscrFieldData);
  6011. }
  6012. for (auto fieldIdx : reflectFieldIndices)
  6013. {
  6014. if (!needsTypeData)
  6015. break;
  6016. BfFieldInstance* fieldInstance = &typeInstance->mFieldInstances[fieldIdx];
  6017. fieldTypes.push_back(CreateFieldData(fieldInstance, _HandleCustomAttrs(fieldInstance->mCustomAttributes)));
  6018. }
  6019. auto reflectFieldDataIRType = mBfIRBuilder->MapType(reflectFieldDataType);
  6020. BfIRValue fieldDataPtr;
  6021. BfIRType fieldDataPtrType = mBfIRBuilder->GetPointerTo(reflectFieldDataIRType);
  6022. if (fieldTypes.size() == 0)
  6023. {
  6024. if ((type->IsSplattable()) && (type->IsStruct()) && (!type->IsValuelessType()) && (!typeInstance->mIsCRepr))
  6025. {
  6026. BfTypeInstance* reflectFieldSplatDataType = ResolveTypeDef(mCompiler->mReflectFieldSplatDataDef)->ToTypeInstance();
  6027. SizedArray<BfIRValue, 3> splatTypes;
  6028. SizedArray<BfIRValue, 3> splatOffsets;
  6029. std::function<void(BfType*, int)> _CheckSplat = [&](BfType* checkType, int offset)
  6030. {
  6031. auto checkTypeInstance = checkType->ToTypeInstance();
  6032. if ((checkTypeInstance != NULL) && (checkTypeInstance->IsValueType()) && (checkTypeInstance->IsDataIncomplete()))
  6033. PopulateType(checkTypeInstance);
  6034. if (checkType->IsStruct())
  6035. {
  6036. int dataEnd = offset;
  6037. if (checkTypeInstance->mBaseType != NULL)
  6038. _CheckSplat(checkTypeInstance->mBaseType, offset);
  6039. if (checkTypeInstance->mIsUnion)
  6040. {
  6041. BfType* unionInnerType = checkTypeInstance->GetUnionInnerType();
  6042. _CheckSplat(unionInnerType, offset);
  6043. }
  6044. else
  6045. {
  6046. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  6047. {
  6048. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  6049. if (fieldInstance->mDataIdx >= 0)
  6050. {
  6051. _CheckSplat(fieldInstance->GetResolvedType(), offset + fieldInstance->mDataOffset);
  6052. dataEnd = offset + fieldInstance->mDataOffset + fieldInstance->mResolvedType->mSize;
  6053. }
  6054. }
  6055. }
  6056. if (checkTypeInstance->IsEnum())
  6057. {
  6058. // Add discriminator
  6059. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  6060. if (checkTypeInstance->mPacking > 0)
  6061. dataEnd = BF_ALIGN(dataEnd, dscrType->mAlign);
  6062. _CheckSplat(dscrType, dataEnd);
  6063. }
  6064. }
  6065. else if (checkType->IsMethodRef())
  6066. {
  6067. // auto methodRefType = (BfMethodRefType*)checkType;
  6068. // for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  6069. // {
  6070. // if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  6071. // _CheckSplat(methodRefType->GetCaptureType(dataIdx), offsetof);
  6072. // else
  6073. // dataLambda(methodRefType->GetCaptureType(dataIdx));
  6074. // }
  6075. }
  6076. else if (!checkType->IsValuelessType())
  6077. {
  6078. splatTypes.Add(GetConstValue(checkType->mTypeId, typeIdType));
  6079. splatOffsets.Add(GetConstValue(offset, intType));
  6080. }
  6081. };
  6082. _CheckSplat(type, 0);
  6083. while (splatTypes.size() < 3)
  6084. {
  6085. splatTypes.Add(GetConstValue(0, typeIdType));
  6086. splatOffsets.Add(GetConstValue(0, intType));
  6087. }
  6088. BfIRValue splatTypesConst = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapType(reflectFieldSplatDataType->mFieldInstances[0].mResolvedType), splatTypes);
  6089. BfIRValue splatOffsetsConst = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapType(reflectFieldSplatDataType->mFieldInstances[1].mResolvedType), splatOffsets);
  6090. SizedArray<BfIRValue, 8> splatVals =
  6091. {
  6092. emptyValueType,
  6093. splatTypesConst,
  6094. splatOffsetsConst
  6095. };
  6096. auto fieldSplatData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectFieldSplatDataType->ToTypeInstance(), BfIRPopulateType_Full), splatVals);
  6097. BfIRValue fieldDataArray = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(reflectFieldSplatDataType), true, BfIRLinkageType_Internal,
  6098. fieldSplatData, typeDataName + ".splats");
  6099. fieldDataPtr = mBfIRBuilder->CreateBitCast(fieldDataArray, fieldDataPtrType);
  6100. }
  6101. else
  6102. fieldDataPtr = mBfIRBuilder->CreateConstNull(fieldDataPtrType);
  6103. }
  6104. else
  6105. {
  6106. BfIRType fieldDataConstType = mBfIRBuilder->GetSizedArrayType(reflectFieldDataIRType, (int)fieldTypes.size());
  6107. BfIRValue fieldDataConst = mBfIRBuilder->CreateConstAgg_Value(fieldDataConstType, fieldTypes);
  6108. BfIRValue fieldDataArray = mBfIRBuilder->CreateGlobalVariable(fieldDataConstType, true, BfIRLinkageType_Internal,
  6109. fieldDataConst, "fields." + typeDataName);
  6110. fieldDataPtr = mBfIRBuilder->CreateBitCast(fieldDataArray, fieldDataPtrType);
  6111. }
  6112. /// Methods
  6113. BfType* reflectMethodDataType = ResolveTypeDef(mCompiler->mReflectMethodDataDef);
  6114. BfType* reflectParamDataType = ResolveTypeDef(mCompiler->mReflectParamDataDef);
  6115. BfType* reflectParamDataPtrType = CreatePointerType(reflectParamDataType);
  6116. struct _SortedMethodInfo
  6117. {
  6118. BfMethodDef* mMethodDef;
  6119. BfMethodCustomAttributes* mMethodCustomAttributes;
  6120. };
  6121. Array<_SortedMethodInfo> sortedMethodList;
  6122. SizedArray<BfIRValue, 16> methodTypes;
  6123. for (int methodIdx = 0; methodIdx < (int)typeDef->mMethods.size(); methodIdx++)
  6124. {
  6125. if (!needsTypeData)
  6126. break;
  6127. // Disable const method reflection info for now
  6128. if (mIsComptimeModule)
  6129. break;
  6130. auto methodInstanceGroup = &typeInstance->mMethodInstanceGroups[methodIdx];
  6131. if (!methodInstanceGroup->IsImplemented())
  6132. continue;
  6133. auto methodDef = typeDef->mMethods[methodIdx];
  6134. if (methodDef->mIsNoReflect)
  6135. continue;
  6136. if (methodDef->mHasComptime)
  6137. continue;
  6138. auto defaultMethod = methodInstanceGroup->mDefault;
  6139. if (defaultMethod == NULL)
  6140. continue;
  6141. if (defaultMethod->mIsUnspecialized)
  6142. continue;
  6143. if (!defaultMethod->mIsReified)
  6144. continue;
  6145. if ((defaultMethod->mChainType == BfMethodChainType_ChainMember) || (defaultMethod->mChainType == BfMethodChainType_ChainSkip))
  6146. continue;
  6147. if (defaultMethod->mMethodDef->mMethodType == BfMethodType_CtorNoBody)
  6148. continue;
  6149. auto methodReflectKind = (BfReflectKind)(reflectKind & ~BfReflectKind_User);
  6150. bool includeMethod = reflectIncludeAllMethods;
  6151. BfMethodCustomAttributes* methodCustomAttributes = NULL;
  6152. if ((defaultMethod->mMethodInfoEx != NULL) && (defaultMethod->mMethodInfoEx->mMethodCustomAttributes != NULL) && (defaultMethod->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes != NULL))
  6153. {
  6154. methodCustomAttributes = defaultMethod->mMethodInfoEx->mMethodCustomAttributes;
  6155. for (auto& customAttr : defaultMethod->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes->mAttributes)
  6156. {
  6157. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  6158. {
  6159. includeMethod = true;
  6160. }
  6161. else
  6162. {
  6163. auto userReflectKind = GetUserReflectKind(customAttr.mType);
  6164. methodReflectKind = (BfReflectKind)(methodReflectKind | userReflectKind);
  6165. }
  6166. }
  6167. }
  6168. if ((!mIsComptimeModule) && (!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, mProject)))
  6169. continue;
  6170. //
  6171. {
  6172. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  6173. if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  6174. {
  6175. for (BfParameterDeclaration* paramDecl : methodDeclaration->mParams)
  6176. {
  6177. if (paramDecl->mAttributes != NULL)
  6178. methodReflectKind = (BfReflectKind)(methodReflectKind | _GetReflectUserFromDirective(paramDecl->mAttributes, BfAttributeTargets_Parameter));
  6179. }
  6180. }
  6181. }
  6182. if ((methodReflectKind & (BfReflectKind_Methods | BfReflectKind_User)) != 0)
  6183. includeMethod = true;
  6184. if ((methodDef->mIsStatic) && ((methodReflectKind & BfReflectKind_StaticMethods) != 0))
  6185. includeMethod = true;
  6186. if ((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend))
  6187. {
  6188. if ((methodReflectKind & BfReflectKind_Constructors) != 0)
  6189. includeMethod = true;
  6190. if ((methodDef->IsDefaultCtor()) && ((methodReflectKind & BfReflectKind_DefaultConstructor) != 0))
  6191. includeMethod = true;
  6192. }
  6193. if ((!includeMethod) && (typeOptions != NULL))
  6194. includeMethod = ApplyTypeOptionMethodFilters(includeMethod, methodDef, typeOptions);
  6195. if (!includeMethod)
  6196. continue;
  6197. sortedMethodList.Add({ methodDef, methodCustomAttributes });
  6198. }
  6199. auto _GetMethodKind = [](BfMethodDef* methodDef)
  6200. {
  6201. if (methodDef->mMethodType == BfMethodType_Ctor)
  6202. return 0;
  6203. return 1;
  6204. };
  6205. std::sort(sortedMethodList.begin(), sortedMethodList.end(), [_GetMethodKind](const _SortedMethodInfo& lhs, const _SortedMethodInfo& rhs)
  6206. {
  6207. int lhsKind = _GetMethodKind(lhs.mMethodDef);
  6208. int rhsKind = _GetMethodKind(rhs.mMethodDef);
  6209. if (lhsKind != rhsKind)
  6210. return lhsKind < rhsKind;
  6211. if (lhs.mMethodDef->mName != rhs.mMethodDef->mName)
  6212. return lhs.mMethodDef->mName < rhs.mMethodDef->mName;
  6213. return lhs.mMethodDef->mIdx < rhs.mMethodDef->mIdx;
  6214. });
  6215. for (auto& methodInfo : sortedMethodList)
  6216. {
  6217. auto methodDef = methodInfo.mMethodDef;
  6218. int methodIdx = methodDef->mIdx;
  6219. auto methodInstanceGroup = &typeInstance->mMethodInstanceGroups[methodIdx];
  6220. auto defaultMethod = methodInstanceGroup->mDefault;
  6221. BfModuleMethodInstance moduleMethodInstance;
  6222. BfIRValue funcVal = voidPtrNull;
  6223. if (((!typeInstance->IsBoxed()) || (!methodDef->mIsStatic)) &&
  6224. (!typeInstance->IsUnspecializedType()) &&
  6225. (methodDef->mMethodType != BfMethodType_Ignore) &&
  6226. (methodDef->mMethodType != BfMethodType_Mixin) &&
  6227. (!methodDef->mIsAbstract) &&
  6228. (methodDef->mGenericParams.size() == 0))
  6229. {
  6230. moduleMethodInstance = GetMethodInstanceAtIdx(typeInstance, methodIdx, NULL, BfGetMethodInstanceFlag_NoInline);
  6231. if (moduleMethodInstance.mFunc)
  6232. funcVal = mBfIRBuilder->CreateBitCast(moduleMethodInstance.mFunc, voidPtrIRType);
  6233. }
  6234. BfIRValue methodNameConst = GetStringObjectValue(methodDef->mName, !mIsComptimeModule);
  6235. BfMethodFlags methodFlags = defaultMethod->GetMethodFlags();
  6236. int customAttrIdx = -1;
  6237. int returnCustomAttrIdx = -1;
  6238. if (methodInfo.mMethodCustomAttributes != NULL)
  6239. {
  6240. customAttrIdx = _HandleCustomAttrs(methodInfo.mMethodCustomAttributes->mCustomAttributes);
  6241. returnCustomAttrIdx = _HandleCustomAttrs(methodInfo.mMethodCustomAttributes->mReturnCustomAttributes);
  6242. }
  6243. enum ParamFlags
  6244. {
  6245. ParamFlag_None = 0,
  6246. ParamFlag_Splat = 1,
  6247. ParamFlag_Implicit = 2,
  6248. ParamFlag_AppendIdx = 4,
  6249. ParamFlag_Params = 8
  6250. };
  6251. SizedArray<BfIRValue, 8> paramVals;
  6252. for (int paramIdx = 0; paramIdx < defaultMethod->GetParamCount(); paramIdx++)
  6253. {
  6254. String paramName = defaultMethod->GetParamName(paramIdx);
  6255. BfType* paramType = defaultMethod->GetParamType(paramIdx);
  6256. ParamFlags paramFlags = ParamFlag_None;
  6257. if (defaultMethod->GetParamIsSplat(paramIdx))
  6258. paramFlags = (ParamFlags)(paramFlags | ParamFlag_Splat);
  6259. if (defaultMethod->GetParamKind(paramIdx) == BfParamKind_AppendIdx)
  6260. paramFlags = (ParamFlags)(paramFlags | ParamFlag_Implicit | ParamFlag_AppendIdx);
  6261. if (defaultMethod->GetParamKind(paramIdx) == BfParamKind_Params)
  6262. paramFlags = (ParamFlags)(paramFlags | ParamFlag_Params);
  6263. BfIRValue paramNameConst = GetStringObjectValue(paramName, !mIsComptimeModule);
  6264. int paramCustomAttrIdx = -1;
  6265. if ((methodInfo.mMethodCustomAttributes != NULL) && (paramIdx < (int)methodInfo.mMethodCustomAttributes->mParamCustomAttributes.mSize))
  6266. paramCustomAttrIdx = _HandleCustomAttrs(methodInfo.mMethodCustomAttributes->mParamCustomAttributes[paramIdx]);
  6267. SizedArray<BfIRValue, 8> paramDataVals =
  6268. {
  6269. emptyValueType,
  6270. paramNameConst,
  6271. GetConstValue(paramType->mTypeId, typeIdType),
  6272. GetConstValue((int32)paramFlags, shortType),
  6273. GetConstValue(-1, intType), // defaultIdx
  6274. GetConstValue(paramCustomAttrIdx, intType) // customAttrIdx
  6275. };
  6276. auto paramData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapType(reflectParamDataType, BfIRPopulateType_Full), paramDataVals);
  6277. paramVals.Add(paramData);
  6278. }
  6279. BfIRValue paramsVal;
  6280. if (paramVals.size() > 0)
  6281. {
  6282. BfIRType paramDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(reflectParamDataType, BfIRPopulateType_Full), (int)paramVals.size());
  6283. BfIRValue paramDataConst = mBfIRBuilder->CreateConstAgg_Value(paramDataArrayType, paramVals);
  6284. BfIRValue paramDataArray = mBfIRBuilder->CreateGlobalVariable(paramDataArrayType, true, BfIRLinkageType_Internal,
  6285. paramDataConst, typeDataName + StrFormat(".params%d", methodIdx));
  6286. paramsVal = mBfIRBuilder->CreateBitCast(paramDataArray, mBfIRBuilder->MapType(reflectParamDataPtrType));
  6287. }
  6288. else
  6289. paramsVal = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(reflectParamDataPtrType));
  6290. int vDataVal = -1;
  6291. if (defaultMethod->mVirtualTableIdx != -1)
  6292. {
  6293. int vDataIdx = -1;
  6294. if (type->IsInterface())
  6295. {
  6296. vDataIdx = defaultMethod->mVirtualTableIdx;
  6297. }
  6298. else
  6299. {
  6300. vDataIdx = 1 + mCompiler->GetDynCastVDataCount() + mCompiler->mMaxInterfaceSlots;
  6301. if ((mCompiler->mOptions.mHasVDataExtender) && (mCompiler->IsHotCompile()))
  6302. {
  6303. auto typeInst = defaultMethod->mMethodInstanceGroup->mOwner;
  6304. int extMethodIdx = (defaultMethod->mVirtualTableIdx - typeInst->GetImplBaseVTableSize()) - typeInst->GetOrigSelfVTableSize();
  6305. if (extMethodIdx >= 0)
  6306. {
  6307. // Extension?
  6308. int vExtOfs = typeInst->GetOrigImplBaseVTableSize();
  6309. vDataVal = ((vDataIdx + vExtOfs + 1) << 20) | (extMethodIdx);
  6310. }
  6311. else
  6312. {
  6313. // Map this new virtual index back to the original index
  6314. vDataIdx += (defaultMethod->mVirtualTableIdx - typeInst->GetImplBaseVTableSize()) + typeInst->GetOrigImplBaseVTableSize();
  6315. }
  6316. }
  6317. else
  6318. {
  6319. vDataIdx += defaultMethod->mVirtualTableIdx;
  6320. }
  6321. }
  6322. if (vDataVal == -1)
  6323. vDataVal = vDataIdx * mSystem->mPtrSize;
  6324. }
  6325. SizedArray<BfIRValue, 8> methodDataVals =
  6326. {
  6327. emptyValueType,
  6328. methodNameConst, // mName
  6329. funcVal, // mFuncPtr
  6330. paramsVal,
  6331. GetConstValue(defaultMethod->mReturnType->mTypeId, typeIdType),
  6332. GetConstValue((int)paramVals.size(), shortType),
  6333. GetConstValue(methodFlags, shortType),
  6334. GetConstValue(methodIdx, intType),
  6335. GetConstValue(vDataVal, intType),
  6336. GetConstValue(customAttrIdx, intType),
  6337. GetConstValue(returnCustomAttrIdx, intType),
  6338. };
  6339. auto methodData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectMethodDataType->ToTypeInstance(), BfIRPopulateType_Full), methodDataVals);
  6340. methodTypes.push_back(methodData);
  6341. }
  6342. BfIRValue methodDataPtr;
  6343. BfIRType methodDataPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(reflectMethodDataType));
  6344. if (methodTypes.size() == 0)
  6345. methodDataPtr = mBfIRBuilder->CreateConstNull(methodDataPtrType);
  6346. else
  6347. {
  6348. BfIRType methodDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(reflectMethodDataType, BfIRPopulateType_Full), (int)methodTypes.size());
  6349. BfIRValue methodDataConst = mBfIRBuilder->CreateConstAgg_Value(methodDataArrayType, methodTypes);
  6350. BfIRValue methodDataArray = mBfIRBuilder->CreateGlobalVariable(methodDataArrayType, true, BfIRLinkageType_Internal,
  6351. methodDataConst, "methods." + typeDataName);
  6352. methodDataPtr = mBfIRBuilder->CreateBitCast(methodDataArray, methodDataPtrType);
  6353. }
  6354. /////
  6355. int interfaceCount = 0;
  6356. BfIRValue interfaceDataPtr;
  6357. BfType* reflectInterfaceDataType = ResolveTypeDef(mCompiler->mReflectInterfaceDataDef);
  6358. BfIRType interfaceDataPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(reflectInterfaceDataType));
  6359. Array<bool> wantsIfaceMethod;
  6360. bool wantsIfaceMethods = false;
  6361. if (typeInstance->mInterfaces.IsEmpty())
  6362. interfaceDataPtr = mBfIRBuilder->CreateConstNull(interfaceDataPtrType);
  6363. else
  6364. {
  6365. SizedArray<BfIRValue, 16> interfaces;
  6366. for (auto& interface : typeInstance->mInterfaces)
  6367. {
  6368. SizedArray<BfIRValue, 8> interfaceDataVals =
  6369. {
  6370. emptyValueType,
  6371. GetConstValue(interface.mInterfaceType->mTypeId, typeIdType),
  6372. GetConstValue(interface.mStartInterfaceTableIdx, intType),
  6373. GetConstValue(interface.mStartVirtualIdx, intType),
  6374. };
  6375. auto interfaceData = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapTypeInst(reflectInterfaceDataType->ToTypeInstance(), BfIRPopulateType_Full), interfaceDataVals);
  6376. interfaces.push_back(interfaceData);
  6377. if (!mIsComptimeModule)
  6378. {
  6379. for (int methodIdx = 0; methodIdx < (int)interface.mInterfaceType->mMethodInstanceGroups.size(); methodIdx++)
  6380. {
  6381. auto ifaceMethodGroup = &interface.mInterfaceType->mMethodInstanceGroups[methodIdx];
  6382. if (ifaceMethodGroup->mExplicitlyReflected)
  6383. {
  6384. wantsIfaceMethods = true;
  6385. int tableIdx = interface.mStartInterfaceTableIdx + methodIdx;
  6386. while (tableIdx >= wantsIfaceMethod.size())
  6387. wantsIfaceMethod.Add(false);
  6388. wantsIfaceMethod[tableIdx] = true;
  6389. }
  6390. }
  6391. }
  6392. }
  6393. BfIRType interfaceDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(reflectInterfaceDataType, BfIRPopulateType_Full), (int)interfaces.size());
  6394. BfIRValue interfaceDataConst = mBfIRBuilder->CreateConstAgg_Value(interfaceDataArrayType, interfaces);
  6395. BfIRValue interfaceDataArray = mBfIRBuilder->CreateGlobalVariable(interfaceDataArrayType, true, BfIRLinkageType_Internal,
  6396. interfaceDataConst, "interfaces." + typeDataName);
  6397. interfaceDataPtr = mBfIRBuilder->CreateBitCast(interfaceDataArray, interfaceDataPtrType);
  6398. interfaceCount = (int)interfaces.size();
  6399. }
  6400. BfIRValue interfaceMethodTable;
  6401. int ifaceMethodTableSize = 0;
  6402. if ((wantsIfaceMethods) && (!typeInstance->IsInterface()) && (typeInstance->mIsReified) && (!typeInstance->IsUnspecializedType())
  6403. && (!typeInstance->mInterfaceMethodTable.IsEmpty()))
  6404. {
  6405. SizedArray<BfIRValue, 16> methods;
  6406. for (int tableIdx = 0; tableIdx < (int)typeInstance->mInterfaceMethodTable.size(); tableIdx++)
  6407. {
  6408. BfIRValue funcVal = voidPtrNull;
  6409. if ((tableIdx < (int)wantsIfaceMethod.size()) && (wantsIfaceMethod[tableIdx]))
  6410. {
  6411. auto methodEntry = typeInstance->mInterfaceMethodTable[tableIdx];
  6412. if (!methodEntry.mMethodRef.IsNull())
  6413. {
  6414. BfMethodInstance* methodInstance = methodEntry.mMethodRef;
  6415. if ((methodInstance->mIsReified) && (methodInstance->mMethodInstanceGroup->IsImplemented()) && (!methodInstance->mIsUnspecialized) &&
  6416. (!methodInstance->mMethodDef->mIsAbstract))
  6417. {
  6418. auto moduleMethodInstance = ReferenceExternalMethodInstance(methodInstance);
  6419. if (moduleMethodInstance.mFunc)
  6420. funcVal = mBfIRBuilder->CreateBitCast(moduleMethodInstance.mFunc, voidPtrIRType);
  6421. }
  6422. }
  6423. }
  6424. methods.Add(funcVal);
  6425. }
  6426. while ((!methods.IsEmpty()) && (methods.back() == voidPtrNull))
  6427. methods.pop_back();
  6428. if (!methods.IsEmpty())
  6429. {
  6430. BfIRType methodDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(voidPtrType, BfIRPopulateType_Full), (int)methods.size());
  6431. BfIRValue methodDataConst = mBfIRBuilder->CreateConstAgg_Value(methodDataArrayType, methods);
  6432. BfIRValue methodDataArray = mBfIRBuilder->CreateGlobalVariable(methodDataArrayType, true, BfIRLinkageType_Internal,
  6433. methodDataConst, "imethods." + typeDataName);
  6434. interfaceMethodTable = mBfIRBuilder->CreateBitCast(methodDataArray, voidPtrPtrIRType);
  6435. ifaceMethodTableSize = (int)methods.size();
  6436. }
  6437. }
  6438. if (!interfaceMethodTable)
  6439. interfaceMethodTable = mBfIRBuilder->CreateConstNull(voidPtrPtrIRType);
  6440. /////
  6441. int underlyingType = 0;
  6442. if ((typeInstance->IsTypedPrimitive()) || (typeInstance->IsBoxed()))
  6443. {
  6444. underlyingType = typeInstance->GetUnderlyingType()->mTypeId;
  6445. }
  6446. int outerTypeId = 0;
  6447. auto outerType = mContext->mUnreifiedModule->GetOuterType(typeInstance);
  6448. if (outerType != NULL)
  6449. {
  6450. outerTypeId = outerType->mTypeId;
  6451. }
  6452. //
  6453. BfIRValue customAttrDataPtr;
  6454. if (customAttrs.size() > 0)
  6455. {
  6456. BfIRType customAttrsArrayType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)customAttrs.size());
  6457. BfIRValue customAttrsConst = mBfIRBuilder->CreateConstAgg_Value(customAttrsArrayType, customAttrs);
  6458. BfIRValue customAttrsArray = mBfIRBuilder->CreateGlobalVariable(customAttrsArrayType, true, BfIRLinkageType_Internal,
  6459. customAttrsConst, "customAttrs." + typeDataName);
  6460. customAttrDataPtr = mBfIRBuilder->CreateBitCast(customAttrsArray, voidPtrPtrIRType);
  6461. }
  6462. else
  6463. {
  6464. customAttrDataPtr = mBfIRBuilder->CreateConstNull(voidPtrPtrIRType);
  6465. }
  6466. SizedArray<BfIRValue, 32> typeDataVals =
  6467. {
  6468. typeData,
  6469. castedClassVData, // mTypeClassVData
  6470. typeNameConst, // mName
  6471. namespaceConst, // mNamespace
  6472. GetConstValue(typeInstance->mInstSize, intType), // mInstSize
  6473. GetConstValue(typeInstance->mInstAlign, intType), // mInstAlign
  6474. GetConstValue(typeCustomAttrIdx, intType), // mCustomAttributes
  6475. GetConstValue(baseTypeId, typeIdType), // mBaseType
  6476. GetConstValue(underlyingType, typeIdType), // mUnderlyingType
  6477. GetConstValue(outerTypeId, typeIdType), // mOuterType
  6478. GetConstValue(typeInstance->mInheritanceId, intType), // mInheritanceId
  6479. GetConstValue(typeInstance->mInheritanceCount, intType), // mInheritanceCount
  6480. GetConstValue(typeInstance->mSlotNum, byteType), // mInterfaceSlot
  6481. GetConstValue(interfaceCount, byteType), // mInterfaceCount
  6482. GetConstValue(ifaceMethodTableSize, shortType), // mInterfaceMethodCount
  6483. GetConstValue((int)methodTypes.size(), shortType), // mMethodDataCount
  6484. GetConstValue(0, shortType), // mPropertyDataCount
  6485. GetConstValue((int)fieldTypes.size(), shortType), // mFieldDataCount
  6486. interfaceDataPtr, // mInterfaceDataPtr
  6487. interfaceMethodTable, // mInterfaceMethodTable
  6488. methodDataPtr, // mMethodDataPtr
  6489. voidPtrNull, // mPropertyDataPtr
  6490. fieldDataPtr, // mFieldDataPtr
  6491. customAttrDataPtr, // mCustomAttrDataPtr
  6492. };
  6493. BfIRType typeInstanceDataType = mBfIRBuilder->MapTypeInst(typeInstanceType->ToTypeInstance(), BfIRPopulateType_Full);
  6494. FixConstValueParams(typeInstanceType->ToTypeInstance(), typeDataVals);
  6495. auto typeInstanceData = mBfIRBuilder->CreateConstAgg_Value(typeInstanceDataType, typeDataVals);
  6496. if (!needsTypeData)
  6497. {
  6498. // No need for anything beyond typeInstanceData
  6499. }
  6500. else if ((typeInstance->IsGenericTypeInstance()) && (typeInstance->IsUnspecializedType()))
  6501. {
  6502. auto genericTypeInstance = typeInstance->ToGenericTypeInstance();
  6503. SizedArray<BfIRValue, 4> unspecializedData =
  6504. {
  6505. typeInstanceData,
  6506. GetConstValue((int)genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments.size(), byteType), // mGenericParamCount
  6507. };
  6508. auto reflectUnspecializedGenericType = ResolveTypeDef(mCompiler->mReflectUnspecializedGenericType);
  6509. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectUnspecializedGenericType->ToTypeInstance(), BfIRPopulateType_Full);
  6510. typeInstanceData = mBfIRBuilder->CreateConstAgg_Value(typeInstanceDataType, unspecializedData);
  6511. }
  6512. else if (typeInstance->IsGenericTypeInstance())
  6513. {
  6514. auto genericTypeInstance = typeInstance->ToGenericTypeInstance();
  6515. auto reflectSpecializedGenericType = ResolveTypeDef(mCompiler->mReflectSpecializedGenericType);
  6516. auto unspecializedType = ResolveTypeDef(typeInstance->mTypeDef->GetDefinition());
  6517. SizedArray<BfIRValue, 4> resolvedTypes;
  6518. for (auto typeGenericArg : genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments)
  6519. resolvedTypes.push_back(GetConstValue(typeGenericArg->mTypeId, typeIdType));
  6520. auto typeIRType = mBfIRBuilder->MapType(typeIdType);
  6521. auto typePtrIRType = mBfIRBuilder->GetPointerTo(typeIRType);
  6522. auto genericArrayType = mBfIRBuilder->GetSizedArrayType(typeIRType, (int)resolvedTypes.size());
  6523. BfIRValue resolvedTypesConst = mBfIRBuilder->CreateConstAgg_Value(genericArrayType, resolvedTypes);
  6524. BfIRValue resolvedTypesArray = mBfIRBuilder->CreateGlobalVariable(genericArrayType, true, BfIRLinkageType_Internal,
  6525. resolvedTypesConst, "resolvedTypes." + typeDataName);
  6526. BfIRValue resovledTypesPtr = mBfIRBuilder->CreateBitCast(resolvedTypesArray, typePtrIRType);
  6527. SizedArray<BfIRValue, 3> specGenericData =
  6528. {
  6529. typeInstanceData,
  6530. GetConstValue(unspecializedType->mTypeId, typeIdType), // mUnspecialziedType
  6531. resovledTypesPtr, // mFieldDataPtr
  6532. };
  6533. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectSpecializedGenericType->ToTypeInstance(), BfIRPopulateType_Full);
  6534. typeInstanceData = mBfIRBuilder->CreateConstAgg_Value(typeInstanceDataType, specGenericData);
  6535. if (typeInstance->IsArray())
  6536. {
  6537. auto arrayType = (BfArrayType*)typeInstance;
  6538. BfType* elementType = genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments[0];
  6539. BfFieldInstance* elementFieldInstance = &genericTypeInstance->mFieldInstances[0];
  6540. SizedArray<BfIRValue, 4> arrayData =
  6541. {
  6542. typeInstanceData,
  6543. GetConstValue(elementType->mSize, intType), // mElementSize
  6544. GetConstValue(1, byteType), // mRank
  6545. GetConstValue(elementFieldInstance->mDataOffset, byteType), // mElementsDataOffset
  6546. };
  6547. auto reflectArrayType = ResolveTypeDef(mCompiler->mReflectArrayType);
  6548. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectArrayType->ToTypeInstance(), BfIRPopulateType_Full);
  6549. typeInstanceData = mBfIRBuilder->CreateConstAgg_Value(typeInstanceDataType, arrayData);
  6550. }
  6551. }
  6552. BfIRValue typeDataVar;
  6553. if (needsTypeData)
  6554. {
  6555. typeDataVar = mBfIRBuilder->CreateGlobalVariable(typeInstanceDataType, true,
  6556. BfIRLinkageType_External, typeInstanceData, typeDataName);
  6557. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  6558. if (mBfIRBuilder->DbgHasInfo())
  6559. {
  6560. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, typeDataName, typeDataName, BfIRMDNode(), 0, mBfIRBuilder->DbgGetTypeInst(typeInstanceType->ToTypeInstance()), false, typeDataVar);
  6561. }
  6562. }
  6563. else
  6564. {
  6565. typeDataVar = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(mContext->mBfTypeType));
  6566. }
  6567. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  6568. mTypeDataRefs[typeInstance] = typeDataVar;
  6569. if ((!mIsComptimeModule) && (classVDataVar))
  6570. {
  6571. BF_ASSERT(!classVDataName.IsEmpty());
  6572. vData[0] = mBfIRBuilder->CreateBitCast(typeDataVar, voidPtrIRType);
  6573. auto classVDataConstDataType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)vData.size());
  6574. auto classVDataConstData = mBfIRBuilder->CreateConstAgg_Value(classVDataConstDataType, vData);
  6575. mBfIRBuilder->GlobalVar_SetInitializer(classVDataVar, classVDataConstData);
  6576. if (mCompiler->mOptions.mObjectHasDebugFlags)
  6577. mBfIRBuilder->GlobalVar_SetAlignment(classVDataVar, 256);
  6578. else
  6579. mBfIRBuilder->GlobalVar_SetAlignment(classVDataVar, mContext->mBfClassVDataPtrType->mAlign);
  6580. if (mBfIRBuilder->DbgHasInfo())
  6581. {
  6582. BfType* voidType = GetPrimitiveType(BfTypeCode_None);
  6583. BfType* voidPtrType = CreatePointerType(voidType);
  6584. BfType* classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  6585. BfIRMDNode arrayType = mBfIRBuilder->DbgCreateArrayType(vData.size() * mSystem->mPtrSize * 8, mSystem->mPtrSize * 8, mBfIRBuilder->DbgGetType(voidPtrType), vData.size());
  6586. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, classVDataName, classVDataName, BfIRMDNode(), 0, arrayType, false, classVDataVar);
  6587. }
  6588. }
  6589. return typeDataVar;
  6590. }
  6591. BfIRValue BfModule::FixClassVData(BfIRValue value)
  6592. {
  6593. if ((!mCompiler->mOptions.mObjectHasDebugFlags) || (mIsComptimeModule))
  6594. return value;
  6595. auto intptrValue = mBfIRBuilder->CreatePtrToInt(value, BfTypeCode_IntPtr);
  6596. auto maskedValue = mBfIRBuilder->CreateAnd(intptrValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)~0xFFULL));
  6597. return mBfIRBuilder->CreateIntToPtr(maskedValue, mBfIRBuilder->GetType(value));
  6598. }
  6599. void BfModule::CheckStaticAccess(BfTypeInstance* typeInstance)
  6600. {
  6601. // Note: this is not just for perf, it fixes a field var-type resolution issue
  6602. if (mBfIRBuilder->mIgnoreWrites)
  6603. return;
  6604. if (mIsComptimeModule)
  6605. return;
  6606. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  6607. //TODO: Create a hashset of these, we don't need to repeatedly call static ctors for a given type
  6608. // When we access classes with static constructors FROM a static constructor,
  6609. // we call that other class's static constructor first. Recursion cannot occur, since
  6610. // we simply ignore subsequent attempts to re-enter the constructor
  6611. if (!typeInstance->mHasStaticInitMethod)
  6612. return;
  6613. if ((mCurMethodInstance == NULL) || ((mCurMethodInstance->mMethodDef->mMethodType != BfMethodType_Ctor) || (!mCurMethodInstance->mMethodDef->mIsStatic)))
  6614. return;
  6615. if (mCurMethodInstance->mMethodInstanceGroup->mOwner == typeInstance)
  6616. return;
  6617. auto checkTypeDef = typeInstance->mTypeDef;
  6618. checkTypeDef->PopulateMemberSets();
  6619. BfMethodDef* nextMethodDef = NULL;
  6620. BfMemberSetEntry* entry;
  6621. if (checkTypeDef->mMethodSet.TryGetWith(String("__BfStaticCtor"), &entry))
  6622. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  6623. while (nextMethodDef != NULL)
  6624. {
  6625. auto checkMethod = nextMethodDef;
  6626. nextMethodDef = nextMethodDef->mNextWithSameName;
  6627. auto methodModule = GetMethodInstance(typeInstance, checkMethod, BfTypeVector());
  6628. if (methodModule)
  6629. {
  6630. auto methodInstance = methodModule.mMethodInstance;
  6631. if ((methodInstance != NULL) &&
  6632. (methodInstance->mMethodDef->mIsStatic) &&
  6633. (methodInstance->mMethodDef->mMethodType == BfMethodType_Ctor) &&
  6634. ((methodInstance->mChainType == BfMethodChainType_ChainHead) || (methodInstance->mChainType == BfMethodChainType_None)))
  6635. {
  6636. mBfIRBuilder->CreateCall(methodModule.mFunc, SizedArray<BfIRValue, 0>());
  6637. break;
  6638. }
  6639. }
  6640. }
  6641. }
  6642. BfIRFunction BfModule::GetIntrinsic(BfMethodInstance* methodInstance, bool reportFailure)
  6643. {
  6644. auto methodOwner = methodInstance->GetOwner();
  6645. auto methodDef = methodInstance->mMethodDef;
  6646. auto methodDeclaration = methodDef->GetMethodDeclaration();
  6647. if (!methodDef->mIsExtern)
  6648. return BfIRFunction();
  6649. if (methodInstance->GetCustomAttributes() == NULL)
  6650. return BfIRFunction();
  6651. for (auto& customAttribute : methodInstance->GetCustomAttributes()->mAttributes)
  6652. {
  6653. String typeName = TypeToString(customAttribute.mType);
  6654. if ((typeName == "System.IntrinsicAttribute") && (customAttribute.mCtorArgs.size() > 0))
  6655. {
  6656. methodInstance->mIsIntrinsic = true;
  6657. auto constant = methodOwner->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  6658. String error;
  6659. if ((constant != NULL) && (constant->mTypeCode == BfTypeCode_StringId))
  6660. {
  6661. int stringId = constant->mInt32;
  6662. auto entry = mContext->mStringObjectIdMap[stringId];
  6663. String intrinName = entry.mString;
  6664. // if (intrinName.StartsWith(":"))
  6665. // {
  6666. // SizedArray<BfIRType, 2> paramTypes;
  6667. // for (auto& param : methodInstance->mParams)
  6668. // paramTypes.push_back(mBfIRBuilder->MapType(param.mResolvedType));
  6669. // return mBfIRBuilder->GetIntrinsic(intrinName.Substring(1), mBfIRBuilder->MapType(methodInstance->mReturnType), paramTypes);
  6670. // }
  6671. // else
  6672. {
  6673. int intrinId = BfIRCodeGen::GetIntrinsicId(intrinName);
  6674. if (intrinId != -1)
  6675. {
  6676. if (intrinId == BfIRIntrinsic_Malloc)
  6677. {
  6678. return GetBuiltInFunc(BfBuiltInFuncType_Malloc);
  6679. }
  6680. else if (intrinId == BfIRIntrinsic_Free)
  6681. {
  6682. return GetBuiltInFunc(BfBuiltInFuncType_Free);
  6683. }
  6684. SizedArray<BfIRType, 2> paramTypes;
  6685. for (auto& param : methodInstance->mParams)
  6686. paramTypes.push_back(mBfIRBuilder->MapType(param.mResolvedType));
  6687. return mBfIRBuilder->GetIntrinsic(intrinName, intrinId, mBfIRBuilder->MapType(methodInstance->mReturnType), paramTypes);
  6688. }
  6689. else if (reportFailure)
  6690. error = StrFormat("Unable to find intrinsic '%s'", entry.mString.c_str());
  6691. }
  6692. }
  6693. else if (reportFailure)
  6694. error = "Intrinsic name must be a constant string";
  6695. if (reportFailure)
  6696. {
  6697. Fail(error, customAttribute.mRef);
  6698. }
  6699. }
  6700. }
  6701. return BfIRFunction();
  6702. }
  6703. BfIRFunction BfModule::GetBuiltInFunc(BfBuiltInFuncType funcTypeId)
  6704. {
  6705. if (mBfIRBuilder->mIgnoreWrites)
  6706. return mBfIRBuilder->GetFakeFunction();
  6707. if (!mBuiltInFuncs[(int)funcTypeId])
  6708. {
  6709. SizedArray<BfIRType, 4> paramTypes;
  6710. auto nullPtrType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr));
  6711. auto intType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_IntPtr));
  6712. auto int32Type = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int32));
  6713. auto intPtrType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_IntPtr));
  6714. auto byteType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int8));
  6715. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  6716. auto objType = mBfIRBuilder->MapType(mContext->mBfObjectType);
  6717. BfIRFunctionType funcType;
  6718. BfIRFunction func;
  6719. switch (funcTypeId)
  6720. {
  6721. case BfBuiltInFuncType_PrintF:
  6722. paramTypes.Add(nullPtrType);
  6723. funcType = mBfIRBuilder->CreateFunctionType(int32Type, paramTypes, true);
  6724. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, "PrintF");
  6725. break;
  6726. case BfBuiltInFuncType_Malloc:
  6727. {
  6728. if ((mCompiler->mOptions.mDebugAlloc) && (!mIsComptimeModule))
  6729. {
  6730. func = GetInternalMethod("Dbg_RawAlloc", 1).mFunc;
  6731. }
  6732. else
  6733. {
  6734. String funcName = mCompiler->mOptions.mMallocLinkName;
  6735. if ((funcName.IsEmpty()) || (mIsComptimeModule))
  6736. funcName = "malloc";
  6737. func = mBfIRBuilder->GetFunction(funcName);
  6738. if (!func)
  6739. {
  6740. paramTypes.clear();
  6741. paramTypes.push_back(intType);
  6742. funcType = mBfIRBuilder->CreateFunctionType(nullPtrType, paramTypes);
  6743. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, funcName);
  6744. mBfIRBuilder->Func_SetParamName(func, 1, "size");
  6745. }
  6746. }
  6747. }
  6748. break;
  6749. case BfBuiltInFuncType_Free:
  6750. {
  6751. if ((mCompiler->mOptions.mDebugAlloc) && (!mIsComptimeModule))
  6752. {
  6753. func = GetInternalMethod("Dbg_RawFree").mFunc;
  6754. }
  6755. else
  6756. {
  6757. String funcName = mCompiler->mOptions.mFreeLinkName;
  6758. if ((funcName.IsEmpty()) || (mIsComptimeModule))
  6759. funcName = "free";
  6760. func = mBfIRBuilder->GetFunction(funcName);
  6761. if (!func)
  6762. {
  6763. paramTypes.clear();
  6764. paramTypes.push_back(nullPtrType);
  6765. funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  6766. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, funcName);
  6767. mBfIRBuilder->Func_SetParamName(func, 1, "ptr");
  6768. }
  6769. }
  6770. }
  6771. break;
  6772. case BfBuiltInFuncType_LoadSharedLibraries:
  6773. paramTypes.clear();
  6774. funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  6775. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, "BfLoadSharedLibraries");
  6776. break;
  6777. default: break;
  6778. }
  6779. mBuiltInFuncs[(int)funcTypeId] = func;
  6780. return func;
  6781. }
  6782. return mBuiltInFuncs[(int)funcTypeId];
  6783. }
  6784. void BfModule::ResolveGenericParamConstraints(BfGenericParamInstance* genericParamInstance, bool isUnspecialized, Array<BfTypeReference*>* deferredResolveTypes)
  6785. {
  6786. BfGenericParamDef* genericParamDef = genericParamInstance->GetGenericParamDef();
  6787. BfExternalConstraintDef* externConstraintDef = genericParamInstance->GetExternConstraintDef();
  6788. BfConstraintDef* constraintDef = genericParamInstance->GetConstraintDef();
  6789. BfType* startingTypeConstraint = genericParamInstance->mTypeConstraint;
  6790. BfAutoComplete* bfAutocomplete = NULL;
  6791. if ((mCompiler->mResolvePassData != NULL) && (isUnspecialized))
  6792. bfAutocomplete = mCompiler->mResolvePassData->mAutoComplete;
  6793. if ((bfAutocomplete != NULL) && (genericParamDef != NULL))
  6794. {
  6795. for (int nameIdx = 0; nameIdx < (int)genericParamDef->mNameNodes.size(); nameIdx++)
  6796. {
  6797. auto nameNode = genericParamDef->mNameNodes[nameIdx];
  6798. if (bfAutocomplete->IsAutocompleteNode(nameNode))
  6799. {
  6800. String filter = nameNode->ToString();
  6801. bfAutocomplete->mInsertStartIdx = nameNode->GetSrcStart();
  6802. bfAutocomplete->mInsertEndIdx = nameNode->GetSrcEnd();
  6803. if (nameIdx != 0)
  6804. {
  6805. bfAutocomplete->AddEntry(AutoCompleteEntry("generic", nameNode->ToString().c_str()), filter);
  6806. }
  6807. }
  6808. }
  6809. }
  6810. for (auto constraint : constraintDef->mConstraints)
  6811. {
  6812. if (auto opConstraint = BfNodeDynCast<BfGenericOperatorConstraint>(constraint))
  6813. {
  6814. BfGenericOperatorConstraintInstance opConstraintInstance;
  6815. if (opConstraint->mLeftType != NULL)
  6816. {
  6817. if (bfAutocomplete != NULL)
  6818. bfAutocomplete->CheckTypeRef(opConstraint->mLeftType, false);
  6819. opConstraintInstance.mLeftType = ResolveTypeRef(opConstraint->mLeftType, BfPopulateType_Interfaces_All);
  6820. if (opConstraintInstance.mLeftType == NULL)
  6821. continue;
  6822. }
  6823. if (opConstraint->mRightType == NULL)
  6824. {
  6825. // We had a failure in parsing
  6826. continue;
  6827. }
  6828. if (opConstraint->mRightType != NULL)
  6829. {
  6830. if (bfAutocomplete != NULL)
  6831. bfAutocomplete->CheckTypeRef(opConstraint->mRightType, false);
  6832. opConstraintInstance.mRightType = ResolveTypeRef(opConstraint->mRightType, BfPopulateType_Interfaces_All);
  6833. if (opConstraintInstance.mRightType == NULL)
  6834. continue;
  6835. }
  6836. if (opConstraint->mOpToken == NULL)
  6837. {
  6838. FailAfter("Missing operator", (opConstraint->mLeftType != NULL) ? (BfAstNode*)opConstraint->mLeftType : (BfAstNode*)opConstraint->mOperatorToken);
  6839. continue;
  6840. }
  6841. if (opConstraint->mLeftType != NULL)
  6842. {
  6843. if (opConstraint->mRightType == NULL)
  6844. {
  6845. // Parse should have failed
  6846. continue;
  6847. }
  6848. opConstraintInstance.mBinaryOp = BfTokenToBinaryOp(opConstraint->mOpToken->mToken);
  6849. if (opConstraintInstance.mBinaryOp == BfBinaryOp_None)
  6850. {
  6851. Fail("Invalid binary operator", opConstraint->mOpToken);
  6852. continue;
  6853. }
  6854. }
  6855. else if ((opConstraint->mOpToken->mToken == BfToken_Implicit) || (opConstraint->mOpToken->mToken == BfToken_Explicit))
  6856. {
  6857. opConstraintInstance.mCastToken = opConstraint->mOpToken->mToken;
  6858. }
  6859. else
  6860. {
  6861. opConstraintInstance.mUnaryOp = BfTokenToUnaryOp(opConstraint->mOpToken->mToken);
  6862. if (opConstraintInstance.mUnaryOp == BfUnaryOp_None)
  6863. {
  6864. Fail("Invalid unary operator", opConstraint->mOpToken);
  6865. continue;
  6866. }
  6867. }
  6868. genericParamInstance->mOperatorConstraints.Add(opConstraintInstance);
  6869. continue;
  6870. }
  6871. auto constraintTypeRef = BfNodeDynCast<BfTypeReference>(constraint);
  6872. if (bfAutocomplete != NULL)
  6873. bfAutocomplete->CheckTypeRef(constraintTypeRef, true);
  6874. //TODO: Constraints may refer to other generic params (of either type or method)
  6875. // TO allow resolution, perhaps move this generic param initialization into GetMethodInstance (passing a genericPass bool)
  6876. BfResolveTypeRefFlags resolveFlags = BfResolveTypeRefFlag_AllowGenericMethodParamConstValue;
  6877. if (isUnspecialized)
  6878. resolveFlags = (BfResolveTypeRefFlags)(resolveFlags | BfResolveTypeRefFlag_DisallowComptime);
  6879. // We we have a deferredResolveTypes then we defer the generic validation, because we may have a case like
  6880. // `where T : Dictionay<TElem, int> and TElem : IHashable` and we don't want to throw the error on `T` before we build `TElem`
  6881. auto constraintType = ResolveTypeRef(constraintTypeRef, (deferredResolveTypes != NULL) ? BfPopulateType_Identity : BfPopulateType_Declaration, resolveFlags);
  6882. if (constraintType != NULL)
  6883. {
  6884. if (deferredResolveTypes != NULL)
  6885. {
  6886. PopulateType(constraintType, BfPopulateType_Declaration);
  6887. if (constraintType->IsUnspecializedTypeVariation())
  6888. deferredResolveTypes->Add(constraintTypeRef);
  6889. }
  6890. if ((constraintDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  6891. {
  6892. bool isValidTypeCode = false;
  6893. BfTypeCode typeCode = BfTypeCode_None;
  6894. if (constraintType->IsTypedPrimitive())
  6895. {
  6896. auto underlyingType = constraintType->GetUnderlyingType();
  6897. if (underlyingType->IsPrimitiveType())
  6898. typeCode = ((BfPrimitiveType*)underlyingType)->mTypeDef->mTypeCode;
  6899. }
  6900. if (constraintType->IsPrimitiveType())
  6901. typeCode = ((BfPrimitiveType*)constraintType)->mTypeDef->mTypeCode;
  6902. if (constraintType->IsInstanceOf(mCompiler->mStringTypeDef))
  6903. isValidTypeCode = true;
  6904. switch (typeCode)
  6905. {
  6906. case BfTypeCode_StringId:
  6907. case BfTypeCode_Boolean:
  6908. case BfTypeCode_Int8:
  6909. case BfTypeCode_UInt8:
  6910. case BfTypeCode_Int16:
  6911. case BfTypeCode_UInt16:
  6912. case BfTypeCode_Int32:
  6913. case BfTypeCode_UInt32:
  6914. case BfTypeCode_Int64:
  6915. case BfTypeCode_UInt64:
  6916. case BfTypeCode_IntPtr:
  6917. case BfTypeCode_UIntPtr:
  6918. case BfTypeCode_IntUnknown:
  6919. case BfTypeCode_UIntUnknown:
  6920. case BfTypeCode_Float:
  6921. case BfTypeCode_Double:
  6922. case BfTypeCode_Char8:
  6923. case BfTypeCode_Char16:
  6924. case BfTypeCode_Char32:
  6925. isValidTypeCode = true;
  6926. break;
  6927. default: break;
  6928. }
  6929. if (isValidTypeCode)
  6930. {
  6931. genericParamInstance->mTypeConstraint = constraintType;
  6932. }
  6933. else
  6934. {
  6935. Fail("Const constraint must be a primitive type", constraintTypeRef);
  6936. }
  6937. }
  6938. else
  6939. {
  6940. bool checkEquality = false;
  6941. if (constraintType->IsVar())
  6942. {
  6943. // From a `comptype` generic undef resolution. Ignore.
  6944. genericParamInstance->mGenericParamFlags = (BfGenericParamFlags)(genericParamInstance->mGenericParamFlags | BfGenericParamFlag_ComptypeExpr);
  6945. genericParamInstance->mComptypeConstraint.Add(constraintTypeRef);
  6946. continue;
  6947. }
  6948. else if (constraintType->IsPrimitiveType())
  6949. {
  6950. if (isUnspecialized)
  6951. {
  6952. Fail("Primitive constraints are not allowed unless preceded with 'const'", constraintTypeRef);
  6953. continue;
  6954. }
  6955. checkEquality = true;
  6956. }
  6957. if (constraintType->IsArray())
  6958. {
  6959. if (isUnspecialized)
  6960. {
  6961. 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);
  6962. continue;
  6963. }
  6964. checkEquality = true;
  6965. }
  6966. if (constraintType->IsGenericParam())
  6967. {
  6968. checkEquality = true;
  6969. }
  6970. else if ((!constraintType->IsTypeInstance()) && (!constraintType->IsSizedArray()))
  6971. {
  6972. if (isUnspecialized)
  6973. {
  6974. Fail(StrFormat("Type '%s' is not allowed as a generic constraint", TypeToString(constraintType).c_str()), constraintTypeRef);
  6975. continue;
  6976. }
  6977. checkEquality = true;
  6978. }
  6979. if (checkEquality)
  6980. {
  6981. genericParamInstance->mTypeConstraint = constraintType;
  6982. }
  6983. else if (constraintType->IsInterface())
  6984. {
  6985. genericParamInstance->mInterfaceConstraints.push_back(constraintType->ToTypeInstance());
  6986. }
  6987. else
  6988. {
  6989. auto constraintTypeInst = constraintType->ToTypeInstance();
  6990. if (genericParamInstance->mTypeConstraint != NULL)
  6991. {
  6992. if ((constraintTypeInst != NULL) && (TypeIsSubTypeOf(constraintTypeInst, genericParamInstance->mTypeConstraint->ToTypeInstance(), false)))
  6993. {
  6994. // Allow more specific type
  6995. genericParamInstance->mTypeConstraint = constraintTypeInst;
  6996. }
  6997. else if ((constraintTypeInst != NULL) && (TypeIsSubTypeOf(genericParamInstance->mTypeConstraint->ToTypeInstance(), constraintTypeInst, false)))
  6998. {
  6999. // Silently ignore less-specific type
  7000. if ((startingTypeConstraint != NULL) && (startingTypeConstraint->IsDelegate()))
  7001. {
  7002. // 'System.Delegate' means that we are expecting an actual delegate instance. Simulate this by wanting a class.
  7003. genericParamInstance->mGenericParamFlags = (BfGenericParamFlags)(genericParamInstance->mGenericParamFlags | BfGenericParamFlag_Class);
  7004. }
  7005. }
  7006. else
  7007. {
  7008. Fail("Only one concrete type constraint may be specified", constraintTypeRef);
  7009. return;
  7010. }
  7011. }
  7012. else
  7013. genericParamInstance->mTypeConstraint = constraintType;
  7014. }
  7015. }
  7016. }
  7017. }
  7018. if (((constraintDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0) &&
  7019. (genericParamInstance->mTypeConstraint == NULL))
  7020. genericParamInstance->mTypeConstraint = GetPrimitiveType(BfTypeCode_IntPtr);
  7021. }
  7022. String BfModule::GenericParamSourceToString(const BfGenericParamSource & genericParamSource)
  7023. {
  7024. if (genericParamSource.mMethodInstance != NULL)
  7025. {
  7026. //auto methodInst = GetUnspecializedMethodInstance(genericParamSource.mMethodInstance, false);
  7027. //SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, methodInst);
  7028. return MethodToString(genericParamSource.mMethodInstance);
  7029. }
  7030. else
  7031. {
  7032. auto typeInst = GetUnspecializedTypeInstance(genericParamSource.mTypeInstance);
  7033. SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, NULL);
  7034. SetAndRestoreValue<BfTypeInstance*> prevTypeInst(mCurTypeInstance, typeInst);
  7035. return TypeToString(typeInst);
  7036. }
  7037. }
  7038. bool BfModule::CheckGenericConstraints(const BfGenericParamSource& genericParamSource, BfType* checkArgType, BfAstNode* checkArgTypeRef, BfGenericParamInstance* genericParamInst, BfTypeVector* methodGenericArgs, BfError** errorOut)
  7039. {
  7040. Array<String> methodParamNameOverrides;
  7041. auto _TypeToString = [&](BfType* type)
  7042. {
  7043. if (genericParamSource.mMethodInstance != NULL)
  7044. {
  7045. if (methodParamNameOverrides.IsEmpty())
  7046. {
  7047. for (auto genericParam : genericParamSource.mMethodInstance->mMethodDef->mGenericParams)
  7048. methodParamNameOverrides.Add(genericParam->mName);
  7049. }
  7050. return TypeToString(type, &methodParamNameOverrides);
  7051. }
  7052. return TypeToString(type);
  7053. };
  7054. bool ignoreErrors = (errorOut == NULL) ||
  7055. ((genericParamSource.mMethodInstance == NULL) && (genericParamSource.mTypeInstance == NULL));
  7056. BfType* origCheckArgType = checkArgType;
  7057. if (origCheckArgType->IsRef())
  7058. origCheckArgType = origCheckArgType->GetUnderlyingType();
  7059. bool argIsReferenceType = false;
  7060. int checkGenericParamFlags = 0;
  7061. if (checkArgType->IsGenericParam())
  7062. {
  7063. BfGenericParamInstance* checkGenericParamInst = GetGenericParamInstance((BfGenericParamType*)checkArgType);
  7064. checkGenericParamFlags = checkGenericParamInst->mGenericParamFlags;
  7065. if (checkGenericParamInst->mTypeConstraint != NULL)
  7066. checkArgType = checkGenericParamInst->mTypeConstraint;
  7067. // if ((checkGenericParamFlags & (BfGenericParamFlag_Struct | BfGenericParamFlag_StructPtr)) != 0)
  7068. // {
  7069. // argMayBeReferenceType = false;
  7070. // }
  7071. // else
  7072. // {
  7073. // argMayBeReferenceType = true;
  7074. // }
  7075. }
  7076. if (checkArgType->IsObjectOrInterface())
  7077. argIsReferenceType = true;
  7078. BfTypeInstance* typeConstraintInst = NULL;
  7079. if (genericParamInst->mTypeConstraint != NULL)
  7080. typeConstraintInst = genericParamInst->mTypeConstraint->ToTypeInstance();
  7081. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Struct) &&
  7082. ((checkGenericParamFlags & (BfGenericParamFlag_Struct | BfGenericParamFlag_Enum | BfGenericParamFlag_Var)) == 0) && (!checkArgType->IsValueType()))
  7083. {
  7084. if ((!ignoreErrors) && (PreFail()))
  7085. *errorOut = Fail(StrFormat("The type '%s' must be a value type in order to use it as parameter '%s' for '%s'",
  7086. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7087. return false;
  7088. }
  7089. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_StructPtr) &&
  7090. ((checkGenericParamFlags & (BfGenericParamFlag_StructPtr | BfGenericParamFlag_Var)) == 0) && (!checkArgType->IsPointer()))
  7091. {
  7092. if ((!ignoreErrors) && (PreFail()))
  7093. *errorOut = Fail(StrFormat("The type '%s' must be a pointer type in order to use it as parameter '%s' for '%s'",
  7094. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7095. return false;
  7096. }
  7097. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Class) &&
  7098. ((checkGenericParamFlags & (BfGenericParamFlag_Class | BfGenericParamFlag_Var)) == 0) && (!argIsReferenceType))
  7099. {
  7100. if ((!ignoreErrors) && (PreFail()))
  7101. *errorOut = Fail(StrFormat("The type '%s' must be a reference type in order to use it as parameter '%s' for '%s'",
  7102. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7103. return false;
  7104. }
  7105. if (genericParamInst->mGenericParamFlags & BfGenericParamFlag_Enum)
  7106. {
  7107. bool isEnum = checkArgType->IsEnum();
  7108. if ((origCheckArgType->IsGenericParam()) && (checkArgType->IsInstanceOf(mCompiler->mEnumTypeDef)))
  7109. isEnum = true;
  7110. if (((checkGenericParamFlags & (BfGenericParamFlag_Enum | BfGenericParamFlag_Var)) == 0) && (!isEnum))
  7111. {
  7112. if ((!ignoreErrors) && (PreFail()))
  7113. *errorOut = Fail(StrFormat("The type '%s' must be an enum type in order to use it as parameter '%s' for '%s'",
  7114. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7115. return false;
  7116. }
  7117. }
  7118. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Concrete) &&
  7119. ((checkGenericParamFlags & (BfGenericParamFlag_Interface | BfGenericParamFlag_Var)) == 0) && (checkArgType->IsInterface()))
  7120. {
  7121. if ((!ignoreErrors) && (PreFail()))
  7122. *errorOut = Fail(StrFormat("The type '%s' must be an concrete type in order to use it as parameter '%s' for '%s'",
  7123. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7124. return false;
  7125. }
  7126. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Interface) &&
  7127. ((checkGenericParamFlags & (BfGenericParamFlag_Interface | BfGenericParamFlag_Var)) == 0) && (!checkArgType->IsInterface()))
  7128. {
  7129. if ((!ignoreErrors) && (PreFail()))
  7130. *errorOut = Fail(StrFormat("The type '%s' must be an interface type in order to use it as parameter '%s' for '%s'",
  7131. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7132. return false;
  7133. }
  7134. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  7135. {
  7136. if (((checkGenericParamFlags & BfGenericParamFlag_Const) == 0) && (!checkArgType->IsConstExprValue()))
  7137. {
  7138. if ((!ignoreErrors) && (PreFail()))
  7139. *errorOut = Fail(StrFormat("The type '%s' must be a const value in order to use it as parameter '%s' for '%s'",
  7140. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7141. return false;
  7142. }
  7143. }
  7144. else
  7145. {
  7146. if (checkArgType->IsConstExprValue())
  7147. {
  7148. if ((!ignoreErrors) && (PreFail()))
  7149. *errorOut = Fail(StrFormat("The value '%s' cannot be used for generic type parameter '%s' for '%s'",
  7150. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7151. return false;
  7152. }
  7153. }
  7154. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Delete) != 0)
  7155. {
  7156. bool canDelete = false;
  7157. if (checkArgType->IsPointer())
  7158. canDelete = true;
  7159. else if (checkArgType->IsObjectOrInterface())
  7160. canDelete = true;
  7161. else if ((checkGenericParamFlags & (BfGenericParamFlag_Delete | BfGenericParamFlag_Var)) != 0)
  7162. canDelete = true;
  7163. if (!canDelete)
  7164. {
  7165. if ((!ignoreErrors) && (PreFail()))
  7166. {
  7167. if (checkArgType->IsGenericParam())
  7168. *errorOut = Fail(StrFormat("Must add 'where %s : delete' constraint in order to use type as parameter '%s' for '%s'",
  7169. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7170. else
  7171. *errorOut = Fail(StrFormat("The type '%s' must be a deletable type in order to use it as parameter '%s' for '%s'",
  7172. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7173. }
  7174. return false;
  7175. }
  7176. }
  7177. if (checkArgType->IsPointer())
  7178. {
  7179. auto ptrType = (BfPointerType*)checkArgType;
  7180. checkArgType = ptrType->mElementType;
  7181. }
  7182. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_New) != 0)
  7183. {
  7184. bool canAlloc = false;
  7185. if (auto checkTypeInst = checkArgType->ToTypeInstance())
  7186. {
  7187. if (checkTypeInst->IsObjectOrStruct())
  7188. {
  7189. checkTypeInst->mTypeDef->PopulateMemberSets();
  7190. BfMemberSetEntry* entry = NULL;
  7191. BfMethodDef* checkMethodDef = NULL;
  7192. checkTypeInst->mTypeDef->mMethodSet.TryGetWith(String("__BfCtor"), &entry);
  7193. if (entry != NULL)
  7194. checkMethodDef = (BfMethodDef*)entry->mMemberDef;
  7195. bool hadProtected = false;
  7196. while (checkMethodDef != NULL)
  7197. {
  7198. if (!checkMethodDef->mParams.IsEmpty())
  7199. {
  7200. auto firstParam = checkMethodDef->mParams[0];
  7201. if (((firstParam->mParamKind == BfParamKind_Params) || (firstParam->mParamKind == BfParamKind_AppendIdx) || (firstParam->mParamKind == BfParamKind_VarArgs)) ||
  7202. ((firstParam->mParamDeclaration != NULL) && (firstParam->mParamDeclaration->mInitializer != NULL)))
  7203. {
  7204. // Allow all-default params
  7205. }
  7206. else
  7207. {
  7208. checkMethodDef = checkMethodDef->mNextWithSameName;
  7209. continue;
  7210. }
  7211. }
  7212. if (checkMethodDef->mProtection == BfProtection_Public)
  7213. {
  7214. canAlloc = true;
  7215. break;
  7216. }
  7217. if ((checkMethodDef->mProtection == BfProtection_Protected) || (checkMethodDef->mProtection == BfProtection_ProtectedInternal))
  7218. hadProtected = true;
  7219. checkMethodDef = checkMethodDef->mNextWithSameName;
  7220. }
  7221. if ((!canAlloc) && (hadProtected) && (mCurTypeInstance != NULL))
  7222. canAlloc = TypeIsSubTypeOf(mCurTypeInstance, checkTypeInst, false);
  7223. }
  7224. }
  7225. else if (checkArgType->IsGenericParam())
  7226. {
  7227. canAlloc = (checkGenericParamFlags & (BfGenericParamFlag_New | BfGenericParamFlag_Var)) != 0;
  7228. }
  7229. else if (checkArgType->IsPrimitiveType())
  7230. {
  7231. // Any primitive types and stuff can be allocated
  7232. canAlloc = true;
  7233. }
  7234. if (!canAlloc)
  7235. {
  7236. if ((!ignoreErrors) && (PreFail()))
  7237. {
  7238. if (checkArgType->IsGenericParam())
  7239. *errorOut = Fail(StrFormat("Must add 'where %s : new' constraint in order to use type as parameter '%s' for '%s'",
  7240. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7241. else
  7242. *errorOut = Fail(StrFormat("The type '%s' must have an accessible default constructor in order to use it as parameter '%s' for '%s'",
  7243. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7244. }
  7245. return false;
  7246. }
  7247. }
  7248. if ((genericParamInst->mInterfaceConstraints.IsEmpty()) && (genericParamInst->mOperatorConstraints.IsEmpty()) && (genericParamInst->mTypeConstraint == NULL))
  7249. return true;
  7250. if (genericParamInst->mTypeConstraint != NULL)
  7251. {
  7252. bool constraintMatched = false;
  7253. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  7254. {
  7255. if (checkArgType->IsConstExprValue())
  7256. {
  7257. auto constExprValueType = (BfConstExprValueType*)checkArgType;
  7258. if (genericParamInst->mTypeConstraint->IsPrimitiveType())
  7259. {
  7260. auto primType = (BfPrimitiveType*)genericParamInst->mTypeConstraint;
  7261. // Let either an exact typematch or an undef pass through. Eventually instead of undefs we may want to do
  7262. // actual expression comparisons, but we are overly permissive now and then we may fail on specialization
  7263. if ((constExprValueType->mValue.mTypeCode != primType->mTypeDef->mTypeCode) &&
  7264. (constExprValueType->mValue.mTypeCode != BfTypeCode_Let) &&
  7265. (primType->mTypeDef->mTypeCode != BfTypeCode_Let))
  7266. {
  7267. bool doError = true;
  7268. if (BfIRConstHolder::IsInt(constExprValueType->mValue.mTypeCode))
  7269. {
  7270. if (BfIRConstHolder::IsInt(primType->mTypeDef->mTypeCode))
  7271. {
  7272. if (mCompiler->mSystem->DoesLiteralFit(primType->mTypeDef->mTypeCode, constExprValueType->mValue))
  7273. doError = false;
  7274. }
  7275. }
  7276. else if ((primType->mTypeDef->mTypeCode == BfTypeCode_Float) && ((constExprValueType->mValue.mTypeCode == BfTypeCode_Double)))
  7277. {
  7278. doError = false;
  7279. }
  7280. if (doError)
  7281. {
  7282. if ((!ignoreErrors) && (PreFail()))
  7283. *errorOut = Fail(StrFormat("Const generic argument '%s', declared with '%s', is not compatible with const constraint '%s' for '%s'", genericParamInst->GetName().c_str(),
  7284. _TypeToString(constExprValueType).c_str(), _TypeToString(genericParamInst->mTypeConstraint).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7285. return false;
  7286. }
  7287. }
  7288. }
  7289. else if (genericParamInst->mTypeConstraint != constExprValueType->mType)
  7290. {
  7291. if ((!ignoreErrors) && (PreFail()))
  7292. *errorOut = Fail(StrFormat("Const generic argument '%s', declared as '%s', is not compatible with const constraint '%s' for '%s'", genericParamInst->GetName().c_str(),
  7293. _TypeToString(constExprValueType).c_str(), _TypeToString(genericParamInst->mTypeConstraint).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  7294. return false;
  7295. }
  7296. }
  7297. }
  7298. else
  7299. {
  7300. BfType* convCheckConstraint = genericParamInst->mTypeConstraint;
  7301. if ((convCheckConstraint->IsUnspecializedType()) && (methodGenericArgs != NULL))
  7302. convCheckConstraint = ResolveGenericType(convCheckConstraint, NULL, methodGenericArgs, mCurTypeInstance);
  7303. if (convCheckConstraint == NULL)
  7304. return false;
  7305. if ((checkArgType->IsMethodRef()) || (checkArgType->IsFunction()))
  7306. {
  7307. if (convCheckConstraint->IsDelegate())
  7308. {
  7309. BfMethodInstance* checkMethodInstance;
  7310. if (checkArgType->IsMethodRef())
  7311. {
  7312. auto methodRefType = (BfMethodRefType*)checkArgType;
  7313. checkMethodInstance = methodRefType->mMethodRef;
  7314. }
  7315. else
  7316. {
  7317. checkMethodInstance = GetRawMethodInstanceAtIdx(checkArgType->ToTypeInstance(), 0, "Invoke");
  7318. }
  7319. auto invokeMethod = GetRawMethodInstanceAtIdx(convCheckConstraint->ToTypeInstance(), 0, "Invoke");
  7320. if (checkMethodInstance->HasExplicitThis() != 0)
  7321. {
  7322. // Don't allow functions with explicit 'this'
  7323. }
  7324. else
  7325. {
  7326. BfExprEvaluator exprEvaluator(this);
  7327. if (exprEvaluator.IsExactMethodMatch(checkMethodInstance, invokeMethod))
  7328. constraintMatched = true;
  7329. }
  7330. }
  7331. else if (convCheckConstraint->IsInstanceOf(mCompiler->mDelegateTypeDef))
  7332. constraintMatched = true;
  7333. }
  7334. else if (CanCast(GetFakeTypedValue(checkArgType), convCheckConstraint))
  7335. {
  7336. constraintMatched = true;
  7337. }
  7338. else if (origCheckArgType->IsWrappableType())
  7339. {
  7340. if (origCheckArgType->IsSizedArray())
  7341. {
  7342. auto sizedArrayType = (BfSizedArrayType*)origCheckArgType;
  7343. if (convCheckConstraint->IsGenericTypeInstance())
  7344. {
  7345. auto convCheckConstraintInst = (BfTypeInstance*)convCheckConstraint;
  7346. if (convCheckConstraintInst->IsInstanceOf(mCompiler->mSizedArrayTypeDef))
  7347. {
  7348. if (convCheckConstraintInst->mGenericTypeInfo->mTypeGenericArguments[0] == sizedArrayType->mElementType)
  7349. {
  7350. auto constExprValueType = (BfConstExprValueType*)convCheckConstraintInst->mGenericTypeInfo->mTypeGenericArguments[1];
  7351. if (sizedArrayType->mElementCount == constExprValueType->mValue.mInt64)
  7352. constraintMatched = true;
  7353. }
  7354. }
  7355. }
  7356. }
  7357. if (!constraintMatched)
  7358. {
  7359. BfType* wrappedStructType = GetWrappedStructType(origCheckArgType, false);
  7360. if (CanCast(GetFakeTypedValue(wrappedStructType), convCheckConstraint))
  7361. constraintMatched = true;
  7362. }
  7363. }
  7364. if (!constraintMatched)
  7365. {
  7366. if ((!ignoreErrors) && (PreFail()))
  7367. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must derive from '%s'", genericParamInst->GetName().c_str(),
  7368. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(), TypeToString(convCheckConstraint).c_str(),
  7369. _TypeToString(genericParamInst->mTypeConstraint).c_str()), checkArgTypeRef);
  7370. return false;
  7371. }
  7372. }
  7373. }
  7374. for (auto checkConstraint : genericParamInst->mInterfaceConstraints)
  7375. {
  7376. BfType* convCheckConstraint = checkConstraint;
  7377. if (convCheckConstraint->IsUnspecializedType())
  7378. convCheckConstraint = ResolveGenericType(convCheckConstraint, NULL, methodGenericArgs, mCurTypeInstance);
  7379. if (convCheckConstraint == NULL)
  7380. return false;
  7381. BfTypeInstance* typeConstraintInst = convCheckConstraint->ToTypeInstance();
  7382. bool implementsInterface = false;
  7383. if (origCheckArgType != checkArgType)
  7384. {
  7385. implementsInterface = CanCast(BfTypedValue(BfIRValue::sValueless, origCheckArgType), convCheckConstraint);
  7386. }
  7387. if (!implementsInterface)
  7388. implementsInterface = CanCast(BfTypedValue(BfIRValue::sValueless, checkArgType), convCheckConstraint);
  7389. if ((!implementsInterface) && (origCheckArgType->IsWrappableType()))
  7390. {
  7391. BfTypeInstance* wrappedStructType = GetWrappedStructType(origCheckArgType, false);
  7392. if (TypeIsSubTypeOf(wrappedStructType, typeConstraintInst))
  7393. implementsInterface = true;
  7394. }
  7395. if ((!implementsInterface) && (origCheckArgType->IsTypedPrimitive()))
  7396. {
  7397. auto underlyingType = origCheckArgType->GetUnderlyingType();
  7398. BfTypeInstance* wrappedStructType = GetWrappedStructType(underlyingType, false);
  7399. if (TypeIsSubTypeOf(wrappedStructType, typeConstraintInst))
  7400. implementsInterface = true;
  7401. }
  7402. if (!implementsInterface)
  7403. {
  7404. if ((!ignoreErrors) && (PreFail()))
  7405. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must implement '%s'", genericParamInst->GetName().c_str(),
  7406. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(), TypeToString(checkConstraint).c_str()), checkArgTypeRef);
  7407. return false;
  7408. }
  7409. }
  7410. for (auto& checkOpConstraint : genericParamInst->mOperatorConstraints)
  7411. {
  7412. auto leftType = checkOpConstraint.mLeftType;
  7413. if ((leftType != NULL) && (leftType->IsUnspecializedType()))
  7414. leftType = ResolveGenericType(leftType, NULL, methodGenericArgs, mCurTypeInstance);
  7415. if (leftType != NULL)
  7416. leftType = FixIntUnknown(leftType);
  7417. auto rightType = checkOpConstraint.mRightType;
  7418. if ((rightType != NULL) && (rightType->IsUnspecializedType()))
  7419. rightType = ResolveGenericType(rightType, NULL, methodGenericArgs, mCurTypeInstance);
  7420. if (rightType != NULL)
  7421. rightType = FixIntUnknown(rightType);
  7422. BfConstraintState constraintSet;
  7423. constraintSet.mPrevState = mContext->mCurConstraintState;
  7424. constraintSet.mGenericParamInstance = genericParamInst;
  7425. constraintSet.mLeftType = leftType;
  7426. constraintSet.mRightType = rightType;
  7427. SetAndRestoreValue<BfConstraintState*> prevConstraintSet(mContext->mCurConstraintState, &constraintSet);
  7428. if (!CheckConstraintState(NULL))
  7429. return false;
  7430. if (checkOpConstraint.mBinaryOp != BfBinaryOp_None)
  7431. {
  7432. BfExprEvaluator exprEvaluator(this);
  7433. BfTypedValue leftValue(mBfIRBuilder->GetFakeVal(), leftType);
  7434. BfTypedValue rightValue(mBfIRBuilder->GetFakeVal(), rightType);
  7435. //
  7436. {
  7437. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  7438. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  7439. exprEvaluator.PerformBinaryOperation(NULL, NULL, checkOpConstraint.mBinaryOp, NULL, (BfBinOpFlags)(BfBinOpFlag_NoClassify | BfBinOpFlag_IsConstraintCheck), leftValue, rightValue);
  7440. }
  7441. if ((!exprEvaluator.mResult) ||
  7442. (!CanCast(exprEvaluator.mResult, origCheckArgType, BfCastFlags_NoConversionOperator)))
  7443. {
  7444. if ((!ignoreErrors) && (PreFail()))
  7445. {
  7446. if (genericParamInst->mExternType != NULL)
  7447. *errorOut = Fail(StrFormat("Binary operation for '%s' must result in '%s' from binary operation '%s %s %s'",
  7448. GenericParamSourceToString(genericParamSource).c_str(), TypeToString(origCheckArgType).c_str(),
  7449. TypeToString(leftType).c_str(), BfGetOpName(checkOpConstraint.mBinaryOp), TypeToString(rightType).c_str()
  7450. ), checkArgTypeRef);
  7451. else
  7452. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must result from binary operation '%s %s %s'", genericParamInst->GetName().c_str(),
  7453. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(),
  7454. TypeToString(leftType).c_str(), BfGetOpName(checkOpConstraint.mBinaryOp), TypeToString(rightType).c_str()
  7455. ), checkArgTypeRef);
  7456. }
  7457. return false;
  7458. }
  7459. }
  7460. else
  7461. {
  7462. BfTypedValue rightValue(mBfIRBuilder->GetFakeVal(), rightType);
  7463. StringT<128> failedOpName;
  7464. if (checkOpConstraint.mCastToken == BfToken_Implicit)
  7465. {
  7466. if (!CanCast(rightValue, origCheckArgType, (BfCastFlags)(BfCastFlags_SilentFail | BfCastFlags_IsConstraintCheck)))
  7467. failedOpName = "implicit conversion from '";
  7468. }
  7469. else
  7470. {
  7471. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  7472. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  7473. if (checkOpConstraint.mCastToken == BfToken_Explicit)
  7474. {
  7475. if (!CastToValue(NULL, rightValue, origCheckArgType, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_SilentFail | BfCastFlags_IsConstraintCheck)))
  7476. failedOpName = "explicit conversion from '";
  7477. }
  7478. else
  7479. {
  7480. BfExprEvaluator exprEvaluator(this);
  7481. exprEvaluator.mResult = rightValue;
  7482. exprEvaluator.PerformUnaryOperation(NULL, checkOpConstraint.mUnaryOp, NULL, BfUnaryOpFlag_IsConstraintCheck);
  7483. if ((!exprEvaluator.mResult) ||
  7484. (!CanCast(exprEvaluator.mResult, origCheckArgType)))
  7485. {
  7486. failedOpName += "unary operation '";
  7487. failedOpName += BfGetOpName(checkOpConstraint.mUnaryOp);
  7488. }
  7489. }
  7490. }
  7491. if (!failedOpName.IsEmpty())
  7492. {
  7493. if ((!ignoreErrors) && (PreFail()))
  7494. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must result from %s%s'", genericParamInst->GetName().c_str(),
  7495. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(),
  7496. failedOpName.c_str(), TypeToString(rightType).c_str()
  7497. ), checkArgTypeRef);
  7498. return false;
  7499. }
  7500. }
  7501. }
  7502. return true;
  7503. }
  7504. BfGenericParamType* BfModule::GetGenericParamType(BfGenericParamKind paramKind, int paramIdx)
  7505. {
  7506. if (paramIdx < (int)mContext->mGenericParamTypes[paramKind].size())
  7507. {
  7508. auto genericParamType = mContext->mGenericParamTypes[paramKind][paramIdx];
  7509. return genericParamType;
  7510. }
  7511. auto genericParamType = new BfGenericParamType();
  7512. genericParamType->mContext = mContext;
  7513. genericParamType->mGenericParamKind = paramKind;
  7514. genericParamType->mGenericParamIdx = paramIdx;
  7515. PopulateType(genericParamType);
  7516. BF_ASSERT(paramIdx == (int)mContext->mGenericParamTypes[paramKind].size());
  7517. mContext->mGenericParamTypes[paramKind].push_back(genericParamType);
  7518. BfResolvedTypeSet::LookupContext lookupCtx;
  7519. lookupCtx.mModule = this;
  7520. BfResolvedTypeSet::EntryRef typeEntry;
  7521. auto inserted = mContext->mResolvedTypes.Insert(genericParamType, &lookupCtx, &typeEntry);
  7522. BF_ASSERT(inserted);
  7523. typeEntry->mValue = genericParamType;
  7524. return genericParamType;
  7525. }
  7526. static int sValueFromExprIdx = 0;
  7527. BfTypedValue BfModule::FlushNullConditional(BfTypedValue result, bool ignoreNullable)
  7528. {
  7529. auto pendingNullCond = mCurMethodState->mPendingNullConditional;
  7530. if ((result) && (!ignoreNullable))
  7531. {
  7532. if (result.mType->IsVar())
  7533. return result;
  7534. auto notNullBB = mBfIRBuilder->GetInsertBlock();
  7535. //TODO: Make this work, needed for 'void' and such
  7536. BfType* nullableType = NULL;
  7537. if ((result.mType->IsValueType()) && (!result.mType->IsNullable()))
  7538. {
  7539. BfTypeVector typeVec;
  7540. typeVec.push_back(result.mType);
  7541. nullableType = ResolveTypeDef(mCompiler->mNullableTypeDef, typeVec);
  7542. BF_ASSERT(nullableType != NULL);
  7543. }
  7544. // Go back to start and do any setup we need
  7545. mBfIRBuilder->SetInsertPoint(pendingNullCond->mPrevBB);
  7546. BfTypedValue nullableTypedValue;
  7547. if (nullableType != NULL)
  7548. {
  7549. nullableTypedValue = BfTypedValue(CreateAlloca(nullableType, true, "nullCond.nullable"), nullableType, true);
  7550. mBfIRBuilder->CreateMemSet(nullableTypedValue.mValue, GetConstValue(0, GetPrimitiveType(BfTypeCode_Int8)),
  7551. GetConstValue(nullableType->mSize), nullableType->mAlign);
  7552. }
  7553. mBfIRBuilder->CreateBr(pendingNullCond->mCheckBB);
  7554. // Now that we have the nullableTypedValue we can set that, or just jump if we didn't need it
  7555. mBfIRBuilder->SetInsertPoint(notNullBB);
  7556. result = LoadValue(result);
  7557. if (nullableTypedValue)
  7558. {
  7559. auto elementType = nullableType->GetUnderlyingType();
  7560. if (elementType->IsVar())
  7561. {
  7562. // Do nothing
  7563. }
  7564. else if (elementType->IsValuelessType())
  7565. {
  7566. BfIRValue ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 1); // mHasValue
  7567. mBfIRBuilder->CreateStore(GetConstValue(1, GetPrimitiveType(BfTypeCode_Boolean)), ptrValue);
  7568. }
  7569. else
  7570. {
  7571. BfIRValue ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 1); // mValue
  7572. mBfIRBuilder->CreateAlignedStore(result.mValue, ptrValue, result.mType->mAlign);
  7573. ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 2); // mHasValue
  7574. mBfIRBuilder->CreateAlignedStore(GetConstValue(1, GetPrimitiveType(BfTypeCode_Boolean)), ptrValue, 1);
  7575. }
  7576. result = nullableTypedValue;
  7577. }
  7578. mBfIRBuilder->CreateBr(pendingNullCond->mDoneBB);
  7579. AddBasicBlock(pendingNullCond->mDoneBB);
  7580. if (nullableType == NULL)
  7581. {
  7582. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapType(result.mType), 1 + (int)pendingNullCond->mNotNullBBs.size());
  7583. mBfIRBuilder->AddPhiIncoming(phi, result.mValue, notNullBB);
  7584. mBfIRBuilder->AddPhiIncoming(phi, GetDefaultValue(result.mType), pendingNullCond->mCheckBB);
  7585. for (int notNullIdx = 0; notNullIdx < (int)pendingNullCond->mNotNullBBs.size() - 1; notNullIdx++)
  7586. {
  7587. auto prevNotNullBB = pendingNullCond->mNotNullBBs[notNullIdx];
  7588. mBfIRBuilder->AddPhiIncoming(phi, GetDefaultValue(result.mType), prevNotNullBB);
  7589. }
  7590. result.mValue = phi;
  7591. }
  7592. }
  7593. else
  7594. {
  7595. mBfIRBuilder->CreateBr(pendingNullCond->mDoneBB);
  7596. mBfIRBuilder->SetInsertPoint(pendingNullCond->mPrevBB);
  7597. mBfIRBuilder->CreateBr(pendingNullCond->mCheckBB);
  7598. AddBasicBlock(pendingNullCond->mDoneBB);
  7599. }
  7600. delete mCurMethodState->mPendingNullConditional;
  7601. mCurMethodState->mPendingNullConditional = NULL;
  7602. return result;
  7603. }
  7604. BF_NOINLINE void BfModule::EvaluateWithNewConditionalScope(BfExprEvaluator& exprEvaluator, BfExpression* expr, BfEvalExprFlags flags)
  7605. {
  7606. BfDeferredLocalAssignData deferredLocalAssignData(mCurMethodState->mCurScope);
  7607. SetAndRestoreValue<BfDeferredLocalAssignData*> prevDLA(mCurMethodState->mDeferredLocalAssignData);
  7608. if (mCurMethodState != NULL)
  7609. {
  7610. deferredLocalAssignData.mIsIfCondition = true;
  7611. deferredLocalAssignData.mIfMayBeSkipped = true;
  7612. deferredLocalAssignData.ExtendFrom(mCurMethodState->mDeferredLocalAssignData, false);
  7613. deferredLocalAssignData.mVarIdBarrier = mCurMethodState->GetRootMethodState()->mCurLocalVarId;
  7614. mCurMethodState->mDeferredLocalAssignData = &deferredLocalAssignData;
  7615. }
  7616. BfScopeData newScope;
  7617. newScope.mOuterIsConditional = true;
  7618. newScope.mAllowTargeting = false;
  7619. if (mCurMethodState != NULL)
  7620. {
  7621. mCurMethodState->AddScope(&newScope);
  7622. NewScopeState(true, false);
  7623. }
  7624. exprEvaluator.mBfEvalExprFlags = (BfEvalExprFlags)(exprEvaluator.mBfEvalExprFlags | flags);
  7625. exprEvaluator.Evaluate(expr, (flags & BfEvalExprFlags_PropogateNullConditional) != 0, (flags & BfEvalExprFlags_IgnoreNullConditional) != 0, (flags & BfEvalExprFlags_AllowSplat) != 0);
  7626. if (mCurMethodState != NULL)
  7627. RestoreScopeState();
  7628. }
  7629. BfTypedValue BfModule::CreateValueFromExpression(BfExprEvaluator& exprEvaluator, BfExpression* expr, BfType* wantTypeRef, BfEvalExprFlags flags, BfType** outOrigType)
  7630. {
  7631. //
  7632. {
  7633. BP_ZONE("CreateValueFromExpression:CheckStack");
  7634. StackHelper stackHelper;
  7635. if (!stackHelper.CanStackExpand(64 * 1024))
  7636. {
  7637. BfTypedValue result;
  7638. if (!stackHelper.Execute([&]()
  7639. {
  7640. result = CreateValueFromExpression(exprEvaluator, expr, wantTypeRef, flags, outOrigType);
  7641. }))
  7642. {
  7643. Fail("Expression too complex to compile", expr);
  7644. }
  7645. return result;
  7646. }
  7647. }
  7648. BP_ZONE("BfModule::CreateValueFromExpression");
  7649. if (outOrigType != NULL)
  7650. *outOrigType = NULL;
  7651. exprEvaluator.mExpectingType = wantTypeRef;
  7652. exprEvaluator.mBfEvalExprFlags = (BfEvalExprFlags)(exprEvaluator.mBfEvalExprFlags | flags);
  7653. exprEvaluator.mExplicitCast = (flags & BfEvalExprFlags_ExplicitCast) != 0;
  7654. if ((flags & BfEvalExprFlags_CreateConditionalScope) != 0)
  7655. {
  7656. if ((mCurMethodState == NULL) || (mCurMethodState->mCurScope->mScopeKind != BfScopeKind_StatementTarget_Conditional))
  7657. {
  7658. EvaluateWithNewConditionalScope(exprEvaluator, expr, flags);
  7659. }
  7660. else
  7661. {
  7662. SetAndRestoreValue<bool> prevIsConditional(mCurMethodState->mCurScope->mIsConditional, true);
  7663. exprEvaluator.Evaluate(expr, (flags & BfEvalExprFlags_PropogateNullConditional) != 0, (flags & BfEvalExprFlags_IgnoreNullConditional) != 0, true);
  7664. }
  7665. }
  7666. else
  7667. exprEvaluator.Evaluate(expr, (flags & BfEvalExprFlags_PropogateNullConditional) != 0, (flags & BfEvalExprFlags_IgnoreNullConditional) != 0, true);
  7668. if (!exprEvaluator.mResult)
  7669. {
  7670. if ((flags & BfEvalExprFlags_InferReturnType) != 0)
  7671. return exprEvaluator.mResult;
  7672. if (!mCompiler->mPassInstance->HasFailed())
  7673. {
  7674. if (PreFail())
  7675. Fail("INTERNAL ERROR: No expression result returned but no error caught in expression evaluator", expr);
  7676. }
  7677. return BfTypedValue();
  7678. }
  7679. auto typedVal = exprEvaluator.mResult;
  7680. if (typedVal.mKind == BfTypedValueKind_GenericConstValue)
  7681. {
  7682. BF_ASSERT(typedVal.mType->IsGenericParam());
  7683. auto genericParamDef = GetGenericParamInstance((BfGenericParamType*)typedVal.mType);
  7684. bool handled = false;
  7685. if ((genericParamDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  7686. {
  7687. auto genericTypeConstraint = genericParamDef->mTypeConstraint;
  7688. if (genericTypeConstraint != NULL)
  7689. {
  7690. auto underlyingConstraint = genericTypeConstraint;
  7691. if ((underlyingConstraint != NULL) && (underlyingConstraint->IsBoxed()))
  7692. underlyingConstraint = underlyingConstraint->GetUnderlyingType();
  7693. if (underlyingConstraint != NULL)
  7694. {
  7695. BfTypedValue result;
  7696. result.mKind = BfTypedValueKind_Value;
  7697. result.mType = genericTypeConstraint;
  7698. result.mValue = mBfIRBuilder->GetUndefConstValue(mBfIRBuilder->MapType(underlyingConstraint));
  7699. typedVal = result;
  7700. handled = true;
  7701. }
  7702. }
  7703. }
  7704. if (!handled)
  7705. {
  7706. //Fail("Only const generic parameters can be used as values", expr);
  7707. AssertErrorState();
  7708. return BfTypedValue();
  7709. }
  7710. }
  7711. if ((flags & BfEvalExprFlags_AllowIntUnknown) == 0)
  7712. FixIntUnknown(typedVal);
  7713. if (!mBfIRBuilder->mIgnoreWrites)
  7714. FixValueActualization(typedVal);
  7715. exprEvaluator.CheckResultForReading(typedVal);
  7716. if ((wantTypeRef == NULL) || (!wantTypeRef->IsRef()))
  7717. {
  7718. if ((flags & BfEvalExprFlags_NoCast) == 0)
  7719. {
  7720. // Only allow a 'ref' type if we have an explicit 'ref' operator
  7721. bool allowRef = false;
  7722. BfAstNode* checkExpr = expr;
  7723. while (checkExpr != NULL)
  7724. {
  7725. if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(checkExpr))
  7726. checkExpr = parenExpr->mExpression;
  7727. else if (auto unaryOp = BfNodeDynCast<BfUnaryOperatorExpression>(checkExpr))
  7728. {
  7729. if ((unaryOp->mOp == BfUnaryOp_Ref) || (unaryOp->mOp == BfUnaryOp_Mut))
  7730. allowRef = true;
  7731. break;
  7732. }
  7733. if (auto block = BfNodeDynCast<BfBlock>(checkExpr))
  7734. {
  7735. if (block->mChildArr.mSize == 0)
  7736. break;
  7737. checkExpr = block->mChildArr.back();
  7738. }
  7739. else
  7740. break;
  7741. }
  7742. if (!allowRef)
  7743. typedVal = RemoveRef(typedVal);
  7744. }
  7745. }
  7746. if ((!typedVal.mType->IsComposite()) && (!typedVal.mType->IsGenericParam())) // Load non-structs by default
  7747. {
  7748. if ((!mBfIRBuilder->mIgnoreWrites) && (!typedVal.mType->IsDataIncomplete()) && (!typedVal.mType->IsValuelessType()) && (!typedVal.mType->IsVar()))
  7749. {
  7750. BF_ASSERT(!typedVal.mValue.IsFake());
  7751. }
  7752. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  7753. }
  7754. if (wantTypeRef != NULL)
  7755. {
  7756. if (outOrigType != NULL)
  7757. *outOrigType = typedVal.mType;
  7758. if (((flags & BfEvalExprFlags_NoCast) == 0) && (!wantTypeRef->IsVar()))
  7759. {
  7760. BfCastFlags castFlags = ((flags & BfEvalExprFlags_ExplicitCast) != 0) ? BfCastFlags_Explicit : BfCastFlags_None;
  7761. if ((flags & BfEvalExprFlags_FieldInitializer) != 0)
  7762. castFlags = (BfCastFlags)(castFlags | BfCastFlags_WarnOnBox);
  7763. typedVal = Cast(expr, typedVal, wantTypeRef, castFlags);
  7764. if (!typedVal)
  7765. return typedVal;
  7766. }
  7767. if (exprEvaluator.mIsVolatileReference)
  7768. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  7769. }
  7770. if ((typedVal.mType->IsValueType()) && ((flags & BfEvalExprFlags_NoValueAddr) != 0))
  7771. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  7772. return typedVal;
  7773. }
  7774. BfTypedValue BfModule::CreateValueFromExpression(BfExpression* expr, BfType* wantTypeRef, BfEvalExprFlags flags, BfType** outOrigType)
  7775. {
  7776. BfExprEvaluator exprEvaluator(this);
  7777. return CreateValueFromExpression(exprEvaluator, expr, wantTypeRef, flags, outOrigType);
  7778. }
  7779. BfTypedValue BfModule::GetOrCreateVarAddr(BfExpression* expr)
  7780. {
  7781. BfExprEvaluator exprEvaluator(this);
  7782. exprEvaluator.Evaluate(expr);
  7783. if (!exprEvaluator.mResult)
  7784. {
  7785. Fail("Invalid expression type", expr);
  7786. return BfTypedValue();
  7787. }
  7788. if (!exprEvaluator.mResult.IsAddr())
  7789. {
  7790. Fail("Cannot assign to value", expr);
  7791. return BfTypedValue();
  7792. }
  7793. return exprEvaluator.mResult;
  7794. }
  7795. // Clear memory, set classVData, call init. Actual ctor is called elsewhere.
  7796. void BfModule::InitTypeInst(BfTypedValue typedValue, BfScopeData* scopeData, bool zeroMemory, BfIRValue sizeValue)
  7797. {
  7798. auto typeInstance = typedValue.mType->ToTypeInstance();
  7799. if (zeroMemory)
  7800. {
  7801. int zeroAlign = typedValue.mType->mAlign;
  7802. if (typeInstance != NULL)
  7803. zeroAlign = typeInstance->mInstAlign;
  7804. mBfIRBuilder->CreateMemSet(typedValue.mValue, GetConstValue8(0), sizeValue, zeroAlign);
  7805. }
  7806. if (!typedValue.mType->IsObject())
  7807. {
  7808. return;
  7809. }
  7810. if ((scopeData == NULL) && (mCurMethodState != NULL))
  7811. return; // Handled in heap alloc funcs
  7812. auto typeDef = typeInstance->mTypeDef;
  7813. mBfIRBuilder->PopulateType(typedValue.mType);
  7814. auto vObjectAddr = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, 0);
  7815. bool isAutocomplete = mCompiler->IsAutocomplete();
  7816. BfIRValue vDataRef;
  7817. if (!isAutocomplete)
  7818. {
  7819. vDataRef = GetClassVDataPtr(typeInstance);
  7820. }
  7821. auto i8Type = GetPrimitiveType(BfTypeCode_Int8);
  7822. auto ptrType = CreatePointerType(i8Type);
  7823. auto ptrPtrType = CreatePointerType(ptrType);
  7824. PopulateType(ptrPtrType, BfPopulateType_Declaration);
  7825. PopulateType(ptrType, BfPopulateType_Declaration);
  7826. auto destAddr = mBfIRBuilder->CreateBitCast(vObjectAddr, mBfIRBuilder->MapType(ptrPtrType));
  7827. if (!isAutocomplete)
  7828. {
  7829. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  7830. {
  7831. auto objectPtr = mBfIRBuilder->CreateBitCast(destAddr, mBfIRBuilder->MapType(mContext->mBfObjectType));
  7832. SizedArray<BfIRValue, 4> llvmArgs;
  7833. llvmArgs.push_back(objectPtr);
  7834. llvmArgs.push_back(vDataRef);
  7835. auto objectStackInitMethod = GetInternalMethod("Dbg_ObjectStackInit");
  7836. if (objectStackInitMethod)
  7837. mBfIRBuilder->CreateCall(objectStackInitMethod.mFunc, llvmArgs);
  7838. }
  7839. else
  7840. {
  7841. auto srcVal = mBfIRBuilder->CreateBitCast(vDataRef, mBfIRBuilder->MapType(ptrType));
  7842. auto objectPtr = mBfIRBuilder->CreateBitCast(destAddr, mBfIRBuilder->MapType(ptrType));
  7843. mBfIRBuilder->CreateStore(srcVal, destAddr);
  7844. }
  7845. }
  7846. }
  7847. BfIRValue BfModule::AllocBytes(BfAstNode* refNode, const BfAllocTarget& allocTarget, BfType* type, BfIRValue sizeValue, BfIRValue alignValue, BfAllocFlags allocFlags/*, bool zeroMemory, bool defaultToMalloc*/)
  7848. {
  7849. BfIRValue result;
  7850. BfType* ptrType;
  7851. if ((type->IsObject()) && ((allocFlags & BfAllocFlags_RawArray) == 0))
  7852. ptrType = type;
  7853. else
  7854. ptrType = CreatePointerType(type);
  7855. if ((allocTarget.mScopedInvocationTarget != NULL) || (allocTarget.mCustomAllocator))
  7856. {
  7857. auto intType = GetPrimitiveType(BfTypeCode_IntPtr);
  7858. SizedArray<BfExpression*, 2> argExprs;
  7859. BfTypedValueExpression typedValueExpr;
  7860. typedValueExpr.Init(BfTypedValue(sizeValue, intType));
  7861. typedValueExpr.mRefNode = refNode;
  7862. argExprs.push_back(&typedValueExpr);
  7863. BfTypedValueExpression appendSizeValueExpr;
  7864. appendSizeValueExpr.Init(BfTypedValue(alignValue, intType));
  7865. appendSizeValueExpr.mRefNode = refNode;
  7866. argExprs.push_back(&appendSizeValueExpr);
  7867. BfExprEvaluator exprEvaluator(this);
  7868. BfTypedValue allocResult;
  7869. if (allocTarget.mScopedInvocationTarget != NULL)
  7870. {
  7871. SizedArray<BfTypeReference*, 2> genericArgs;
  7872. exprEvaluator.DoInvocation(allocTarget.mScopedInvocationTarget, NULL, argExprs, BfMethodGenericArguments());
  7873. allocResult = LoadValue(exprEvaluator.mResult);
  7874. }
  7875. else if (allocTarget.mCustomAllocator)
  7876. {
  7877. auto customTypeInst = allocTarget.mCustomAllocator.mType->ToTypeInstance();
  7878. if (customTypeInst == NULL)
  7879. {
  7880. if (allocTarget.mCustomAllocator.mType->IsStructPtr())
  7881. customTypeInst = allocTarget.mCustomAllocator.mType->GetUnderlyingType()->ToTypeInstance();
  7882. }
  7883. if (customTypeInst == NULL)
  7884. {
  7885. Fail(StrFormat("Type '%s' cannot be used as a custom allocator", TypeToString(allocTarget.mCustomAllocator.mType).c_str()), refNode);
  7886. }
  7887. else
  7888. {
  7889. BfTypedValueExpression typeValueExpr;
  7890. String allocMethodName = "Alloc";
  7891. if (GetRawMethodByName(customTypeInst, "AllocTyped", -1, true, true))
  7892. {
  7893. allocMethodName = "AllocTyped";
  7894. auto typeType = ResolveTypeDef(mCompiler->mTypeTypeDef);
  7895. auto typeRefVal = CreateTypeDataRef(type);
  7896. typeValueExpr.Init(BfTypedValue(typeRefVal, typeType));
  7897. typeValueExpr.mRefNode = refNode;
  7898. argExprs.Insert(0, &typeValueExpr);
  7899. }
  7900. if (HasMixin(customTypeInst, allocMethodName, 2))
  7901. {
  7902. BfSizedArray<BfExpression*> argExprArr;
  7903. argExprArr.mSize = (int)argExprs.size();
  7904. argExprArr.mVals = &argExprs[0];
  7905. exprEvaluator.InjectMixin(refNode, allocTarget.mCustomAllocator, false, allocMethodName, argExprs, {});
  7906. allocResult = exprEvaluator.GetResult();
  7907. }
  7908. else
  7909. {
  7910. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  7911. BfResolvedArgs argValues(&sizedArgExprs);
  7912. exprEvaluator.ResolveArgValues(argValues);
  7913. SetAndRestoreValue<bool> prevNoBind(mCurMethodState->mNoBind, true);
  7914. allocResult = exprEvaluator.MatchMethod(refNode, NULL, allocTarget.mCustomAllocator, false, false, allocMethodName, argValues, BfMethodGenericArguments());
  7915. }
  7916. }
  7917. }
  7918. if (allocResult)
  7919. {
  7920. if (allocResult.mType->IsVoidPtr())
  7921. result = mBfIRBuilder->CreateBitCast(allocResult.mValue, mBfIRBuilder->MapType(ptrType));
  7922. else
  7923. result = CastToValue(refNode, allocResult, ptrType, BfCastFlags_Explicit);
  7924. return result;
  7925. }
  7926. }
  7927. if ((allocFlags & BfAllocFlags_NoDefaultToMalloc) != 0)
  7928. return result;
  7929. if ((mCompiler->mOptions.mDebugAlloc) && (!mIsComptimeModule))
  7930. {
  7931. BfIRValue allocData = GetDbgRawAllocData(type);
  7932. BfModuleMethodInstance allocMethod = GetInternalMethod("Dbg_RawAlloc", 2);
  7933. SizedArray<BfIRValue, 2> llvmArgs;
  7934. llvmArgs.push_back(sizeValue);
  7935. llvmArgs.push_back(allocData);
  7936. BfIRValue bitData = mBfIRBuilder->CreateCall(allocMethod.mFunc, llvmArgs);
  7937. return mBfIRBuilder->CreateBitCast(bitData, mBfIRBuilder->MapType(ptrType));
  7938. }
  7939. BfModuleMethodInstance moduleMethodInstance;
  7940. moduleMethodInstance = GetInternalMethod("Malloc");
  7941. SizedArray<BfIRValue, 1> llvmArgs;
  7942. llvmArgs.push_back(sizeValue);
  7943. auto func = moduleMethodInstance.mFunc;
  7944. if ((!func) || (func.IsFake()))
  7945. {
  7946. BF_ASSERT((mCompiler->mIsResolveOnly) || (mBfIRBuilder->mIgnoreWrites));
  7947. return mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(ptrType));
  7948. }
  7949. BfIRValue bitData = mBfIRBuilder->CreateCall(func, llvmArgs);
  7950. if ((allocFlags & BfAllocFlags_ZeroMemory) != 0)
  7951. mBfIRBuilder->CreateMemSet(bitData, GetConstValue8(0), sizeValue, alignValue);
  7952. result = mBfIRBuilder->CreateBitCast(bitData, mBfIRBuilder->MapType(ptrType));
  7953. return result;
  7954. }
  7955. BfIRValue BfModule::GetMarkFuncPtr(BfType* type)
  7956. {
  7957. if (type->IsStruct())
  7958. {
  7959. auto typeInstance = type->ToTypeInstance();
  7960. BfModuleMethodInstance moduleMethodInst = GetMethodByName(typeInstance, BF_METHODNAME_MARKMEMBERS, 0, true);
  7961. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  7962. }
  7963. else if (type->IsObjectOrInterface())
  7964. {
  7965. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  7966. BfModuleMethodInstance moduleMethodInst = GetMethodByName(gcType, "MarkDerefedObject");
  7967. BF_ASSERT(moduleMethodInst.mFunc);
  7968. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  7969. }
  7970. else
  7971. {
  7972. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  7973. BfExprEvaluator exprEvaluator(this);
  7974. SizedArray<BfResolvedArg, 1> resolvedArgs;
  7975. BfResolvedArg resolvedArg;
  7976. resolvedArg.mTypedValue = BfTypedValue(mBfIRBuilder->GetFakeVal(), type, type->IsComposite());
  7977. resolvedArgs.Add(resolvedArg);
  7978. BfMethodMatcher methodMatcher(NULL, this, "Mark", resolvedArgs, BfMethodGenericArguments());
  7979. methodMatcher.CheckType(gcType, BfTypedValue(), false);
  7980. BfModuleMethodInstance moduleMethodInst = exprEvaluator.GetSelectedMethod(NULL, methodMatcher.mBestMethodTypeInstance, methodMatcher.mBestMethodDef, methodMatcher);
  7981. BF_ASSERT(moduleMethodInst.mFunc);
  7982. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  7983. }
  7984. return BfIRValue();
  7985. }
  7986. BfIRValue BfModule::GetDbgRawAllocData(BfType* type)
  7987. {
  7988. BfIRValue allocDataValue;
  7989. if (mDbgRawAllocDataRefs.TryGetValue(type, &allocDataValue))
  7990. return allocDataValue;
  7991. BfIRValue markFuncPtr;
  7992. if (type->WantsGCMarking())
  7993. markFuncPtr = GetMarkFuncPtr(type);
  7994. else
  7995. markFuncPtr = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  7996. BfIRValue typeDataRef = CreateTypeDataRef(type);
  7997. auto dbgRawAllocDataType = ResolveTypeDef(mCompiler->mDbgRawAllocDataTypeDef)->ToTypeInstance();
  7998. BfTypeInstance* typeInstance = type->ToTypeInstance();
  7999. if (typeInstance == NULL)
  8000. {
  8001. typeInstance = GetWrappedStructType(type);
  8002. if (typeInstance != NULL)
  8003. AddDependency(typeInstance, mCurTypeInstance, BfDependencyMap::DependencyFlag_Allocates);
  8004. }
  8005. if (typeInstance != NULL)
  8006. PopulateType(typeInstance);
  8007. int stackCount = mCompiler->mOptions.mAllocStackCount;
  8008. if ((typeInstance != NULL) && (typeInstance->mTypeOptionsIdx != -1))
  8009. {
  8010. auto typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  8011. stackCount = BfTypeOptions::Apply(stackCount, typeOptions->mAllocStackTraceDepth);
  8012. }
  8013. SizedArray<BfIRValue, 2> dataValues;
  8014. dataValues.Add(mBfIRBuilder->CreateConstAggZero(mBfIRBuilder->MapType(dbgRawAllocDataType->mBaseType, BfIRPopulateType_Full)));
  8015. dataValues.Add(typeDataRef);
  8016. dataValues.Add(markFuncPtr);
  8017. dataValues.Add(mBfIRBuilder->CreateConst(BfTypeCode_Int32, stackCount));
  8018. BfIRValue dataStruct = mBfIRBuilder->CreateConstAgg_Value(mBfIRBuilder->MapType(dbgRawAllocDataType, BfIRPopulateType_Full), dataValues);
  8019. allocDataValue = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(dbgRawAllocDataType), true, BfIRLinkageType_Internal, dataStruct, "__allocData_" + BfSafeMangler::Mangle(type));
  8020. mDbgRawAllocDataRefs.TryAdd(type, allocDataValue);
  8021. return allocDataValue;
  8022. }
  8023. BfIRValue BfModule::AllocFromType(BfType* type, const BfAllocTarget& allocTarget, BfIRValue appendSizeValue, BfIRValue arraySize, int arrayDim, BfAllocFlags allocFlags, int alignOverride)
  8024. {
  8025. BP_ZONE("AllocFromType");
  8026. BfScopeData* scopeData = allocTarget.mScopeData;
  8027. BF_ASSERT(!type->IsVar());
  8028. auto typeInstance = type->ToTypeInstance();
  8029. if ((typeInstance == NULL) && (type->IsGenericParam()))
  8030. typeInstance = mContext->mBfObjectType;
  8031. bool isHeapAlloc = scopeData == NULL;
  8032. bool isScopeAlloc = scopeData != NULL;
  8033. bool isLoopedAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsLooped(scopeData));
  8034. bool isDynAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsDyn(scopeData));
  8035. bool isRawArrayAlloc = (allocFlags & BfAllocFlags_RawArray) != 0;
  8036. bool zeroMemory = (allocFlags & BfAllocFlags_ZeroMemory) != 0;
  8037. bool noDtorCall = (allocFlags & BfAllocFlags_NoDtorCall) != 0;
  8038. if ((type->IsValuelessType()) && ((!arraySize) || (isRawArrayAlloc)))
  8039. {
  8040. BfPointerType* ptrType = CreatePointerType(type);
  8041. auto val = mBfIRBuilder->CreateIntToPtr(mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1), mBfIRBuilder->MapType(ptrType));
  8042. return val;
  8043. }
  8044. if (typeInstance != NULL)
  8045. mBfIRBuilder->PopulateType(typeInstance);
  8046. bool hasCustomAllocator = (allocTarget.mCustomAllocator) || (allocTarget.mScopedInvocationTarget != NULL);
  8047. if ((!hasCustomAllocator) && (mBfIRBuilder->mIgnoreWrites))
  8048. {
  8049. return mBfIRBuilder->GetFakeVal();
  8050. }
  8051. AddDependency(type, mCurTypeInstance, BfDependencyMap::DependencyFlag_Allocates);
  8052. BfIRValue sizeValue;
  8053. BfIRType allocType = mBfIRBuilder->MapType(type);
  8054. int allocSize = type->mSize;
  8055. int allocAlign = type->mAlign;
  8056. if (typeInstance != NULL)
  8057. {
  8058. if ((!mBfIRBuilder->mIgnoreWrites) && (!mIsComptimeModule))
  8059. typeInstance->mHasBeenInstantiated = true;
  8060. allocSize = typeInstance->mInstSize;
  8061. allocAlign = typeInstance->mInstAlign;
  8062. //if (typeInstance->IsEnum())
  8063. //allocType = typeInstance->mIRType;
  8064. allocType = mBfIRBuilder->MapTypeInst(typeInstance);
  8065. }
  8066. if (alignOverride != -1)
  8067. allocAlign = alignOverride;
  8068. // The "dynSize" cases:
  8069. // If we are not dyn, but we are a variable size and could be looped over multiple times then we attempt to reuse
  8070. // the last stack space. We won't use StackSave and StackRestore because a scoped alloc that occurs after this but
  8071. // needs to be retained after the current scopeData (ie: scopeData::), then it would cause these allocs to accumulate even
  8072. // though we'd expect their stack space to be released
  8073. auto _CreateDynAlloc = [&](const BfIRValue& sizeValue, int align)
  8074. {
  8075. MarkDynStack(scopeData);
  8076. BfType* intType = GetPrimitiveType(BfTypeCode_IntPtr);
  8077. // For dynamically sized scoped allocs, we need to check the previous size to see if we need to realloc
  8078. BfType* voidType = GetPrimitiveType(BfTypeCode_None);
  8079. BfType* voidPtrType = CreatePointerType(voidType);
  8080. if (!mCurMethodState->mDynStackRevIdx)
  8081. {
  8082. mCurMethodState->mDynStackRevIdx = CreateAlloca(intType, false, "curDynStackRevIdx");
  8083. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  8084. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  8085. auto storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), mCurMethodState->mDynStackRevIdx);
  8086. mBfIRBuilder->ClearDebugLocation(storeInst);
  8087. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  8088. }
  8089. auto byteType = GetPrimitiveType(BfTypeCode_Int8);
  8090. auto bytePtrType = CreatePointerType(byteType);
  8091. auto dynSizeAllocaInst = CreateAlloca(intType, false, "dynSize");
  8092. auto dynStackRevIdx = CreateAlloca(intType, false, "dynStackRevIdx");
  8093. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  8094. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  8095. auto storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), dynSizeAllocaInst);
  8096. mBfIRBuilder->ClearDebugLocation(storeInst);
  8097. storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), dynStackRevIdx);
  8098. mBfIRBuilder->ClearDebugLocation(storeInst);
  8099. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  8100. auto dynPtrAllocaInst = CreateAlloca(bytePtrType, false, "dynPtr");
  8101. if (IsTargetingBeefBackend())
  8102. {
  8103. // Since we don't allocate a debug variable for this, with LifetimeExtends, the easiest way
  8104. // to ensure there isn't any register collision during looping is just to not allow it to
  8105. // bind to a register at all
  8106. mBfIRBuilder->SetAllocaForceMem(dynSizeAllocaInst);
  8107. mBfIRBuilder->SetAllocaForceMem(dynPtrAllocaInst);
  8108. }
  8109. auto resizeBB = mBfIRBuilder->CreateBlock("dynAlloc.resize");
  8110. auto endBB = mBfIRBuilder->CreateBlock("dynAlloc.end");
  8111. auto verCheckBB = mBfIRBuilder->CreateBlock("dynAlloc.verCheck");
  8112. auto curDynStackRevIdx = mBfIRBuilder->CreateLoad(mCurMethodState->mDynStackRevIdx);
  8113. auto prevSize = mBfIRBuilder->CreateLoad(dynSizeAllocaInst);
  8114. auto isGreater = mBfIRBuilder->CreateCmpGT(sizeValue, prevSize, true);
  8115. mBfIRBuilder->CreateCondBr(isGreater, resizeBB, verCheckBB);
  8116. mBfIRBuilder->AddBlock(verCheckBB);
  8117. mBfIRBuilder->SetInsertPoint(verCheckBB);
  8118. auto prevDynStackRevIdx = mBfIRBuilder->CreateLoad(dynStackRevIdx);
  8119. auto dynStackChanged = mBfIRBuilder->CreateCmpNE(prevDynStackRevIdx, curDynStackRevIdx);
  8120. mBfIRBuilder->CreateCondBr(dynStackChanged, resizeBB, endBB);
  8121. mBfIRBuilder->AddBlock(resizeBB);
  8122. mBfIRBuilder->SetInsertPoint(resizeBB);
  8123. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  8124. mBfIRBuilder->SetAllocaAlignment(allocaInst, align);
  8125. mBfIRBuilder->CreateStore(allocaInst, dynPtrAllocaInst);
  8126. mBfIRBuilder->CreateStore(sizeValue, dynSizeAllocaInst);
  8127. mBfIRBuilder->CreateStore(curDynStackRevIdx, dynStackRevIdx);
  8128. mBfIRBuilder->CreateBr(endBB);
  8129. mBfIRBuilder->AddBlock(endBB);
  8130. mBfIRBuilder->SetInsertPoint(endBB);
  8131. return mBfIRBuilder->CreateLoad(dynPtrAllocaInst);
  8132. };
  8133. if (isScopeAlloc)
  8134. {
  8135. if (arraySize)
  8136. {
  8137. bool isConstantArraySize = arraySize.IsConst();
  8138. if (isRawArrayAlloc)
  8139. {
  8140. BfPointerType* ptrType = CreatePointerType(type);
  8141. if ((!isDynAlloc) && (!isConstantArraySize) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  8142. {
  8143. BfIRValue sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  8144. auto loadedPtr = _CreateDynAlloc(sizeValue, type->mAlign);
  8145. InitTypeInst(BfTypedValue(loadedPtr, ptrType), scopeData, zeroMemory, sizeValue);
  8146. return mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(type)));
  8147. }
  8148. else
  8149. {
  8150. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  8151. isDynAlloc = (isDynAlloc) || (!arraySize.IsConst());
  8152. if (!isDynAlloc)
  8153. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  8154. else
  8155. {
  8156. MarkDynStack(scopeData);
  8157. SaveStackState(scopeData);
  8158. }
  8159. int typeSize = type->GetStride();
  8160. BfIRValue allocaInst;
  8161. BfIRValue result;
  8162. if ((typeInstance == NULL) || (typeInstance->mIsCRepr))
  8163. {
  8164. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type), arraySize);
  8165. result = allocaInst;
  8166. }
  8167. else
  8168. {
  8169. if (typeInstance->IsStruct())
  8170. typeSize = typeInstance->GetInstStride();
  8171. auto byteType = GetPrimitiveStructType(BfTypeCode_Int8);
  8172. sizeValue = mBfIRBuilder->CreateMul(GetConstValue(typeSize), arraySize);
  8173. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  8174. auto ptrType = CreatePointerType(typeInstance);
  8175. result = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(ptrType));
  8176. if (!isDynAlloc)
  8177. mBfIRBuilder->ClearDebugLocation(result);
  8178. }
  8179. if (!isDynAlloc)
  8180. mBfIRBuilder->ClearDebugLocation(allocaInst);
  8181. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  8182. if (!isDynAlloc)
  8183. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  8184. auto typedVal = BfTypedValue(result, type, BfTypedValueKind_Addr);
  8185. if (arraySize.IsConst())
  8186. {
  8187. auto constant = mBfIRBuilder->GetConstant(arraySize);
  8188. if (constant->mInt64 == 0)
  8189. noDtorCall = true;
  8190. }
  8191. if (!noDtorCall)
  8192. {
  8193. bool isConstSize = arraySize.IsConst();
  8194. BfIRBlock clearBlock;
  8195. BfIRBlock contBlock;
  8196. bool wantsDeinit = ((!IsOptimized()) && (!mIsComptimeModule) && (!mBfIRBuilder->mIgnoreWrites) && (!mCompiler->mIsResolveOnly));
  8197. if (wantsDeinit)
  8198. {
  8199. BfIRBlock prevBlock;
  8200. if (!isConstSize)
  8201. {
  8202. clearBlock = mBfIRBuilder->CreateBlock("clear");
  8203. contBlock = mBfIRBuilder->CreateBlock("clearCont");
  8204. prevBlock = mBfIRBuilder->GetInsertBlock();
  8205. mBfIRBuilder->AddBlock(clearBlock);
  8206. mBfIRBuilder->SetInsertPoint(clearBlock);
  8207. }
  8208. auto deferredCall = AddStackAlloc(typedVal, arraySize, NULL, scopeData, false, true);
  8209. if (!isConstSize)
  8210. {
  8211. mBfIRBuilder->CreateBr(contBlock);
  8212. mBfIRBuilder->SetInsertPoint(prevBlock);
  8213. if (deferredCall != NULL)
  8214. {
  8215. // Zero out size args
  8216. for (int i = 1; i < deferredCall->mModuleMethodInstance.mMethodInstance->GetParamCount(); i++)
  8217. {
  8218. auto scopedArg = deferredCall->mScopeArgs[i];
  8219. if (scopedArg != deferredCall->mOrigScopeArgs[i])
  8220. mBfIRBuilder->CreateStore(GetDefaultValue(deferredCall->mModuleMethodInstance.mMethodInstance->GetParamType(i)), deferredCall->mScopeArgs[i]);
  8221. }
  8222. }
  8223. mBfIRBuilder->CreateCondBr(mBfIRBuilder->CreateCmpNE(arraySize, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0)), clearBlock, contBlock);
  8224. mBfIRBuilder->AddBlock(contBlock);
  8225. mBfIRBuilder->SetInsertPoint(contBlock);
  8226. }
  8227. }
  8228. }
  8229. return result;
  8230. }
  8231. }
  8232. else
  8233. {
  8234. if ((!isDynAlloc) && (!arraySize.IsConst()) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  8235. {
  8236. // Generate and check new size
  8237. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  8238. auto firstElementField = &arrayType->mFieldInstances.back();
  8239. int arrayClassSize = firstElementField->mDataOffset;
  8240. sizeValue = GetConstValue(arrayClassSize);
  8241. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  8242. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  8243. auto loadedPtr = _CreateDynAlloc(sizeValue, arrayType->mAlign);
  8244. auto typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->MapType(arrayType)), arrayType);
  8245. if (!noDtorCall)
  8246. AddStackAlloc(typedVal, BfIRValue(), NULL, scopeData, false, true);
  8247. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  8248. return typedVal.mValue;
  8249. }
  8250. else
  8251. {
  8252. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  8253. auto firstElementField = &arrayType->mFieldInstances.back();
  8254. if (!type->IsValuelessType())
  8255. {
  8256. int arrayClassSize = firstElementField->mDataOffset;
  8257. sizeValue = GetConstValue(arrayClassSize);
  8258. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  8259. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  8260. }
  8261. else
  8262. sizeValue = GetConstValue(arrayType->mInstSize);
  8263. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  8264. isDynAlloc = (isDynAlloc) || (!sizeValue.IsConst());
  8265. if (!isDynAlloc)
  8266. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  8267. else
  8268. {
  8269. MarkDynStack(scopeData);
  8270. SaveStackState(scopeData);
  8271. }
  8272. BfType* byteType = GetPrimitiveType(BfTypeCode_Int8);
  8273. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  8274. if (!isDynAlloc)
  8275. mBfIRBuilder->ClearDebugLocation(allocaInst);
  8276. auto allocaBlock = mBfIRBuilder->GetInsertBlock();
  8277. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  8278. BfTypedValue typedVal;
  8279. if (!isDynAlloc)
  8280. {
  8281. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  8282. typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(arrayType)), arrayType);
  8283. mBfIRBuilder->ClearDebugLocation_Last();
  8284. mBfIRBuilder->SetInsertPoint(prevBlock);
  8285. allocaBlock = mCurMethodState->mIRInitBlock;
  8286. }
  8287. else
  8288. typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(arrayType)), arrayType);
  8289. if (!noDtorCall)
  8290. AddStackAlloc(typedVal, BfIRValue(), NULL, scopeData, false, true, allocaBlock);
  8291. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  8292. return typedVal.mValue;
  8293. }
  8294. }
  8295. }
  8296. else if (appendSizeValue)
  8297. {
  8298. // It may seem that we should check IsLooped against only the requested scope, BUT- if later on we perform
  8299. // a scoped alloc that crosses our boundary then we won't be able to reclaim the stack space, so we always
  8300. // use the "dynSize" version conservatively
  8301. if ((!isDynAlloc) && (!appendSizeValue.IsConst()) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  8302. {
  8303. // Generate and check new size
  8304. sizeValue = GetConstValue(typeInstance->mInstSize);
  8305. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  8306. auto loadedPtr = _CreateDynAlloc(sizeValue, typeInstance->mAlign);
  8307. auto typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->MapTypeInstPtr(typeInstance)), typeInstance);
  8308. if (!noDtorCall)
  8309. AddStackAlloc(typedVal, arraySize, NULL, scopeData, mCurMethodState->mInConditionalBlock, true);
  8310. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  8311. return typedVal.mValue;
  8312. }
  8313. else // stack alloc, unlooped, with append
  8314. {
  8315. sizeValue = GetConstValue(typeInstance->mInstSize);
  8316. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  8317. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  8318. bool wasDynAlloc = isDynAlloc;
  8319. isDynAlloc = (isDynAlloc) || (!sizeValue.IsConst());
  8320. if (!isDynAlloc)
  8321. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  8322. else
  8323. {
  8324. MarkDynStack(scopeData);
  8325. SaveStackState(scopeData);
  8326. }
  8327. auto sbyteType = GetPrimitiveType(BfTypeCode_Int8);
  8328. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(sbyteType), sizeValue);
  8329. if (!isDynAlloc)
  8330. {
  8331. mBfIRBuilder->ClearDebugLocation(allocaInst);
  8332. }
  8333. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  8334. bool mayBeLarge = false;
  8335. if (sizeValue.IsConst())
  8336. {
  8337. auto constantInt = mBfIRBuilder->GetConstant(sizeValue);
  8338. if (constantInt->mInt64 >= 4096)
  8339. mayBeLarge = true;
  8340. }
  8341. else
  8342. mayBeLarge = true;
  8343. if (((type->IsObject() && (!mayBeLarge))) ||
  8344. // If we create a memset that can fill in backwards (or at least 4k chunked backward) then we can remove the '!mayBeLarge' cond
  8345. ((zeroMemory) && (!mayBeLarge)))
  8346. {
  8347. mBfIRBuilder->SetAllocaNoChkStkHint(allocaInst);
  8348. }
  8349. BfIRValue castedVal;
  8350. if (!isDynAlloc)
  8351. {
  8352. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  8353. castedVal = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapTypeInstPtr(typeInstance));
  8354. mBfIRBuilder->ClearDebugLocation(castedVal);
  8355. mBfIRBuilder->SetInsertPoint(prevBlock);
  8356. if (WantsLifetimes())
  8357. {
  8358. mBfIRBuilder->CreateLifetimeStart(allocaInst);
  8359. scopeData->mDeferredLifetimeEnds.push_back(allocaInst);
  8360. }
  8361. }
  8362. else
  8363. {
  8364. castedVal = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapTypeInstPtr(typeInstance));
  8365. }
  8366. auto typedVal = BfTypedValue(castedVal, typeInstance);
  8367. if (!noDtorCall)
  8368. {
  8369. bool doCondAlloca = false;
  8370. if (!IsTargetingBeefBackend())
  8371. doCondAlloca = !wasDynAlloc && isDynAlloc && mCurMethodState->mInConditionalBlock;
  8372. AddStackAlloc(typedVal, arraySize, NULL, scopeData, doCondAlloca, true);
  8373. }
  8374. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  8375. return typedVal.mValue;
  8376. }
  8377. }
  8378. else // "Normal" stack alloc
  8379. {
  8380. BF_ASSERT(!sizeValue);
  8381. //TODO: If sizeValue is a constant then do this in the head IR builder
  8382. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  8383. if (!isLoopedAlloc)
  8384. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  8385. else
  8386. {
  8387. MarkDynStack(scopeData);
  8388. SaveStackState(scopeData);
  8389. }
  8390. auto allocaInst = mBfIRBuilder->CreateAlloca(allocType);
  8391. if (!isLoopedAlloc)
  8392. mBfIRBuilder->ClearDebugLocation(allocaInst);
  8393. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  8394. bool mayBeLarge = allocSize >= 4096;
  8395. if (((typeInstance != NULL) && (typeInstance->IsObject()) && (!mayBeLarge)) ||
  8396. // If we create a memset that can fill in backwards (or at least 4k chunked backward) then we can remove the '!mayBeLarge' cond
  8397. ((zeroMemory) && (!mayBeLarge)))
  8398. {
  8399. // With an object, we know we will at least set the vdata pointer which will probe the start of the new address,
  8400. // and memset is always safe
  8401. mBfIRBuilder->SetAllocaNoChkStkHint(allocaInst);
  8402. }
  8403. auto typedVal = BfTypedValue(allocaInst, type);
  8404. if (!isLoopedAlloc)
  8405. {
  8406. mBfIRBuilder->ClearDebugLocation(allocaInst);
  8407. mBfIRBuilder->SetInsertPoint(prevBlock);
  8408. if (WantsLifetimes())
  8409. {
  8410. mBfIRBuilder->CreateLifetimeStart(allocaInst);
  8411. scopeData->mDeferredLifetimeEnds.push_back(allocaInst);
  8412. }
  8413. }
  8414. if (!noDtorCall)
  8415. AddStackAlloc(typedVal, BfIRValue(), NULL, scopeData, false, true);
  8416. if (typeInstance != NULL)
  8417. {
  8418. InitTypeInst(typedVal, scopeData, zeroMemory, GetConstValue(typeInstance->mInstSize));
  8419. }
  8420. else
  8421. {
  8422. mBfIRBuilder->CreateMemSet(allocaInst, GetConstValue8(0), GetConstValue(allocSize), allocAlign);
  8423. }
  8424. return allocaInst;
  8425. }
  8426. }
  8427. else if (arraySize)
  8428. {
  8429. if (isRawArrayAlloc)
  8430. {
  8431. sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  8432. return AllocBytes(allocTarget.mRefNode, allocTarget, type, sizeValue, GetConstValue(allocAlign), allocFlags);
  8433. }
  8434. else
  8435. {
  8436. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  8437. typeInstance = arrayType;
  8438. BfIRValue arraySizeMinusOne = mBfIRBuilder->CreateSub(arraySize, GetConstValue(1));
  8439. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySizeMinusOne);
  8440. appendSizeValue = elementDataSize;
  8441. if (!type->IsSizeAligned())
  8442. {
  8443. appendSizeValue = mBfIRBuilder->CreateAdd(appendSizeValue, GetConstValue(type->GetStride() - type->mSize));
  8444. }
  8445. }
  8446. }
  8447. if ((typeInstance != NULL) && (typeInstance->IsObject()))
  8448. {
  8449. auto vDataRef = GetClassVDataPtr(typeInstance);
  8450. BfIRValue result;
  8451. bool isResultInitialized = false;
  8452. int stackCount = mCompiler->mOptions.mAllocStackCount;
  8453. if (typeInstance->mTypeOptionsIdx != -1)
  8454. {
  8455. auto typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  8456. stackCount = BfTypeOptions::Apply(stackCount, typeOptions->mAllocStackTraceDepth);
  8457. }
  8458. if (mIsComptimeModule)
  8459. stackCount = 0;
  8460. if (!sizeValue)
  8461. sizeValue = GetConstValue(typeInstance->mInstSize);
  8462. if (appendSizeValue)
  8463. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  8464. BfIRValue origSizeValue = sizeValue;
  8465. bool isAllocEx = hasCustomAllocator && (stackCount > 1);
  8466. if (isAllocEx)
  8467. {
  8468. auto prepareStackTraceMethod = GetInternalMethod("Dbg_PrepareStackTrace");
  8469. if (prepareStackTraceMethod)
  8470. {
  8471. SizedArray<BfIRValue, 2> irArgs;
  8472. irArgs.Add(sizeValue);
  8473. irArgs.Add(GetConstValue(stackCount));
  8474. auto addlBytes = mBfIRBuilder->CreateCall(prepareStackTraceMethod.mFunc, irArgs);
  8475. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, addlBytes);
  8476. }
  8477. }
  8478. if (allocTarget.mCustomAllocator)
  8479. {
  8480. auto customAlloc = allocTarget.mCustomAllocator.mType->ToTypeInstance();
  8481. // Use AllocObject if we have it, otherwise we just use AllocBytes further down
  8482. if ((customAlloc != NULL) && (GetRawMethodByName(customAlloc, "AllocObject", -1, true, true) != NULL))
  8483. {
  8484. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  8485. mBfIRBuilder->PopulateType(classVDataType);
  8486. auto typeInstType = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef)->ToTypeInstance();
  8487. mBfIRBuilder->PopulateType(typeInstType);
  8488. auto typePtrPtr = mBfIRBuilder->CreateInBoundsGEP(vDataRef, 0, 1); // mType
  8489. auto typePtr = mBfIRBuilder->CreateLoad(typePtrPtr);
  8490. auto typeInstPtr = mBfIRBuilder->CreateBitCast(typePtr, mBfIRBuilder->MapTypeInstPtr(typeInstType));
  8491. BfTypedValueExpression typedValueExpr;
  8492. typedValueExpr.Init(BfTypedValue(typeInstPtr, typeInstType));
  8493. typedValueExpr.mRefNode = allocTarget.mRefNode;
  8494. BfExprEvaluator exprEvaluator(this);
  8495. SizedArray<BfExpression*, 2> argExprs;
  8496. argExprs.push_back(&typedValueExpr);
  8497. BfTypedValueExpression sizeValueExpr;
  8498. sizeValueExpr.Init(BfTypedValue(sizeValue, GetPrimitiveType(BfTypeCode_IntPtr)));
  8499. sizeValueExpr.mRefNode = allocTarget.mRefNode;
  8500. argExprs.push_back(&sizeValueExpr);
  8501. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  8502. BfResolvedArgs argValues(&sizedArgExprs);
  8503. exprEvaluator.ResolveArgValues(argValues);
  8504. exprEvaluator.mNoBind = true;
  8505. BfTypedValue allocResult = exprEvaluator.MatchMethod(allocTarget.mRefNode, NULL, allocTarget.mCustomAllocator, false, false, "AllocObject", argValues, BfMethodGenericArguments());
  8506. if (allocResult)
  8507. {
  8508. if ((allocResult.mType->IsVoidPtr()) || (allocResult.mType == mContext->mBfObjectType))
  8509. result = mBfIRBuilder->CreateBitCast(allocResult.mValue, mBfIRBuilder->MapType(typeInstance));
  8510. else
  8511. result = CastToValue(allocTarget.mRefNode, allocResult, typeInstance, BfCastFlags_Explicit);
  8512. isResultInitialized = true;
  8513. }
  8514. }
  8515. }
  8516. bool wasAllocated = false;
  8517. if (!result)
  8518. {
  8519. if (hasCustomAllocator)
  8520. result = AllocBytes(allocTarget.mRefNode, allocTarget, typeInstance, sizeValue, GetConstValue(typeInstance->mInstAlign), (BfAllocFlags)(BfAllocFlags_ZeroMemory | BfAllocFlags_NoDefaultToMalloc));
  8521. else if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mCompiler->mOptions.mDebugAlloc) && (!mIsComptimeModule))
  8522. {
  8523. SizedArray<BfIRValue, 4> llvmArgs;
  8524. llvmArgs.push_back(sizeValue);
  8525. auto irFunc = GetBuiltInFunc(BfBuiltInFuncType_Malloc);
  8526. result = mBfIRBuilder->CreateCall(irFunc, llvmArgs);
  8527. result = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapTypeInstPtr(typeInstance));
  8528. wasAllocated = true;
  8529. }
  8530. }
  8531. if (result)
  8532. {
  8533. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  8534. {
  8535. auto objectPtr = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapTypeInstPtr(mContext->mBfObjectType));
  8536. SizedArray<BfIRValue, 4> llvmArgs;
  8537. llvmArgs.push_back(objectPtr);
  8538. llvmArgs.push_back(origSizeValue);
  8539. llvmArgs.push_back(vDataRef);
  8540. auto objectCreatedMethod = GetInternalMethod(isAllocEx ?
  8541. (isResultInitialized ? "Dbg_ObjectCreatedEx" : "Dbg_ObjectAllocatedEx") :
  8542. (isResultInitialized ? "Dbg_ObjectCreated" : "Dbg_ObjectAllocated"));
  8543. mBfIRBuilder->CreateCall(objectCreatedMethod.mFunc, llvmArgs);
  8544. if (wasAllocated)
  8545. {
  8546. auto byteType = GetPrimitiveType(BfTypeCode_UInt8);
  8547. auto bytePtrType = CreatePointerType(byteType);
  8548. auto flagsPtr = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapType(bytePtrType));
  8549. auto flagsVal = mBfIRBuilder->CreateLoad(flagsPtr);
  8550. auto modifiedFlagsVal = mBfIRBuilder->CreateOr(flagsVal, mBfIRBuilder->CreateConst(BfTypeCode_UInt8, /*BF_OBJECTFLAG_ALLOCATED*/4));
  8551. mBfIRBuilder->CreateStore(modifiedFlagsVal, flagsPtr);
  8552. }
  8553. }
  8554. else
  8555. {
  8556. auto ptrType = mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr);
  8557. auto vDataPtr = mBfIRBuilder->CreateBitCast(vDataRef, ptrType);
  8558. auto vDataMemberPtr = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->GetPointerTo(ptrType));
  8559. mBfIRBuilder->CreateStore(vDataPtr, vDataMemberPtr);
  8560. }
  8561. }
  8562. else
  8563. {
  8564. if ((mBfIRBuilder->mIgnoreWrites) ||
  8565. ((mCompiler->mIsResolveOnly) && (!mIsComptimeModule)))
  8566. return GetDefaultValue(typeInstance);
  8567. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  8568. auto vData = mBfIRBuilder->CreateBitCast(vDataRef, mBfIRBuilder->MapTypeInstPtr(classVDataType->ToTypeInstance()));
  8569. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  8570. {
  8571. SizedArray<BfIRValue, 4> llvmArgs;
  8572. llvmArgs.push_back(vData);
  8573. llvmArgs.push_back(sizeValue);
  8574. llvmArgs.push_back(GetConstValue(typeInstance->mAlign));
  8575. llvmArgs.push_back(GetConstValue(stackCount));
  8576. auto moduleMethodInstance = GetInternalMethod("Dbg_ObjectAlloc", 4);
  8577. BfIRValue objectVal = mBfIRBuilder->CreateCall(moduleMethodInstance.mFunc, llvmArgs);
  8578. result = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(typeInstance));
  8579. }
  8580. else
  8581. {
  8582. SizedArray<BfIRValue, 4> llvmArgs;
  8583. llvmArgs.push_back(sizeValue);
  8584. BfIRFunction irFunc;
  8585. if ((mCompiler->mOptions.mDebugAlloc) && (!mIsComptimeModule))
  8586. {
  8587. auto moduleMethodInstance = GetInternalMethod("Dbg_RawObjectAlloc", 1);
  8588. irFunc = moduleMethodInstance.mFunc;
  8589. }
  8590. if (!irFunc)
  8591. irFunc = GetBuiltInFunc(BfBuiltInFuncType_Malloc);
  8592. BfIRValue objectVal = mBfIRBuilder->CreateCall(irFunc, llvmArgs);
  8593. auto objResult = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(mContext->mBfObjectType, BfIRPopulateType_Full));
  8594. auto vdataPtr = mBfIRBuilder->CreateInBoundsGEP(objResult, 0, 0);
  8595. if (mIsComptimeModule)
  8596. {
  8597. vdataPtr = mBfIRBuilder->CreateBitCast(vdataPtr, mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapTypeInstPtr(classVDataType->ToTypeInstance())));
  8598. }
  8599. mBfIRBuilder->CreateStore(vData, vdataPtr);
  8600. result = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(typeInstance));
  8601. }
  8602. }
  8603. if ((zeroMemory) && (arraySize))
  8604. {
  8605. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  8606. typeInstance = arrayType;
  8607. auto firstElementField = &arrayType->mFieldInstances.back();
  8608. int arrayClassSize = firstElementField->mDataOffset;
  8609. BfIRValue elementDataSize;
  8610. bool skipZero = false;
  8611. if (arraySize.IsConst())
  8612. {
  8613. BfIRValue arraySizeMinusOne = mBfIRBuilder->CreateSub(arraySize, GetConstValue(1));
  8614. elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySizeMinusOne);
  8615. elementDataSize = mBfIRBuilder->CreateAdd(elementDataSize, GetConstValue(type->mSize));
  8616. auto constVal = mBfIRBuilder->GetConstant(elementDataSize);
  8617. if (constVal->mInt64 <= 0)
  8618. skipZero = true;
  8619. }
  8620. else
  8621. {
  8622. // For non const, don't use an unpadded last element - saves us checking against negative numbers going into memset for the zero-length case
  8623. elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  8624. }
  8625. if (!skipZero)
  8626. {
  8627. auto i8Type = GetPrimitiveType(BfTypeCode_Int8);
  8628. auto ptrType = CreatePointerType(i8Type);
  8629. auto ptrVal = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapType(ptrType));
  8630. ptrVal = mBfIRBuilder->CreateInBoundsGEP(ptrVal, arrayClassSize);
  8631. mBfIRBuilder->CreateMemSet(ptrVal, GetConstValue8(0), elementDataSize, type->mAlign);
  8632. appendSizeValue = elementDataSize;
  8633. }
  8634. }
  8635. return result;
  8636. }
  8637. else
  8638. {
  8639. if (!sizeValue)
  8640. sizeValue = GetConstValue(allocSize);
  8641. return AllocBytes(allocTarget.mRefNode, allocTarget, type, sizeValue, GetConstValue(allocAlign), zeroMemory ? BfAllocFlags_ZeroMemory : BfAllocFlags_None);
  8642. }
  8643. }
  8644. void BfModule::ValidateAllocation(BfType* type, BfAstNode* refNode)
  8645. {
  8646. if ((type == NULL) || (refNode == NULL))
  8647. return;
  8648. auto typeInstance = type->ToTypeInstance();
  8649. if ((typeInstance != NULL) && (typeInstance->mTypeDef->mIsOpaque))
  8650. Fail(StrFormat("Unable to allocate opaque type '%s'", TypeToString(type).c_str()), refNode);
  8651. }
  8652. void BfModule::EmitAlign(BfIRValue& appendCurIdx, int align)
  8653. {
  8654. appendCurIdx = mBfIRBuilder->CreateAdd(appendCurIdx, GetConstValue(align - 1));
  8655. appendCurIdx = mBfIRBuilder->CreateAnd(appendCurIdx, GetConstValue(~(align - 1)));
  8656. }
  8657. void BfModule::EmitAppendAlign(int align, int sizeMultiple)
  8658. {
  8659. if (sizeMultiple == 0)
  8660. sizeMultiple = align;
  8661. if ((mCurMethodState->mCurAppendAlign != 0) && (mCurMethodState->mCurAppendAlign % align != 0))
  8662. {
  8663. if (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Ctor)
  8664. {
  8665. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  8666. BF_ASSERT(localVar->mName == "appendIdx");
  8667. auto appendIdxVal = BfTypedValue(localVar->mValue, localVar->mResolvedType, true);
  8668. BfIRValue appendCurIdx = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  8669. if (align > 1)
  8670. {
  8671. appendCurIdx = mBfIRBuilder->CreateAdd(appendCurIdx, GetConstValue(align - 1));
  8672. appendCurIdx = mBfIRBuilder->CreateAnd(appendCurIdx, GetConstValue(~(align - 1)));
  8673. }
  8674. mBfIRBuilder->CreateStore(appendCurIdx, appendIdxVal.mValue);
  8675. }
  8676. else
  8677. {
  8678. BF_ASSERT(mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend);
  8679. BfIRValue appendCurIdxPtr = mCurMethodState->mRetVal.mValue;
  8680. BfIRValue appendCurIdx = mBfIRBuilder->CreateLoad(appendCurIdxPtr);
  8681. appendCurIdx = mBfIRBuilder->CreateAdd(appendCurIdx, GetConstValue(align - 1));
  8682. appendCurIdx = mBfIRBuilder->CreateAnd(appendCurIdx, GetConstValue(~(align - 1)));
  8683. mBfIRBuilder->CreateStore(appendCurIdx, appendCurIdxPtr);
  8684. }
  8685. }
  8686. if (mCurMethodState->mCurAppendAlign == 0)
  8687. mCurMethodState->mCurAppendAlign = sizeMultiple;
  8688. else
  8689. {
  8690. if (sizeMultiple % align == 0)
  8691. mCurMethodState->mCurAppendAlign = align;
  8692. else
  8693. mCurMethodState->mCurAppendAlign = sizeMultiple % align;
  8694. }
  8695. }
  8696. BfIRValue BfModule::AppendAllocFromType(BfType* type, BfIRValue appendSizeValue, int appendAllocAlign, BfIRValue arraySize, int arrayDim, bool isRawArrayAlloc, bool zeroMemory)
  8697. {
  8698. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  8699. BF_ASSERT(localVar->mName == "appendIdx");
  8700. BfTypedValue appendIdxVal(localVar->mValue, localVar->mResolvedType, true);
  8701. BfIRValue retValue;
  8702. BfTypeInstance* retTypeInstance = NULL;
  8703. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  8704. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  8705. if (arraySize)
  8706. {
  8707. if (isRawArrayAlloc)
  8708. {
  8709. EmitAppendAlign(type->mAlign);
  8710. BfPointerType* ptrType = CreatePointerType(type);
  8711. BfIRValue sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->mSize), arraySize);
  8712. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  8713. if (mSystem->mPtrSize != 4)
  8714. sizeValue = mBfIRBuilder->CreateNumericCast(sizeValue, true, (intPtrType->mSize == 4) ? BfTypeCode_Int32 : BfTypeCode_Int64);
  8715. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  8716. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  8717. if (zeroMemory)
  8718. {
  8719. auto ptr = mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(voidPtrType));
  8720. mBfIRBuilder->CreateMemSet(ptr, GetConstValue8(0), sizeValue, type->mAlign);
  8721. }
  8722. return mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(ptrType));
  8723. }
  8724. else
  8725. {
  8726. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  8727. EmitAppendAlign(arrayType->mAlign, type->mSize);
  8728. auto firstElementField = &arrayType->mFieldInstances.back();
  8729. int arrayClassSize = arrayType->mInstSize - firstElementField->mDataSize;
  8730. BfIRValue sizeValue = GetConstValue(arrayClassSize);
  8731. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->mSize), arraySize);
  8732. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  8733. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  8734. if (mSystem->mPtrSize != 4)
  8735. sizeValue = mBfIRBuilder->CreateNumericCast(sizeValue, true, (intPtrType->mSize == 4) ? BfTypeCode_Int32 : BfTypeCode_Int64);
  8736. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  8737. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  8738. if (zeroMemory)
  8739. {
  8740. // Only zero out the actual elements
  8741. int dataOffset = arrayType->mFieldInstances.back().mDataOffset;
  8742. auto newOffset = mBfIRBuilder->CreateAdd(curIdxVal, GetConstValue(dataOffset));
  8743. auto newSize = mBfIRBuilder->CreateSub(sizeValue, GetConstValue(dataOffset));
  8744. auto ptr = mBfIRBuilder->CreateIntToPtr(newOffset, mBfIRBuilder->MapType(voidPtrType));
  8745. mBfIRBuilder->CreateMemSet(ptr, GetConstValue8(0), newSize, type->mAlign);
  8746. }
  8747. retTypeInstance = arrayType;
  8748. retValue = mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(arrayType));
  8749. }
  8750. }
  8751. else
  8752. {
  8753. auto typeInst = type->ToTypeInstance();
  8754. BfIRValue sizeValue;
  8755. BfIRType toType;
  8756. if (typeInst != NULL)
  8757. {
  8758. EmitAppendAlign(typeInst->mInstAlign, typeInst->mInstSize);
  8759. sizeValue = GetConstValue(typeInst->mInstSize);
  8760. toType = mBfIRBuilder->MapTypeInstPtr(typeInst);
  8761. }
  8762. else
  8763. {
  8764. EmitAppendAlign(type->mAlign, type->mSize);
  8765. sizeValue = GetConstValue(type->mSize);
  8766. auto toPtrType = CreatePointerType(type);
  8767. toType = mBfIRBuilder->MapType(toPtrType);
  8768. }
  8769. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  8770. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  8771. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  8772. retTypeInstance = typeInst;
  8773. retValue = mBfIRBuilder->CreateIntToPtr(curIdxVal, toType);
  8774. }
  8775. if ((retTypeInstance != NULL) && (retTypeInstance->IsObject()))
  8776. {
  8777. mBfIRBuilder->PopulateType(retTypeInstance);
  8778. auto int8Type = mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8);
  8779. auto ptrType = mBfIRBuilder->GetPointerTo(int8Type);
  8780. auto ptrPtrType = mBfIRBuilder->GetPointerTo(ptrType);
  8781. auto curThis = GetThis();
  8782. BfIRValue newFlags;
  8783. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  8784. {
  8785. auto thisFlagsPtr = mBfIRBuilder->CreateBitCast(curThis.mValue, ptrType);
  8786. auto thisFlags = mBfIRBuilder->CreateLoad(thisFlagsPtr);
  8787. auto maskedThisFlags = mBfIRBuilder->CreateAnd(thisFlags, GetConstValue8(BfObjectFlag_StackAlloc)); // Take 'stack' flag from 'this'
  8788. newFlags = mBfIRBuilder->CreateOr(maskedThisFlags, GetConstValue8(BfObjectFlag_AppendAlloc));
  8789. }
  8790. auto vObjectAddr = mBfIRBuilder->CreateInBoundsGEP(retValue, 0, 0);
  8791. auto vDataRef = CreateClassVDataGlobal(retTypeInstance);
  8792. auto destAddr = mBfIRBuilder->CreateBitCast(vObjectAddr, ptrPtrType);
  8793. auto srcVal = mBfIRBuilder->CreateBitCast(vDataRef, ptrType);
  8794. mBfIRBuilder->CreateStore(srcVal, destAddr);
  8795. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  8796. {
  8797. auto flagsPtr = mBfIRBuilder->CreateBitCast(destAddr, ptrType);
  8798. mBfIRBuilder->CreateStore(newFlags, flagsPtr);
  8799. }
  8800. }
  8801. if (appendSizeValue)
  8802. {
  8803. EmitAppendAlign(appendAllocAlign);
  8804. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  8805. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, appendSizeValue);
  8806. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  8807. }
  8808. return retValue;
  8809. }
  8810. bool BfModule::IsOptimized()
  8811. {
  8812. if (mProject == NULL)
  8813. return false;
  8814. if (mIsComptimeModule)
  8815. return false;
  8816. int optLevel = GetModuleOptions().mOptLevel;
  8817. return (optLevel >= BfOptLevel_O1) && (optLevel <= BfOptLevel_O3);
  8818. }
  8819. bool BfModule::IsTargetingBeefBackend()
  8820. {
  8821. if (mProject == NULL)
  8822. return true;
  8823. return GetModuleOptions().mOptLevel == BfOptLevel_OgPlus;
  8824. }
  8825. bool BfModule::WantsLifetimes()
  8826. {
  8827. if (mBfIRBuilder->mIgnoreWrites)
  8828. return false;
  8829. if ((mIsComptimeModule) && (mBfIRBuilder->HasDebugLocation()))
  8830. return true;
  8831. else if (mProject == NULL)
  8832. return false;
  8833. return GetModuleOptions().mOptLevel == BfOptLevel_OgPlus;
  8834. }
  8835. bool BfModule::HasCompiledOutput()
  8836. {
  8837. return (!mSystem->mIsResolveOnly) && (mGeneratesCode) && (!mIsComptimeModule);
  8838. }
  8839. bool BfModule::HasExecutedOutput()
  8840. {
  8841. return ((!mSystem->mIsResolveOnly) && (mGeneratesCode)) || (mIsComptimeModule);
  8842. }
  8843. // We will skip the object access check for any occurrences of this value
  8844. void BfModule::SkipObjectAccessCheck(BfTypedValue typedVal)
  8845. {
  8846. if ((mBfIRBuilder->mIgnoreWrites) || (!typedVal.mType->IsObjectOrInterface()) || (mCurMethodState == NULL) || (mCurMethodState->mIgnoreObjectAccessCheck))
  8847. return;
  8848. if ((!mCompiler->mOptions.mObjectHasDebugFlags) || (mIsComptimeModule))
  8849. return;
  8850. if ((typedVal.mValue.mFlags & BfIRValueFlags_Value) == 0)
  8851. return;
  8852. mCurMethodState->mSkipObjectAccessChecks.Add(typedVal.mValue.mId);
  8853. }
  8854. void BfModule::EmitObjectAccessCheck(BfTypedValue typedVal)
  8855. {
  8856. if ((mBfIRBuilder->mIgnoreWrites) || (!typedVal.mType->IsObjectOrInterface()) || (mCurMethodState == NULL) || (mCurMethodState->mIgnoreObjectAccessCheck))
  8857. return;
  8858. if ((!mCompiler->mOptions.mObjectHasDebugFlags) || (mIsComptimeModule))
  8859. return;
  8860. if (typedVal.mValue.IsConst())
  8861. {
  8862. int stringIdx = GetStringPoolIdx(typedVal.mValue, mBfIRBuilder);
  8863. if (stringIdx != -1)
  8864. return;
  8865. auto constant = mBfIRBuilder->GetConstant(typedVal.mValue);
  8866. if (constant->mTypeCode == BfTypeCode_NullPtr)
  8867. return;
  8868. if (constant->mConstType == BfConstType_BitCastNull)
  8869. return;
  8870. }
  8871. bool emitObjectAccessCheck = mCompiler->mOptions.mEmitObjectAccessCheck;
  8872. auto typeOptions = GetTypeOptions();
  8873. if (typeOptions != NULL)
  8874. emitObjectAccessCheck = typeOptions->Apply(emitObjectAccessCheck, BfOptionFlags_EmitObjectAccessCheck);
  8875. if (!emitObjectAccessCheck)
  8876. return;
  8877. if ((typedVal.mValue.mFlags & BfIRValueFlags_Value) != 0)
  8878. {
  8879. if (mCurMethodState->mSkipObjectAccessChecks.Contains(typedVal.mValue.mId))
  8880. return;
  8881. }
  8882. if (typedVal.IsAddr())
  8883. typedVal = LoadValue(typedVal);
  8884. mBfIRBuilder->CreateObjectAccessCheck(typedVal.mValue, !IsOptimized());
  8885. }
  8886. void BfModule::EmitEnsureInstructionAt()
  8887. {
  8888. if (mBfIRBuilder->mIgnoreWrites)
  8889. return;
  8890. if (mIsComptimeModule)
  8891. {
  8892. // Always add
  8893. }
  8894. else if ((mProject == NULL) || (!mHasFullDebugInfo) || (IsOptimized()) || (mCompiler->mOptions.mOmitDebugHelpers))
  8895. return;
  8896. mBfIRBuilder->CreateEnsureInstructionAt();
  8897. }
  8898. void BfModule::EmitDynamicCastCheck(const BfTypedValue& targetValue, BfType* targetType, BfIRBlock trueBlock, BfIRBlock falseBlock, bool nullSucceeds)
  8899. {
  8900. if (mBfIRBuilder->mIgnoreWrites)
  8901. return; // Nothing needed here
  8902. auto irb = mBfIRBuilder;
  8903. auto checkBB = irb->CreateBlock("as.check");
  8904. auto isNull = irb->CreateIsNull(targetValue.mValue);
  8905. mBfIRBuilder->CreateCondBr(isNull, nullSucceeds ? trueBlock : falseBlock, checkBB);
  8906. if (mIsComptimeModule)
  8907. {
  8908. AddBasicBlock(checkBB);
  8909. auto callResult = mBfIRBuilder->Comptime_DynamicCastCheck(targetValue.mValue, targetType->mTypeId, mBfIRBuilder->MapType(mContext->mBfObjectType));
  8910. auto cmpResult = mBfIRBuilder->CreateCmpNE(callResult, GetDefaultValue(mContext->mBfObjectType));
  8911. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  8912. return;
  8913. }
  8914. auto intType = GetPrimitiveType(BfTypeCode_IntPtr);
  8915. auto intPtrType = CreatePointerType(intType);
  8916. auto intPtrPtrType = CreatePointerType(intPtrType);
  8917. auto int32Type = GetPrimitiveType(BfTypeCode_Int32);
  8918. auto int32PtrType = CreatePointerType(int32Type);
  8919. auto typeTypeInstance = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef)->ToTypeInstance();
  8920. if (mCompiler->mOptions.mAllowHotSwapping)
  8921. {
  8922. BfExprEvaluator exprEvaluator(this);
  8923. AddBasicBlock(checkBB);
  8924. auto objectParam = mBfIRBuilder->CreateBitCast(targetValue.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType));
  8925. auto moduleMethodInstance = GetMethodByName(mContext->mBfObjectType, targetType->IsInterface() ? "DynamicCastToInterface" : "DynamicCastToTypeId");
  8926. SizedArray<BfIRValue, 4> irArgs;
  8927. irArgs.push_back(objectParam);
  8928. irArgs.push_back(GetConstValue32(targetType->mTypeId));
  8929. auto callResult = exprEvaluator.CreateCall(NULL, moduleMethodInstance.mMethodInstance, moduleMethodInstance.mFunc, false, irArgs);
  8930. auto cmpResult = mBfIRBuilder->CreateCmpNE(callResult.mValue, GetDefaultValue(callResult.mType));
  8931. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  8932. }
  8933. else
  8934. {
  8935. AddBasicBlock(checkBB);
  8936. BfIRValue vDataPtr = irb->CreateBitCast(targetValue.mValue, irb->MapType(intPtrType));
  8937. vDataPtr = irb->CreateLoad(vDataPtr);
  8938. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  8939. vDataPtr = irb->CreateAnd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, (uint64)~0xFFULL));
  8940. if (targetType->IsInterface())
  8941. {
  8942. auto targetTypeInst = targetType->ToTypeInstance();
  8943. AddDependency(targetType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  8944. // Skip past mType, but since a 'GetDynCastVDataCount()' data is included in the sSlotOfs, we need to remove that
  8945. //int inheritanceIdOfs = mSystem->mPtrSize - (mCompiler->GetDynCastVDataCount())*4;
  8946. //vDataPtr = irb->CreateAdd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, inheritanceIdOfs));
  8947. vDataPtr = irb->CreateAdd(vDataPtr, irb->GetConfigConst(BfIRConfigConst_DynSlotOfs, BfTypeCode_IntPtr));
  8948. BfIRValue slotOfs = GetInterfaceSlotNum(targetType->ToTypeInstance());
  8949. BfIRValue slotByteOfs = irb->CreateMul(slotOfs, irb->CreateConst(BfTypeCode_Int32, 4));
  8950. slotByteOfs = irb->CreateNumericCast(slotByteOfs, false, BfTypeCode_IntPtr);
  8951. vDataPtr = irb->CreateAdd(vDataPtr, slotByteOfs);
  8952. vDataPtr = irb->CreateIntToPtr(vDataPtr, irb->MapType(int32PtrType));
  8953. BfIRValue typeId = irb->CreateLoad(vDataPtr);
  8954. BfIRValue cmpResult = irb->CreateCmpEQ(typeId, irb->CreateConst(BfTypeCode_Int32, targetType->mTypeId));
  8955. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  8956. }
  8957. else
  8958. {
  8959. if (!targetType->IsTypeInstance())
  8960. targetType = GetWrappedStructType(targetType);
  8961. AddDependency(targetType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  8962. int inheritanceIdOfs = mSystem->mPtrSize;
  8963. vDataPtr = irb->CreateAdd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, inheritanceIdOfs));
  8964. vDataPtr = irb->CreateIntToPtr(vDataPtr, irb->MapType(int32PtrType));
  8965. BfIRValue objInheritanceId = irb->CreateLoad(vDataPtr);
  8966. BfIRValue typeDataRef = CreateTypeDataRef(targetType);
  8967. BfIRValue typeInstDataRef = irb->CreateBitCast(typeDataRef, irb->MapType(typeTypeInstance, BfIRPopulateType_Full));
  8968. auto fieldInst = &typeTypeInstance->mFieldInstances[9];
  8969. BF_ASSERT(fieldInst->GetFieldDef()->mName == "mInheritanceId");
  8970. BfIRValue gepValue = irb->CreateInBoundsGEP(typeInstDataRef, 0, fieldInst->mDataIdx);
  8971. BfIRValue wantInheritanceId = irb->CreateLoad(gepValue);
  8972. fieldInst = &typeTypeInstance->mFieldInstances[10];
  8973. BF_ASSERT(fieldInst->GetFieldDef()->mName == "mInheritanceCount");
  8974. gepValue = irb->CreateInBoundsGEP(typeInstDataRef, 0, fieldInst->mDataIdx);
  8975. BfIRValue inheritanceCount = irb->CreateLoad(gepValue);
  8976. BfIRValue idDiff = irb->CreateSub(objInheritanceId, wantInheritanceId);
  8977. BfIRValue cmpResult = irb->CreateCmpLTE(idDiff, inheritanceCount, false);
  8978. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  8979. }
  8980. }
  8981. }
  8982. void BfModule::EmitDynamicCastCheck(BfTypedValue typedVal, BfType* type, bool allowNull)
  8983. {
  8984. if (mBfIRBuilder->mIgnoreWrites)
  8985. return;
  8986. bool emitDynamicCastCheck = mCompiler->mOptions.mEmitDynamicCastCheck;
  8987. auto typeOptions = GetTypeOptions();
  8988. if (typeOptions != NULL)
  8989. emitDynamicCastCheck = typeOptions->Apply(emitDynamicCastCheck, BfOptionFlags_EmitDynamicCastCheck);
  8990. if (emitDynamicCastCheck)
  8991. {
  8992. int wantTypeId = 0;
  8993. if (!type->IsGenericParam())
  8994. wantTypeId = type->mTypeId;
  8995. BfIRBlock failBlock = mBfIRBuilder->CreateBlock("dynFail");
  8996. BfIRBlock endBlock = mBfIRBuilder->CreateBlock("dynEnd");
  8997. EmitDynamicCastCheck(typedVal, type, endBlock, failBlock, allowNull ? true : false);
  8998. AddBasicBlock(failBlock);
  8999. if (mIsComptimeModule)
  9000. {
  9001. mBfIRBuilder->Comptime_Error(CeErrorKind_ObjectDynCheckFailed);
  9002. }
  9003. else
  9004. {
  9005. SizedArray<BfIRValue, 8> llvmArgs;
  9006. auto bitAddr = mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType));
  9007. llvmArgs.push_back(bitAddr);
  9008. llvmArgs.push_back(GetConstValue32(wantTypeId));
  9009. auto objDynCheck = GetInternalMethod("ObjectDynCheckFailed");
  9010. BF_ASSERT(objDynCheck);
  9011. if (objDynCheck)
  9012. {
  9013. auto callInst = mBfIRBuilder->CreateCall(objDynCheck.mFunc, llvmArgs);
  9014. }
  9015. }
  9016. mBfIRBuilder->CreateBr(endBlock);
  9017. AddBasicBlock(endBlock);
  9018. }
  9019. }
  9020. BfTypedValue BfModule::BoxValue(BfAstNode* srcNode, BfTypedValue typedVal, BfType* toType, const BfAllocTarget& allocTarget, BfCastFlags castFlags)
  9021. {
  9022. bool callDtor = (castFlags & BfCastFlags_NoBoxDtor) == 0;
  9023. bool wantConst = ((castFlags & BfCastFlags_WantsConst) != 0) && (typedVal.mValue.IsConst());
  9024. if ((mBfIRBuilder->mIgnoreWrites) && (!wantConst))
  9025. {
  9026. if (toType == mContext->mBfObjectType)
  9027. return BfTypedValue(mBfIRBuilder->GetFakeVal(), toType);
  9028. if (toType->IsBoxed())
  9029. {
  9030. BfBoxedType* boxedType = (BfBoxedType*)toType;
  9031. if (boxedType->mElementType->IsGenericParam())
  9032. {
  9033. if (typedVal.mType == boxedType->mElementType)
  9034. return BfTypedValue(mBfIRBuilder->GetFakeVal(), toType);
  9035. else
  9036. return BfTypedValue();
  9037. }
  9038. }
  9039. }
  9040. BP_ZONE("BoxValue");
  9041. BfTypeInstance* fromStructTypeInstance = typedVal.mType->ToTypeInstance();
  9042. if (typedVal.mType->IsNullable())
  9043. {
  9044. typedVal = MakeAddressable(typedVal);
  9045. auto innerType = typedVal.mType->GetUnderlyingType();
  9046. if (!innerType->IsValueType())
  9047. {
  9048. if (!mIgnoreErrors)
  9049. Fail("Only value types can be boxed", srcNode);
  9050. return BfTypedValue();
  9051. }
  9052. auto boxedType = CreateBoxedType(innerType);
  9053. auto resultType = toType;
  9054. if (resultType == NULL)
  9055. resultType = boxedType;
  9056. if (mBfIRBuilder->mIgnoreWrites)
  9057. return BfTypedValue(mBfIRBuilder->GetFakeVal(), resultType);
  9058. auto prevBB = mBfIRBuilder->GetInsertBlock();
  9059. auto boxBB = mBfIRBuilder->CreateBlock("boxedN.notNull");
  9060. auto endBB = mBfIRBuilder->CreateBlock("boxedN.end");
  9061. mBfIRBuilder->PopulateType(typedVal.mType);
  9062. auto hasValueAddr = mBfIRBuilder->CreateInBoundsGEP(typedVal.mValue, 0, innerType->IsValuelessType() ? 1 : 2); // has_value
  9063. auto hasValue = mBfIRBuilder->CreateLoad(hasValueAddr);
  9064. mBfIRBuilder->CreateCondBr(hasValue, boxBB, endBB);
  9065. AddDependency(boxedType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  9066. mBfIRBuilder->AddBlock(boxBB);
  9067. mBfIRBuilder->SetInsertPoint(boxBB);
  9068. BfScopeData newScope;
  9069. newScope.mOuterIsConditional = true;
  9070. mCurMethodState->AddScope(&newScope);
  9071. NewScopeState();
  9072. BfIRValue nullableValueAddr;
  9073. BfIRValue loadedVal;
  9074. if (innerType->IsValuelessType())
  9075. {
  9076. loadedVal = mBfIRBuilder->GetFakeVal();
  9077. }
  9078. else
  9079. {
  9080. nullableValueAddr = mBfIRBuilder->CreateInBoundsGEP(typedVal.mValue, 0, 1); // value
  9081. loadedVal = mBfIRBuilder->CreateLoad(nullableValueAddr);
  9082. }
  9083. auto boxedVal = BoxValue(srcNode, BfTypedValue(loadedVal, fromStructTypeInstance->GetUnderlyingType()), resultType, allocTarget, callDtor ? BfCastFlags_None : BfCastFlags_NoBoxDtor);
  9084. RestoreScopeState();
  9085. if (!boxedVal)
  9086. return BfTypedValue();
  9087. mBfIRBuilder->CreateBr(endBB);
  9088. auto boxBBEnd = mBfIRBuilder->GetInsertBlock();
  9089. mBfIRBuilder->AddBlock(endBB);
  9090. mBfIRBuilder->SetInsertPoint(endBB);
  9091. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapType(resultType), 2);
  9092. mBfIRBuilder->AddPhiIncoming(phi, boxedVal.mValue, boxBBEnd);
  9093. mBfIRBuilder->AddPhiIncoming(phi, GetDefaultValue(resultType), prevBB);
  9094. return BfTypedValue(phi, resultType);
  9095. }
  9096. bool alreadyCheckedCast = false;
  9097. BfTypeInstance* toTypeInstance = NULL;
  9098. if (toType != NULL)
  9099. toTypeInstance = toType->ToTypeInstance();
  9100. bool isStructPtr = typedVal.mType->IsStructPtr();
  9101. if (fromStructTypeInstance == NULL)
  9102. {
  9103. auto primType = (BfPrimitiveType*)typedVal.mType;
  9104. if ((typedVal.mType->IsPointer()) && (toTypeInstance->IsInstanceOf(mCompiler->mIHashableTypeDef)))
  9105. {
  9106. // Can always do IHashable
  9107. alreadyCheckedCast = true;
  9108. }
  9109. if ((!typedVal.mType->IsPointer()) || (toTypeInstance == mContext->mBfObjectType))
  9110. fromStructTypeInstance = GetWrappedStructType(typedVal.mType);
  9111. else
  9112. {
  9113. auto checkStructTypeInstance = GetWrappedStructType(typedVal.mType);
  9114. if (checkStructTypeInstance == toType->GetUnderlyingType())
  9115. fromStructTypeInstance = checkStructTypeInstance;
  9116. }
  9117. if (isStructPtr)
  9118. {
  9119. if ((toTypeInstance != NULL) && (fromStructTypeInstance != NULL) && (TypeIsSubTypeOf(fromStructTypeInstance, toTypeInstance)))
  9120. alreadyCheckedCast = true;
  9121. fromStructTypeInstance = typedVal.mType->GetUnderlyingType()->ToTypeInstance();
  9122. }
  9123. if ((fromStructTypeInstance == NULL) && (alreadyCheckedCast))
  9124. fromStructTypeInstance = GetWrappedStructType(typedVal.mType);
  9125. }
  9126. if (fromStructTypeInstance == NULL)
  9127. return BfTypedValue();
  9128. // Need to box it
  9129. bool isBoxedType = (fromStructTypeInstance != NULL) && (toType->IsBoxed());
  9130. if ((toType == NULL) || (toType == mContext->mBfObjectType) || (isBoxedType) || (alreadyCheckedCast) || (TypeIsSubTypeOf(fromStructTypeInstance, toTypeInstance)))
  9131. {
  9132. if ((mBfIRBuilder->mIgnoreWrites) && (!wantConst))
  9133. return BfTypedValue(mBfIRBuilder->GetFakeVal(), (toType != NULL) ? toType : CreateBoxedType(typedVal.mType));
  9134. auto boxedType = CreateBoxedType(typedVal.mType);
  9135. mBfIRBuilder->PopulateType(boxedType);
  9136. if (wantConst)
  9137. return BfTypedValue(mBfIRBuilder->CreateConstBox(typedVal.mValue, mBfIRBuilder->MapType(boxedType)), boxedType);
  9138. AddDependency(boxedType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  9139. auto allocaInst = AllocFromType(boxedType, allocTarget, BfIRValue(), BfIRValue(), 0, callDtor ? BfAllocFlags_None : BfAllocFlags_NoDtorCall);
  9140. BfTypedValue boxedTypedValue(allocaInst, boxedType);
  9141. mBfIRBuilder->SetName(allocaInst, "boxed." + fromStructTypeInstance->mTypeDef->mName->ToString());
  9142. if (boxedType->IsUnspecializedType())
  9143. {
  9144. BF_ASSERT((srcNode == NULL) || (mCurMethodInstance->mIsUnspecialized));
  9145. }
  9146. else
  9147. {
  9148. PopulateType(fromStructTypeInstance);
  9149. if (!fromStructTypeInstance->IsValuelessType())
  9150. {
  9151. typedVal = LoadValue(typedVal);
  9152. auto valPtr = mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 1);
  9153. if ((typedVal.mType != fromStructTypeInstance) && (!isStructPtr))
  9154. {
  9155. auto ptrType = CreatePointerType(typedVal.mType);
  9156. valPtr = mBfIRBuilder->CreateBitCast(valPtr, mBfIRBuilder->MapType(ptrType));
  9157. }
  9158. if (typedVal.IsSplat())
  9159. {
  9160. AggregateSplatIntoAddr(typedVal, valPtr);
  9161. }
  9162. else
  9163. mBfIRBuilder->CreateStore(typedVal.mValue, valPtr, typedVal.mType->mAlign);
  9164. }
  9165. }
  9166. if (toType == NULL)
  9167. {
  9168. return BfTypedValue(allocaInst, boxedType);
  9169. }
  9170. else
  9171. {
  9172. auto castedValue = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(toType));
  9173. return BfTypedValue(castedValue, toType);
  9174. }
  9175. }
  9176. return BfTypedValue();
  9177. }
  9178. bool BfModule::GetBasePropertyDef(BfPropertyDef*& propDef, BfTypeInstance*& typeInst)
  9179. {
  9180. BfTypeInstance* checkTypeInst = typeInst;
  9181. while (checkTypeInst != NULL)
  9182. {
  9183. for (auto checkProp : checkTypeInst->mTypeDef->mProperties)
  9184. {
  9185. if (checkProp->mName == propDef->mName)
  9186. {
  9187. auto checkPropDeclaration = BfNodeDynCast<BfPropertyDeclaration>(checkProp->mFieldDeclaration);
  9188. if ((checkPropDeclaration == NULL) || (checkPropDeclaration->mVirtualSpecifier == NULL) || (checkPropDeclaration->mVirtualSpecifier->GetToken() == BfToken_Virtual))
  9189. {
  9190. propDef = checkProp;
  9191. typeInst = checkTypeInst;
  9192. return true;
  9193. }
  9194. }
  9195. }
  9196. checkTypeInst = checkTypeInst->mBaseType;
  9197. }
  9198. return false;
  9199. }
  9200. BfMethodInstance* BfModule::GetRawMethodInstanceAtIdx(BfTypeInstance* typeInstance, int methodIdx, const char* assertName)
  9201. {
  9202. if (!typeInstance->mResolvingVarField)
  9203. {
  9204. if (!typeInstance->DefineStateAllowsStaticMethods())
  9205. PopulateType(typeInstance, BfPopulateType_AllowStaticMethods);
  9206. }
  9207. else
  9208. {
  9209. if (methodIdx >= (int)typeInstance->mMethodInstanceGroups.size())
  9210. {
  9211. AssertErrorState();
  9212. return NULL;
  9213. }
  9214. }
  9215. if (assertName != NULL)
  9216. {
  9217. BF_ASSERT(typeInstance->mTypeDef->mMethods[methodIdx]->mName == assertName);
  9218. }
  9219. if (methodIdx >= typeInstance->mMethodInstanceGroups.mSize)
  9220. {
  9221. if (mCompiler->EnsureCeUnpaused(typeInstance))
  9222. {
  9223. BF_FATAL("OOB in GetRawMethodInstanceAtIdx");
  9224. }
  9225. return NULL;
  9226. }
  9227. auto& methodGroup = typeInstance->mMethodInstanceGroups[methodIdx];
  9228. if (methodGroup.mDefault == NULL)
  9229. {
  9230. if (!mCompiler->mIsResolveOnly)
  9231. {
  9232. // Get it from the owning module so we don't create a reference prematurely...
  9233. auto declModule = typeInstance->mModule;
  9234. if ((typeInstance->mGenericTypeInfo != NULL) && (typeInstance->mGenericTypeInfo->mFinishedGenericParams) && (methodGroup.mOnDemandKind == BfMethodOnDemandKind_NotSet))
  9235. {
  9236. methodGroup.mOnDemandKind = BfMethodOnDemandKind_NoDecl_AwaitingReference;
  9237. if (!declModule->mIsScratchModule)
  9238. declModule->mOnDemandMethodCount++;
  9239. }
  9240. BF_ASSERT((methodGroup.mOnDemandKind == BfMethodOnDemandKind_AlwaysInclude) || (methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) || (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl) ||
  9241. (typeInstance->mTypeFailed) || (typeInstance->mDefineState < BfTypeDefineState_DefinedAndMethodsSlotted));
  9242. if ((methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) || (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl))
  9243. methodGroup.mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingDecl;
  9244. BfGetMethodInstanceFlags useFlags = (BfGetMethodInstanceFlags)(BfGetMethodInstanceFlag_MethodInstanceOnly | BfGetMethodInstanceFlag_UnspecializedPass | BfGetMethodInstanceFlag_Unreified);
  9245. return declModule->GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector(), useFlags).mMethodInstance;
  9246. }
  9247. else
  9248. {
  9249. auto declModule = typeInstance->mModule;
  9250. BfGetMethodInstanceFlags useFlags = (BfGetMethodInstanceFlags)(BfGetMethodInstanceFlag_MethodInstanceOnly | BfGetMethodInstanceFlag_UnspecializedPass);
  9251. return declModule->GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector(), useFlags).mMethodInstance;
  9252. }
  9253. }
  9254. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  9255. //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
  9256. // be from a call to the NON-raw version
  9257. // if (!methodInstance->mMethodInstanceGroup->IsImplemented())
  9258. // {
  9259. // methodInstance->mIsReified = mIsReified;
  9260. // if (methodInstance->mMethodProcessRequest == NULL)
  9261. // typeInstance->mModule->AddMethodToWorkList(methodInstance);
  9262. // }
  9263. return methodInstance;
  9264. }
  9265. BfMethodInstance* BfModule::GetRawMethodInstance(BfTypeInstance* typeInstance, BfMethodDef* methodDef)
  9266. {
  9267. if (methodDef->mIsLocalMethod)
  9268. {
  9269. return GetMethodInstance(typeInstance, methodDef, BfTypeVector()).mMethodInstance;
  9270. }
  9271. return GetRawMethodInstanceAtIdx(typeInstance, methodDef->mIdx, NULL);
  9272. }
  9273. BfMethodInstance* BfModule::GetRawMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase, bool allowMixin)
  9274. {
  9275. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  9276. while (typeInstance != NULL)
  9277. {
  9278. typeInstance->mTypeDef->PopulateMemberSets();
  9279. BfMemberSetEntry* entry = NULL;
  9280. BfMethodDef* methodDef = NULL;
  9281. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  9282. methodDef = (BfMethodDef*)entry->mMemberDef;
  9283. while (methodDef != NULL)
  9284. {
  9285. if (((allowMixin) || (methodDef->mMethodType != BfMethodType_Mixin)) &&
  9286. (methodDef->mGenericParams.size() == 0) &&
  9287. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  9288. return GetRawMethodInstance(typeInstance, methodDef);
  9289. methodDef = methodDef->mNextWithSameName;
  9290. }
  9291. if (!checkBase)
  9292. break;
  9293. typeInstance = typeInstance->mBaseType;
  9294. }
  9295. return NULL;
  9296. }
  9297. BfMethodInstance* BfModule::GetUnspecializedMethodInstance(BfMethodInstance* methodInstance, bool useUnspecializedType)
  9298. {
  9299. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mMethodGenericArguments.size() != 0))
  9300. methodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  9301. auto owner = methodInstance->mMethodInstanceGroup->mOwner;
  9302. if (!useUnspecializedType)
  9303. return methodInstance;
  9304. if (!owner->IsGenericTypeInstance())
  9305. return methodInstance;
  9306. if ((owner->IsDelegateFromTypeRef()) ||
  9307. (owner->IsFunctionFromTypeRef()) ||
  9308. (owner->IsTuple()))
  9309. {
  9310. return methodInstance;
  9311. }
  9312. auto genericType = (BfTypeInstance*)owner;
  9313. if ((genericType->IsUnspecializedType()) && (!genericType->IsUnspecializedTypeVariation()))
  9314. return methodInstance;
  9315. if (methodInstance->mMethodDef->mIsLocalMethod)
  9316. return methodInstance;
  9317. if (methodInstance->mMethodDef->mDeclaringType->IsEmitted())
  9318. return methodInstance;
  9319. auto unspecializedType = ResolveTypeDef(genericType->mTypeDef->GetDefinition());
  9320. if (unspecializedType == NULL)
  9321. {
  9322. AssertErrorState();
  9323. return methodInstance;
  9324. }
  9325. if (unspecializedType == NULL)
  9326. return methodInstance;
  9327. auto unspecializedTypeInst = unspecializedType->ToTypeInstance();
  9328. return GetRawMethodInstanceAtIdx(unspecializedTypeInst, methodInstance->mMethodDef->mIdx);
  9329. }
  9330. int BfModule::GetGenericParamAndReturnCount(BfMethodInstance* methodInstance)
  9331. {
  9332. int genericCount = 0;
  9333. auto unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance);
  9334. for (int paramIdx = 0; paramIdx < unspecializedMethodInstance->GetParamCount(); paramIdx++)
  9335. {
  9336. auto param = unspecializedMethodInstance->GetParamType(paramIdx);
  9337. if (param->IsGenericParam())
  9338. genericCount++;
  9339. }
  9340. if (unspecializedMethodInstance->mReturnType->IsGenericParam())
  9341. genericCount++;
  9342. return genericCount;
  9343. }
  9344. BfModule* BfModule::GetSpecializedMethodModule(const SizedArrayImpl<BfProject*>& projectList)
  9345. {
  9346. BF_ASSERT(!mIsScratchModule);
  9347. BF_ASSERT(mIsReified);
  9348. BfModule* mainModule = this;
  9349. if (mParentModule != NULL)
  9350. mainModule = mParentModule;
  9351. BfModule* specModule = NULL;
  9352. BfModule** specModulePtr = NULL;
  9353. if (mainModule->mSpecializedMethodModules.TryGetValueWith(projectList, &specModulePtr))
  9354. {
  9355. return *specModulePtr;
  9356. }
  9357. else
  9358. {
  9359. String specModuleName = mModuleName;
  9360. for (auto bfProject : projectList)
  9361. {
  9362. specModuleName += StrFormat("@%s", bfProject->mSafeName.c_str());
  9363. }
  9364. specModule = new BfModule(mContext, specModuleName);
  9365. specModule->mProject = mainModule->mProject;
  9366. specModule->mParentModule = mainModule;
  9367. specModule->mIsSpecializedMethodModuleRoot = true;
  9368. specModule->Init();
  9369. Array<BfProject*> projList;
  9370. for (auto project : projectList)
  9371. projList.Add(project);
  9372. mainModule->mSpecializedMethodModules[projList] = specModule;
  9373. }
  9374. return specModule;
  9375. }
  9376. BfIRValue BfModule::CreateFunctionFrom(BfMethodInstance* methodInstance, bool tryExisting, bool isInlined)
  9377. {
  9378. if (IsSkippingExtraResolveChecks())
  9379. return BfIRValue();
  9380. if (methodInstance->mMethodInstanceGroup->mOwner->IsInterface())
  9381. {
  9382. //BF_ASSERT(!methodInstance->mIRFunction);
  9383. return BfIRValue();
  9384. }
  9385. auto methodDef = methodInstance->mMethodDef;
  9386. StringT<4096> methodName;
  9387. BfMangler::Mangle(methodName, mCompiler->GetMangleKind(), methodInstance);
  9388. if (isInlined != methodInstance->mAlwaysInline)
  9389. {
  9390. if (isInlined)
  9391. methodName += "__INLINE";
  9392. else
  9393. methodName += "__NOINLINE";
  9394. }
  9395. if (tryExisting)
  9396. {
  9397. auto func = mBfIRBuilder->GetFunction(methodName);
  9398. if (func)
  9399. return func;
  9400. }
  9401. auto intrinsic = GetIntrinsic(methodInstance);
  9402. if (intrinsic)
  9403. return intrinsic;
  9404. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  9405. {
  9406. return CreateDllImportGlobalVar(methodInstance, false);
  9407. }
  9408. BfIRType returnType;
  9409. SizedArray<BfIRType, 8> paramTypes;
  9410. methodInstance->GetIRFunctionInfo(this, returnType, paramTypes);
  9411. auto funcType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes, methodInstance->IsVarArgs());
  9412. auto func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, methodName);
  9413. auto callingConv = GetIRCallingConvention(methodInstance);
  9414. if (callingConv != BfIRCallingConv_CDecl)
  9415. mBfIRBuilder->SetFuncCallingConv(func, callingConv);
  9416. SetupIRMethod(methodInstance, func, isInlined);
  9417. // auto srcModule = methodInstance->GetOwner()->GetModule();
  9418. // if ((srcModule != NULL) && (srcModule->mProject != mProject))
  9419. // {
  9420. // if (srcModule->mProject->mTargetType == BfTargetType_BeefDynLib)
  9421. // {
  9422. // mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_DllImport);
  9423. // }
  9424. // }
  9425. return func;
  9426. }
  9427. BfModuleMethodInstance BfModule::GetMethodInstanceAtIdx(BfTypeInstance* typeInstance, int methodIdx, const char* assertName, BfGetMethodInstanceFlags flags)
  9428. {
  9429. if (assertName != NULL)
  9430. {
  9431. BF_ASSERT(typeInstance->mTypeDef->mMethods[methodIdx]->mName == assertName);
  9432. }
  9433. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  9434. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  9435. BfMethodDef* methodDef = NULL;
  9436. BfTypeInstance* foreignType = NULL;
  9437. if (methodInstance != NULL)
  9438. {
  9439. methodDef = methodInstance->mMethodDef;
  9440. if (methodInstance->mMethodInfoEx != NULL)
  9441. foreignType = methodInstance->mMethodInfoEx->mForeignType;
  9442. }
  9443. if ((methodInstance != NULL) && (mIsReified) && (!methodInstance->mIsReified))
  9444. {
  9445. // Can't use it, not reified
  9446. methodInstance = NULL;
  9447. }
  9448. if ((methodInstance != NULL) && (mBfIRBuilder != NULL) && (mBfIRBuilder->mIgnoreWrites) &&
  9449. (methodInstance->mMethodInstanceGroup->IsImplemented()))
  9450. {
  9451. BfIRFunction func(mBfIRBuilder->GetFakeVal());
  9452. return BfModuleMethodInstance(methodInstance, func);
  9453. }
  9454. if (foreignType != NULL)
  9455. return GetMethodInstance(typeInstance, methodDef, BfTypeVector(), (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ForeignMethodDef), foreignType);
  9456. return GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector(), flags);
  9457. }
  9458. BfModuleMethodInstance BfModule::GetMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  9459. {
  9460. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  9461. while (typeInstance != NULL)
  9462. {
  9463. typeInstance->mTypeDef->PopulateMemberSets();
  9464. BfMemberSetEntry* entry = NULL;
  9465. BfMethodDef* methodDef = NULL;
  9466. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  9467. methodDef = (BfMethodDef*)entry->mMemberDef;
  9468. while (methodDef != NULL)
  9469. {
  9470. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  9471. (methodDef->mGenericParams.size() == 0) &&
  9472. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  9473. {
  9474. auto moduleMethodInstance = GetMethodInstanceAtIdx(typeInstance, methodDef->mIdx);
  9475. if (moduleMethodInstance)
  9476. return moduleMethodInstance;
  9477. }
  9478. methodDef = methodDef->mNextWithSameName;
  9479. }
  9480. if (!checkBase)
  9481. break;
  9482. typeInstance = typeInstance->mBaseType;
  9483. }
  9484. return BfModuleMethodInstance();
  9485. }
  9486. BfModuleMethodInstance BfModule::GetMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, const Array<BfType*>& paramTypes, bool checkBase)
  9487. {
  9488. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  9489. while (typeInstance != NULL)
  9490. {
  9491. typeInstance->mTypeDef->PopulateMemberSets();
  9492. BfMemberSetEntry* entry = NULL;
  9493. BfMethodDef* methodDef = NULL;
  9494. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  9495. methodDef = (BfMethodDef*)entry->mMemberDef;
  9496. while (methodDef != NULL)
  9497. {
  9498. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  9499. (methodDef->mGenericParams.size() == 0) &&
  9500. (paramTypes.size() == methodDef->mParams.size()))
  9501. {
  9502. auto moduleMethodInstance = GetMethodInstanceAtIdx(typeInstance, methodDef->mIdx);
  9503. if (moduleMethodInstance.mMethodInstance != NULL)
  9504. {
  9505. bool matches = true;
  9506. for (int paramIdx = 0; paramIdx < (int)paramTypes.size(); paramIdx++)
  9507. {
  9508. if (moduleMethodInstance.mMethodInstance->GetParamType(paramIdx) != paramTypes[paramIdx])
  9509. matches = false;
  9510. }
  9511. if (matches)
  9512. return moduleMethodInstance;
  9513. }
  9514. }
  9515. methodDef = methodDef->mNextWithSameName;
  9516. }
  9517. if (!checkBase)
  9518. break;
  9519. typeInstance = typeInstance->mBaseType;
  9520. }
  9521. return BfModuleMethodInstance();
  9522. }
  9523. BfModuleMethodInstance BfModule::GetInternalMethod(const StringImpl& methodName, int paramCount)
  9524. {
  9525. auto internalType = ResolveTypeDef(mCompiler->mInternalTypeDef);
  9526. PopulateType(internalType);
  9527. auto moduleMethodInstance = GetMethodByName(internalType->ToTypeInstance(), methodName, paramCount);
  9528. if (!moduleMethodInstance)
  9529. {
  9530. Fail(StrFormat("Failed to find System.Internal method '%s'", methodName.c_str()));
  9531. }
  9532. return moduleMethodInstance;
  9533. }
  9534. BfOperatorInfo* BfModule::GetOperatorInfo(BfTypeInstance* typeInstance, BfOperatorDef* operatorDef)
  9535. {
  9536. while (operatorDef->mIdx >= typeInstance->mOperatorInfo.size())
  9537. typeInstance->mOperatorInfo.Add(NULL);
  9538. if (typeInstance->mOperatorInfo[operatorDef->mIdx] == NULL)
  9539. {
  9540. SetAndRestoreValue<bool> ignoreErrors(mIgnoreErrors, true);
  9541. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  9542. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL);
  9543. BfTypeState typeState;
  9544. typeState.mType = typeInstance;
  9545. typeState.mCurTypeDef = operatorDef->mDeclaringType;
  9546. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  9547. BfOperatorInfo* operatorInfo = new BfOperatorInfo();
  9548. if (operatorDef->mReturnTypeRef != NULL)
  9549. operatorInfo->mReturnType = ResolveTypeRef(operatorDef->mReturnTypeRef, BfPopulateType_Identity);
  9550. if (operatorDef->mParams.size() >= 1)
  9551. operatorInfo->mLHSType = ResolveTypeRef(operatorDef->mParams[0]->mTypeRef, BfPopulateType_Identity);
  9552. if (operatorDef->mParams.size() >= 2)
  9553. operatorInfo->mRHSType = ResolveTypeRef(operatorDef->mParams[1]->mTypeRef, BfPopulateType_Identity);
  9554. typeInstance->mOperatorInfo[operatorDef->mIdx] = operatorInfo;
  9555. }
  9556. return typeInstance->mOperatorInfo[operatorDef->mIdx];
  9557. }
  9558. BfType* BfModule::CheckOperator(BfTypeInstance* typeInstance, BfOperatorDef* operatorDef, const BfTypedValue& lhs, const BfTypedValue& rhs)
  9559. {
  9560. auto operatorInfo = GetOperatorInfo(typeInstance, operatorDef);
  9561. if (operatorInfo == NULL)
  9562. return NULL;
  9563. if (operatorInfo->mReturnType == NULL)
  9564. return NULL;
  9565. auto castFlags = BfCastFlags_IsConstraintCheck;
  9566. if (operatorDef->mOperatorDeclaration->mIsConvOperator)
  9567. castFlags = (BfCastFlags)(castFlags | BfCastFlags_NoConversionOperator);
  9568. if (lhs)
  9569. {
  9570. if (operatorInfo->mLHSType == NULL)
  9571. return NULL;
  9572. if (!CanCast(lhs, operatorInfo->mLHSType, castFlags))
  9573. return NULL;
  9574. }
  9575. if (rhs)
  9576. {
  9577. if (operatorInfo->mRHSType == NULL)
  9578. return NULL;
  9579. if (!CanCast(rhs, operatorInfo->mRHSType, castFlags))
  9580. return NULL;
  9581. }
  9582. return operatorInfo->mReturnType;
  9583. }
  9584. bool BfModule::IsMethodImplementedAndReified(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  9585. {
  9586. while (typeInstance != NULL)
  9587. {
  9588. typeInstance->mTypeDef->PopulateMemberSets();
  9589. BfMemberSetEntry* entry = NULL;
  9590. BfMethodDef* methodDef = NULL;
  9591. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  9592. methodDef = (BfMethodDef*)entry->mMemberDef;
  9593. while (methodDef != NULL)
  9594. {
  9595. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  9596. (methodDef->mGenericParams.size() == 0) &&
  9597. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  9598. {
  9599. auto& methodInstanceGroup = typeInstance->mMethodInstanceGroups[methodDef->mIdx];
  9600. if (!methodInstanceGroup.IsImplemented())
  9601. return false;
  9602. if (methodInstanceGroup.mDefault == NULL)
  9603. return false;
  9604. return methodInstanceGroup.mDefault->mIsReified;
  9605. }
  9606. methodDef = methodDef->mNextWithSameName;
  9607. }
  9608. if (!checkBase)
  9609. break;
  9610. typeInstance = typeInstance->mBaseType;
  9611. }
  9612. return false;
  9613. }
  9614. bool BfModule::HasMixin(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  9615. {
  9616. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  9617. while (typeInstance != NULL)
  9618. {
  9619. typeInstance->mTypeDef->PopulateMemberSets();
  9620. BfMemberSetEntry* entry = NULL;
  9621. BfMethodDef* methodDef = NULL;
  9622. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  9623. methodDef = (BfMethodDef*)entry->mMemberDef;
  9624. while (methodDef != NULL)
  9625. {
  9626. if ((methodDef->mMethodType == BfMethodType_Mixin) &&
  9627. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  9628. return true;
  9629. methodDef = methodDef->mNextWithSameName;
  9630. }
  9631. if (!checkBase)
  9632. break;
  9633. typeInstance = typeInstance->mBaseType;
  9634. }
  9635. return BfModuleMethodInstance();
  9636. }
  9637. StringT<128> BfModule::MethodToString(BfMethodInstance* methodInst, BfMethodNameFlags methodNameFlags, BfTypeVector* typeGenericArgs, BfTypeVector* methodGenericArgs)
  9638. {
  9639. auto methodDef = methodInst->mMethodDef;
  9640. bool allowResolveGenericParamNames = ((methodNameFlags & BfMethodNameFlag_ResolveGenericParamNames) != 0);
  9641. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  9642. bool hasGenericArgs = (typeGenericArgs != NULL) || (methodGenericArgs != NULL);
  9643. BfType* type = methodInst->mMethodInstanceGroup->mOwner;
  9644. if ((hasGenericArgs) && (type->IsUnspecializedType()))
  9645. type = ResolveGenericType(type, typeGenericArgs, methodGenericArgs, mCurTypeInstance);
  9646. if ((type == NULL) || (!type->IsUnspecializedTypeVariation()))
  9647. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  9648. if (allowResolveGenericParamNames)
  9649. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  9650. StringT<128> methodName;
  9651. auto _AddTypeName = [&](BfType* type)
  9652. {
  9653. auto typeNameFlags = BfTypeNameFlags_None;
  9654. if (allowResolveGenericParamNames)
  9655. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  9656. if ((hasGenericArgs) && (type->IsUnspecializedType()))
  9657. type = ResolveGenericType(type, typeGenericArgs, methodGenericArgs, mCurTypeInstance);
  9658. methodName += TypeToString(type, typeNameFlags);
  9659. };
  9660. if ((methodNameFlags & BfMethodNameFlag_IncludeReturnType) != 0)
  9661. {
  9662. _AddTypeName(methodInst->mReturnType);
  9663. methodName += " ";
  9664. }
  9665. if ((methodNameFlags & BfMethodNameFlag_OmitTypeName) == 0)
  9666. {
  9667. methodName += TypeToString(type, typeNameFlags);
  9668. if (methodName == "$")
  9669. methodName = "";
  9670. else if (!methodName.IsEmpty())
  9671. methodName += ".";
  9672. }
  9673. String accessorString;
  9674. StringT<64> methodDefName = methodInst->mMethodDef->mName;
  9675. if (methodInst->mMethodDef->mIsLocalMethod)
  9676. {
  9677. int atPos = (int)methodDefName.IndexOf('$');
  9678. methodDefName.RemoveToEnd(atPos);
  9679. methodDefName.Replace("@", ".");
  9680. }
  9681. else
  9682. {
  9683. int atPos = (int)methodDefName.IndexOf('$');
  9684. if (atPos != -1)
  9685. {
  9686. accessorString = methodDefName.Substring(0, atPos);
  9687. if ((accessorString == "get") || (accessorString == "set"))
  9688. {
  9689. methodDefName = methodDefName.Substring(atPos + 1);
  9690. }
  9691. else
  9692. accessorString = "";
  9693. }
  9694. }
  9695. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mForeignType != NULL))
  9696. {
  9697. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  9698. if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  9699. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  9700. methodName += TypeToString(methodInst->mMethodInfoEx->mForeignType, typeNameFlags);
  9701. methodName += ".";
  9702. }
  9703. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mExplicitInterface != NULL))
  9704. {
  9705. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  9706. if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  9707. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  9708. methodName += "[";
  9709. methodName += TypeToString(methodInst->mMethodInfoEx->mExplicitInterface, typeNameFlags);
  9710. methodName += "].";
  9711. }
  9712. if (methodDef->mMethodType == BfMethodType_Operator)
  9713. {
  9714. BfOperatorDef* operatorDef = (BfOperatorDef*)methodDef;
  9715. if (operatorDef->mOperatorDeclaration->mIsConvOperator)
  9716. {
  9717. // Don't add explicit/implicit part, since that's not available in GCC mangling
  9718. /*if (operatorDef->mOperatorDeclaration->mExplicitToken != NULL)
  9719. {
  9720. if (operatorDef->mOperatorDeclaration->mExplicitToken->GetToken() == BfToken_Explicit)
  9721. methodName += "explicit ";
  9722. else if (operatorDef->mOperatorDeclaration->mExplicitToken->GetToken() == BfToken_Explicit)
  9723. methodName += "explicit ";
  9724. }*/
  9725. methodName += "operator ";
  9726. if (methodInst->mReturnType != NULL)
  9727. methodName += TypeToString(methodInst->mReturnType);
  9728. }
  9729. else
  9730. {
  9731. methodName += "operator";
  9732. if (operatorDef->mOperatorDeclaration->mOpTypeToken != NULL)
  9733. methodName += BfTokenToString(operatorDef->mOperatorDeclaration->mOpTypeToken->GetToken());
  9734. }
  9735. }
  9736. else if (methodDef->mMethodType == BfMethodType_Ctor)
  9737. {
  9738. if (methodDef->mIsStatic)
  9739. methodName += "__BfStaticCtor";
  9740. else
  9741. methodName += "this";
  9742. accessorString = "";
  9743. }
  9744. else if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  9745. {
  9746. auto propertyDecl = methodDef->GetPropertyDeclaration();
  9747. if (auto indexerProperty = BfNodeDynCast<BfIndexerDeclaration>(propertyDecl))
  9748. {
  9749. methodName += "get indexer";
  9750. }
  9751. else
  9752. {
  9753. if ((propertyDecl != NULL) && (propertyDecl->mNameNode != NULL))
  9754. propertyDecl->mNameNode->ToString(methodName);
  9755. methodName += " get accessor";
  9756. return methodName;
  9757. }
  9758. }
  9759. else if (methodDef->mMethodType == BfMethodType_PropertySetter)
  9760. {
  9761. auto propertyDecl = methodDef->GetPropertyDeclaration();
  9762. if (auto indexerProperty = BfNodeDynCast<BfIndexerDeclaration>(propertyDecl))
  9763. {
  9764. methodName += "set indexer";
  9765. }
  9766. else
  9767. {
  9768. if ((propertyDecl != NULL) && (propertyDecl->mNameNode != NULL))
  9769. propertyDecl->mNameNode->ToString(methodName);
  9770. methodName += " set accessor";
  9771. return methodName;
  9772. }
  9773. }
  9774. else
  9775. methodName += methodDefName;
  9776. if (methodDef->mMethodType == BfMethodType_Mixin)
  9777. methodName += "!";
  9778. BfTypeVector newMethodGenericArgs;
  9779. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mMethodGenericArguments.size() != 0))
  9780. {
  9781. methodName += "<";
  9782. for (int i = 0; i < (int)methodInst->mMethodInfoEx->mMethodGenericArguments.size(); i++)
  9783. {
  9784. if (i > 0)
  9785. methodName += ", ";
  9786. BfTypeNameFlags typeNameFlags = BfTypeNameFlag_ShortConst;
  9787. //Why did we have this methodInst->mIsUnspecializedVariation check? Sometimes we do need to show errors calling methods that refer back to our types
  9788. //if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  9789. if (allowResolveGenericParamNames)
  9790. typeNameFlags = (BfTypeNameFlags)(typeNameFlags | BfTypeNameFlag_ResolveGenericParamNames);
  9791. BfType* type = methodInst->mMethodInfoEx->mMethodGenericArguments[i];
  9792. if ((methodGenericArgs != NULL) && (type->IsUnspecializedType()))
  9793. {
  9794. bool hasEmpty = false;
  9795. for (auto arg : *methodGenericArgs)
  9796. {
  9797. if (arg == NULL)
  9798. hasEmpty = true;
  9799. }
  9800. if (hasEmpty)
  9801. {
  9802. for (int genericIdx = 0; genericIdx < (int)methodGenericArgs->size(); genericIdx++)
  9803. {
  9804. auto arg = (*methodGenericArgs)[genericIdx];
  9805. if (arg != NULL)
  9806. newMethodGenericArgs.push_back(arg);
  9807. else
  9808. {
  9809. auto genericParamInst = methodInst->mMethodInfoEx->mGenericParams[genericIdx];
  9810. if (genericParamInst->mTypeConstraint != NULL)
  9811. newMethodGenericArgs.push_back(genericParamInst->mTypeConstraint);
  9812. else
  9813. newMethodGenericArgs.push_back(mContext->mBfObjectType); // Default
  9814. }
  9815. }
  9816. methodGenericArgs = &newMethodGenericArgs;
  9817. }
  9818. if (type->IsUnspecializedType())
  9819. type = ResolveGenericType(type, NULL, methodGenericArgs, mCurTypeInstance);
  9820. }
  9821. if ((methodGenericArgs == NULL) && (mCurMethodInstance == NULL) && (mCurTypeInstance == NULL))
  9822. {
  9823. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, methodInst->GetOwner());
  9824. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInst);
  9825. methodName += TypeToString(type, typeNameFlags);
  9826. }
  9827. else
  9828. methodName += TypeToString(type, typeNameFlags);
  9829. }
  9830. methodName += ">";
  9831. }
  9832. if (accessorString.length() == 0)
  9833. {
  9834. int dispParamIdx = 0;
  9835. methodName += "(";
  9836. for (int paramIdx = 0; paramIdx < (int)methodInst->GetParamCount(); paramIdx++)
  9837. {
  9838. int paramKind = methodInst->GetParamKind(paramIdx);
  9839. if ((paramKind == BfParamKind_ImplicitCapture) || (paramKind == BfParamKind_AppendIdx))
  9840. continue;
  9841. if (dispParamIdx > 0)
  9842. methodName += ", ";
  9843. if (paramKind == BfParamKind_Params)
  9844. methodName += "params ";
  9845. BfType* type = methodInst->GetParamType(paramIdx);
  9846. _AddTypeName(type);
  9847. methodName += " ";
  9848. methodName += methodInst->GetParamName(paramIdx);
  9849. auto paramInitializer = methodInst->GetParamInitializer(paramIdx);
  9850. if ((paramInitializer != NULL) && ((methodNameFlags & BfMethodNameFlag_NoAst) == 0))
  9851. {
  9852. methodName += " = ";
  9853. methodName += paramInitializer->ToString();
  9854. }
  9855. dispParamIdx++;
  9856. }
  9857. methodName += ")";
  9858. }
  9859. if (accessorString.length() != 0)
  9860. {
  9861. methodName += " ";
  9862. methodName += accessorString;
  9863. }
  9864. if ((methodNameFlags & BfMethodNameFlag_IncludeMut) != 0)
  9865. {
  9866. if ((methodDef->mIsMutating) && (methodInst->GetOwner()->IsValueType()))
  9867. methodName += " mut";
  9868. }
  9869. return methodName;
  9870. }
  9871. void BfModule::pt(BfType* type)
  9872. {
  9873. OutputDebugStrF("%s\n", TypeToString(type).c_str());
  9874. }
  9875. void BfModule::pm(BfMethodInstance* type)
  9876. {
  9877. OutputDebugStrF("%s\n", MethodToString(type).c_str());
  9878. }
  9879. static void AddAttributeTargetName(BfAttributeTargets& flagsLeft, BfAttributeTargets checkFlag, String& str, String addString)
  9880. {
  9881. if ((flagsLeft & checkFlag) == 0)
  9882. return;
  9883. if (!str.empty())
  9884. {
  9885. if (flagsLeft == checkFlag)
  9886. {
  9887. if ((int)str.IndexOf(',') != -1)
  9888. str += ", and ";
  9889. else
  9890. str += " and ";
  9891. }
  9892. else
  9893. str += ", ";
  9894. }
  9895. str += addString;
  9896. flagsLeft = (BfAttributeTargets)(flagsLeft & ~checkFlag);
  9897. }
  9898. static String GetAttributesTargetListString(BfAttributeTargets attrTarget)
  9899. {
  9900. String resultStr;
  9901. auto flagsLeft = attrTarget;
  9902. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Assembly, resultStr, "assembly declarations");
  9903. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Module, resultStr, "module declarations");
  9904. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Class, resultStr, "class declarations");
  9905. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Struct, resultStr, "struct declarations");
  9906. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Enum, resultStr, "enum declarations");
  9907. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Constructor, resultStr, "constructor declarations");
  9908. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Method, resultStr, "method declarations");
  9909. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Property, resultStr, "property declarations");
  9910. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Field, resultStr, "field declarations");
  9911. AddAttributeTargetName(flagsLeft, BfAttributeTargets_StaticField, resultStr, "static field declarations");
  9912. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Interface, resultStr, "interface declarations");
  9913. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Parameter, resultStr, "parameter declarations");
  9914. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Delegate, resultStr, "delegate declarations");
  9915. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Function, resultStr, "function declarations");
  9916. AddAttributeTargetName(flagsLeft, BfAttributeTargets_ReturnValue, resultStr, "return value");
  9917. AddAttributeTargetName(flagsLeft, BfAttributeTargets_GenericParameter, resultStr, "generic parameters");
  9918. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Invocation, resultStr, "invocations");
  9919. AddAttributeTargetName(flagsLeft, BfAttributeTargets_MemberAccess, resultStr, "member access");
  9920. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Alloc, resultStr, "allocations");
  9921. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Alias, resultStr, "aliases");
  9922. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Block, resultStr, "blocks");
  9923. if (resultStr.IsEmpty())
  9924. return "<nothing>";
  9925. return resultStr;
  9926. }
  9927. BfIRType BfModule::CurrentAddToConstHolder(BfIRType irType)
  9928. {
  9929. if (irType.mKind == BfIRTypeData::TypeKind_SizedArray)
  9930. {
  9931. auto sizedArrayType = (BfConstantSizedArrayType*)mBfIRBuilder->GetConstantById(irType.mId);
  9932. return mCurTypeInstance->GetOrCreateConstHolder()->GetSizedArrayType(CurrentAddToConstHolder(sizedArrayType->mType), (int)sizedArrayType->mLength);
  9933. }
  9934. return irType;
  9935. }
  9936. void BfModule::CurrentAddToConstHolder(BfIRValue& irVal)
  9937. {
  9938. auto constant = mBfIRBuilder->GetConstant(irVal);
  9939. int stringPoolIdx = GetStringPoolIdx(irVal, mBfIRBuilder);
  9940. if (stringPoolIdx != -1)
  9941. {
  9942. irVal = mCurTypeInstance->GetOrCreateConstHolder()->CreateConst(BfTypeCode_StringId, stringPoolIdx);
  9943. return;
  9944. }
  9945. if (constant->mConstType == BfConstType_Agg)
  9946. {
  9947. auto constArray = (BfConstantAgg*)constant;
  9948. SizedArray<BfIRValue, 8> newVals;
  9949. for (auto val : constArray->mValues)
  9950. {
  9951. auto newVal = val;
  9952. CurrentAddToConstHolder(newVal);
  9953. newVals.push_back(newVal);
  9954. }
  9955. irVal = mCurTypeInstance->GetOrCreateConstHolder()->CreateConstAgg(CurrentAddToConstHolder(constArray->mType), newVals);
  9956. return;
  9957. }
  9958. auto origConst = irVal;
  9959. if ((constant->mConstType == BfConstType_BitCast) || (constant->mConstType == BfConstType_BitCastNull))
  9960. {
  9961. auto bitcast = (BfConstantBitCast*)constant;
  9962. BfIRValue newVal;
  9963. if (bitcast->mTarget)
  9964. {
  9965. newVal = BfIRValue(BfIRValueFlags_Const, bitcast->mTarget);
  9966. CurrentAddToConstHolder(newVal);
  9967. }
  9968. else
  9969. newVal = mCurTypeInstance->GetOrCreateConstHolder()->CreateConstNull();
  9970. irVal = mCurTypeInstance->GetOrCreateConstHolder()->CreateConstBitCast(newVal, CurrentAddToConstHolder(bitcast->mToType));
  9971. return;
  9972. }
  9973. irVal = mCurTypeInstance->CreateConst(constant, mBfIRBuilder);
  9974. }
  9975. void BfModule::ClearConstData()
  9976. {
  9977. mBfIRBuilder->ClearConstData();
  9978. mStringObjectPool.Clear();
  9979. mStringCharPtrPool.Clear();
  9980. mStringPoolRefs.Clear();
  9981. mUnreifiedStringPoolRefs.Clear();
  9982. mStaticFieldRefs.Clear();
  9983. }
  9984. BfTypedValue BfModule::GetTypedValueFromConstant(BfConstant* constant, BfIRConstHolder* constHolder, BfType* wantType)
  9985. {
  9986. switch (constant->mTypeCode)
  9987. {
  9988. case BfTypeCode_StringId:
  9989. case BfTypeCode_Boolean:
  9990. case BfTypeCode_Int8:
  9991. case BfTypeCode_UInt8:
  9992. case BfTypeCode_Int16:
  9993. case BfTypeCode_UInt16:
  9994. case BfTypeCode_Int32:
  9995. case BfTypeCode_UInt32:
  9996. case BfTypeCode_Int64:
  9997. case BfTypeCode_UInt64:
  9998. case BfTypeCode_IntPtr:
  9999. case BfTypeCode_UIntPtr:
  10000. case BfTypeCode_IntUnknown:
  10001. case BfTypeCode_UIntUnknown:
  10002. case BfTypeCode_Char8:
  10003. case BfTypeCode_Char16:
  10004. case BfTypeCode_Char32:
  10005. case BfTypeCode_Float:
  10006. case BfTypeCode_Double:
  10007. {
  10008. auto constVal = mBfIRBuilder->CreateConst(constant, constHolder);
  10009. BfTypedValue typedValue;
  10010. bool allowUnactualized = mBfIRBuilder->mIgnoreWrites;
  10011. if (constant->mTypeCode == BfTypeCode_StringId)
  10012. {
  10013. if ((wantType->IsInstanceOf(mCompiler->mStringTypeDef)) ||
  10014. ((wantType->IsPointer()) && (wantType->GetUnderlyingType() == GetPrimitiveType(BfTypeCode_Char8))))
  10015. {
  10016. typedValue = BfTypedValue(ConstantToCurrent(constant, constHolder, wantType, allowUnactualized), wantType);
  10017. return typedValue;
  10018. }
  10019. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  10020. typedValue = BfTypedValue(ConstantToCurrent(constant, constHolder, stringType, allowUnactualized), stringType);
  10021. }
  10022. if (!typedValue)
  10023. {
  10024. auto constVal = mBfIRBuilder->CreateConst(constant, constHolder);
  10025. typedValue = BfTypedValue(constVal, GetPrimitiveType(constant->mTypeCode));
  10026. }
  10027. if (typedValue.mType == wantType)
  10028. return typedValue;
  10029. if (wantType->IsTypedPrimitive())
  10030. {
  10031. if (typedValue.mType == wantType->GetUnderlyingType())
  10032. {
  10033. typedValue.mType = wantType;
  10034. return typedValue;
  10035. }
  10036. }
  10037. auto castedTypedValue = Cast(NULL, typedValue, wantType, (BfCastFlags)(BfCastFlags_SilentFail | BfCastFlags_Explicit));
  10038. if (!castedTypedValue)
  10039. return BfTypedValue();
  10040. return castedTypedValue;
  10041. }
  10042. break;
  10043. default: break;
  10044. }
  10045. BfIRValue irValue = ConstantToCurrent(constant, constHolder, wantType);
  10046. BF_ASSERT(irValue);
  10047. if (!irValue)
  10048. return BfTypedValue();
  10049. if (constant->mConstType == BfConstType_GlobalVar)
  10050. {
  10051. mBfIRBuilder->PopulateType(wantType);
  10052. auto result = BfTypedValue(irValue, wantType, true);
  10053. if (!wantType->IsComposite())
  10054. result = LoadValue(result);
  10055. return result;
  10056. }
  10057. return BfTypedValue(irValue, wantType, false);
  10058. }
  10059. bool BfModule::HasUnactializedConstant(BfConstant* constant, BfIRConstHolder* constHolder)
  10060. {
  10061. if ((constant->mConstType == BfConstType_TypeOf) || (constant->mConstType == BfConstType_TypeOf_WithData))
  10062. return true;
  10063. if (constant->mTypeCode == BfTypeCode_StringId)
  10064. return true;
  10065. if (constant->mConstType == BfConstType_Agg)
  10066. {
  10067. auto constArray = (BfConstantAgg*)constant;
  10068. for (auto val : constArray->mValues)
  10069. {
  10070. if (HasUnactializedConstant(constHolder->GetConstant(val), constHolder))
  10071. return true;
  10072. }
  10073. }
  10074. return false;
  10075. }
  10076. BfIRValue BfModule::ConstantToCurrent(BfConstant* constant, BfIRConstHolder* constHolder, BfType* wantType, bool allowUnactualized)
  10077. {
  10078. if (constant->mTypeCode == BfTypeCode_NullPtr)
  10079. {
  10080. if ((wantType == NULL) && (constant->mIRType.mKind == BfIRTypeData::TypeKind_TypeId))
  10081. wantType = mContext->mTypes[constant->mIRType.mId];
  10082. if (wantType == NULL)
  10083. return mBfIRBuilder->CreateConstNull();
  10084. return GetDefaultValue(wantType);
  10085. }
  10086. if (constant->mTypeCode == BfTypeCode_StringId)
  10087. {
  10088. if (!allowUnactualized)
  10089. {
  10090. if ((wantType->IsInstanceOf(mCompiler->mStringTypeDef)) ||
  10091. ((wantType->IsPointer()) && (wantType->GetUnderlyingType() == GetPrimitiveType(BfTypeCode_Char8))))
  10092. {
  10093. const StringImpl& str = mContext->mStringObjectIdMap[constant->mInt32].mString;
  10094. BfIRValue stringObjConst = GetStringObjectValue(str, false, true);
  10095. if (wantType->IsPointer())
  10096. return GetStringCharPtr(stringObjConst, true);
  10097. return stringObjConst;
  10098. }
  10099. }
  10100. }
  10101. if (constant->mConstType == Beefy::BfConstType_TypeOf)
  10102. {
  10103. auto constTypeOf = (BfTypeOf_Const*)constant;
  10104. if (mCurTypeInstance != NULL)
  10105. AddDependency(constTypeOf->mType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  10106. return CreateTypeDataRef(constTypeOf->mType);
  10107. }
  10108. if (constant->mConstType == BfConstType_PtrToInt)
  10109. {
  10110. auto fromPtrToInt = (BfConstantPtrToInt*)constant;
  10111. auto fromTarget = constHolder->GetConstantById(fromPtrToInt->mTarget);
  10112. return mBfIRBuilder->CreatePtrToInt(ConstantToCurrent(fromTarget, constHolder, NULL), fromPtrToInt->mToTypeCode);
  10113. }
  10114. if (constant->mConstType == BfConstType_IntToPtr)
  10115. {
  10116. auto fromPtrToInt = (BfConstantIntToPtr*)constant;
  10117. auto fromTarget = constHolder->GetConstantById(fromPtrToInt->mTarget);
  10118. BfIRType toIRType = fromPtrToInt->mToType;
  10119. if (toIRType.mKind == BfIRTypeData::TypeKind_TypeId)
  10120. {
  10121. auto toType = mContext->mTypes[toIRType.mId];
  10122. toIRType = mBfIRBuilder->MapType(toType);
  10123. }
  10124. return mBfIRBuilder->CreateIntToPtr(ConstantToCurrent(fromTarget, constHolder, NULL), toIRType);
  10125. }
  10126. if ((constant->mConstType == BfConstType_BitCast) || (constant->mConstType == BfConstType_BitCastNull))
  10127. {
  10128. auto bitcast = (BfConstantBitCast*)constant;
  10129. auto fromTarget = constHolder->GetConstantById(bitcast->mTarget);
  10130. BfIRType toIRType = bitcast->mToType;
  10131. if (toIRType.mKind == BfIRTypeData::TypeKind_TypeId)
  10132. {
  10133. auto toType = mContext->mTypes[toIRType.mId];
  10134. toIRType = mBfIRBuilder->MapType(toType);
  10135. }
  10136. return mBfIRBuilder->CreateBitCast(ConstantToCurrent(fromTarget, constHolder, NULL), toIRType);
  10137. }
  10138. if (constant->mConstType == BfConstType_Agg)
  10139. {
  10140. auto constArray = (BfConstantAgg*)constant;
  10141. if ((wantType == NULL) && (constArray->mType.mKind == BfIRTypeData::TypeKind_TypeId))
  10142. wantType = mContext->mTypes[constArray->mType.mId];
  10143. if (wantType->IsArray())
  10144. wantType = CreateSizedArrayType(wantType->GetUnderlyingType(), (int)constArray->mValues.mSize);
  10145. SizedArray<BfIRValue, 8> newVals;
  10146. if (wantType->IsSizedArray())
  10147. {
  10148. auto elementType = wantType->GetUnderlyingType();
  10149. for (auto val : constArray->mValues)
  10150. {
  10151. newVals.Add(ConstantToCurrent(constHolder->GetConstant(val), constHolder, elementType));
  10152. }
  10153. }
  10154. else
  10155. {
  10156. auto wantTypeInst = wantType->ToTypeInstance();
  10157. if (wantTypeInst->mBaseType != NULL)
  10158. {
  10159. auto baseVal = ConstantToCurrent(constHolder->GetConstant(constArray->mValues[0]), constHolder, wantTypeInst->mBaseType);
  10160. newVals.Add(baseVal);
  10161. }
  10162. if (wantType->IsUnion())
  10163. {
  10164. auto innerType = wantType->ToTypeInstance()->GetUnionInnerType();
  10165. if (!innerType->IsValuelessType())
  10166. {
  10167. auto val = ConstantToCurrent(constHolder->GetConstant(constArray->mValues[1]), constHolder, innerType);
  10168. newVals.Add(val);
  10169. }
  10170. }
  10171. if ((!wantType->IsUnion()) || (wantType->IsPayloadEnum()))
  10172. {
  10173. for (auto& fieldInstance : wantTypeInst->mFieldInstances)
  10174. {
  10175. if (fieldInstance.mDataIdx < 0)
  10176. continue;
  10177. auto val = constArray->mValues[fieldInstance.mDataIdx];
  10178. BfIRValue memberVal = ConstantToCurrent(constHolder->GetConstant(val), constHolder, fieldInstance.mResolvedType);
  10179. if (fieldInstance.mDataIdx == newVals.mSize)
  10180. newVals.Add(memberVal);
  10181. else
  10182. {
  10183. while (fieldInstance.mDataIdx >= newVals.mSize)
  10184. newVals.Add(BfIRValue());
  10185. newVals[fieldInstance.mDataIdx] = memberVal;
  10186. }
  10187. }
  10188. }
  10189. for (auto& val : newVals)
  10190. {
  10191. if (!val)
  10192. val = mBfIRBuilder->CreateConstArrayZero(0);
  10193. }
  10194. }
  10195. return mBfIRBuilder->CreateConstAgg(mBfIRBuilder->MapType(wantType, BfIRPopulateType_Identity), newVals);
  10196. }
  10197. return mBfIRBuilder->CreateConst(constant, constHolder);
  10198. }
  10199. void BfModule::ValidateCustomAttributes(BfCustomAttributes* customAttributes, BfAttributeTargets attrTarget)
  10200. {
  10201. if (attrTarget == BfAttributeTargets_SkipValidate)
  10202. return;
  10203. for (auto& customAttribute : customAttributes->mAttributes)
  10204. {
  10205. if (!customAttribute.mAwaitingValidation)
  10206. continue;
  10207. if ((customAttribute.mType->mAttributeData->mAttributeTargets & attrTarget) == 0)
  10208. {
  10209. Fail(StrFormat("Attribute '%s' is not valid on this declaration type. It is only valid on %s.",
  10210. customAttribute.GetRefNode()->ToString().c_str(), GetAttributesTargetListString(customAttribute.mType->mAttributeData->mAttributeTargets).c_str()), customAttribute.mRef->mAttributeTypeRef); // CS0592
  10211. }
  10212. customAttribute.mAwaitingValidation = false;
  10213. }
  10214. }
  10215. void BfModule::GetCustomAttributes(BfCustomAttributes* customAttributes, BfAttributeDirective* attributesDirective, BfAttributeTargets attrTarget, BfGetCustomAttributesFlags flags, BfCaptureInfo* captureInfo)
  10216. {
  10217. bool allowNonConstArgs = (flags & BfGetCustomAttributesFlags_AllowNonConstArgs) != 0;
  10218. bool keepConstsInModule = (flags & BfGetCustomAttributesFlags_KeepConstsInModule) != 0;
  10219. if (!mCompiler->mHasRequiredTypes)
  10220. return;
  10221. if ((attributesDirective != NULL) && (mCompiler->mResolvePassData != NULL))
  10222. {
  10223. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(attributesDirective))
  10224. sourceClassifier->VisitChild(attributesDirective);
  10225. }
  10226. SetAndRestoreValue<bool> prevIsCapturingMethodMatchInfo;
  10227. if (mCompiler->IsAutocomplete())
  10228. prevIsCapturingMethodMatchInfo.Init(mCompiler->mResolvePassData->mAutoComplete->mIsCapturingMethodMatchInfo, false);
  10229. BfTypeInstance* baseAttrTypeInst = mContext->mUnreifiedModule->ResolveTypeDef(mCompiler->mAttributeTypeDef)->ToTypeInstance();
  10230. BfAttributeTargets targetOverride = (BfAttributeTargets)0;
  10231. BfTypeDef* activeTypeDef = GetActiveTypeDef();
  10232. BfAutoComplete* autoComplete = NULL;
  10233. if (mCompiler->mResolvePassData != NULL)
  10234. autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  10235. for (; attributesDirective != NULL; attributesDirective = attributesDirective->mNextAttribute)
  10236. {
  10237. if (auto tokenNode = BfNodeDynCast<BfTokenNode>(attributesDirective->mAttributeTargetSpecifier))
  10238. {
  10239. if (captureInfo == NULL)
  10240. {
  10241. Fail("Capture specifiers can only be used in lambda allocations", tokenNode);
  10242. continue;
  10243. }
  10244. BfCaptureInfo::Entry captureEntry;
  10245. captureEntry.mCaptureType = (tokenNode->mToken == BfToken_Ampersand) ? BfCaptureType_Reference : BfCaptureType_Copy;
  10246. if (!attributesDirective->mArguments.IsEmpty())
  10247. {
  10248. captureEntry.mNameNode = BfNodeDynCast<BfIdentifierNode>(attributesDirective->mArguments[0]);
  10249. if ((captureEntry.mNameNode != NULL) && (autoComplete != NULL))
  10250. autoComplete->CheckIdentifier(captureEntry.mNameNode);
  10251. }
  10252. captureInfo->mCaptures.Add(captureEntry);
  10253. continue;
  10254. }
  10255. BfAutoParentNodeEntry autoParentNodeEntry(this, attributesDirective);
  10256. BfCustomAttribute customAttribute;
  10257. customAttribute.mAwaitingValidation = true;
  10258. customAttribute.mDeclaringType = activeTypeDef;
  10259. customAttribute.mRef = attributesDirective;
  10260. if (attributesDirective->mAttrOpenToken != NULL)
  10261. targetOverride = (BfAttributeTargets)0;
  10262. if (attributesDirective->mAttributeTypeRef == NULL)
  10263. {
  10264. AssertErrorState();
  10265. continue;
  10266. }
  10267. BfType* attrType;
  10268. if (mContext->mCurTypeState != NULL)
  10269. {
  10270. SetAndRestoreValue<BfTypeReference*> prevTypeRef(mContext->mCurTypeState->mCurAttributeTypeRef, attributesDirective->mAttributeTypeRef);
  10271. attrType = ResolveTypeRef(attributesDirective->mAttributeTypeRef, BfPopulateType_Identity, (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_Attribute | BfResolveTypeRefFlag_NoReify));
  10272. }
  10273. else
  10274. {
  10275. attrType = ResolveTypeRef(attributesDirective->mAttributeTypeRef, BfPopulateType_Identity, (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_Attribute | BfResolveTypeRefFlag_NoReify));
  10276. }
  10277. BfTypeDef* attrTypeDef = NULL;
  10278. if ((attrType != NULL) && (attrType->IsTypeInstance()))
  10279. attrTypeDef = attrType->ToTypeInstance()->mTypeDef;
  10280. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  10281. {
  10282. mCompiler->mResolvePassData->mAutoComplete->CheckAttributeTypeRef(attributesDirective->mAttributeTypeRef);
  10283. if (attrTypeDef != NULL)
  10284. mCompiler->mResolvePassData->HandleTypeReference(attributesDirective->mAttributeTypeRef, attrTypeDef);
  10285. }
  10286. bool isBypassedAttr = false;
  10287. if (attrTypeDef != NULL)
  10288. {
  10289. // 'Object' has some dependencies on some attributes, but those attributes are classes so we have a circular dependency issue
  10290. // We solve it by having a 'bypass' for known attributes that Object depends on
  10291. if ((attributesDirective->mArguments.empty()) && (autoComplete == NULL) && (attrType != NULL) && (attrType->IsTypeInstance()))
  10292. {
  10293. if (attrType->IsInstanceOf(mCompiler->mCReprAttributeTypeDef))
  10294. {
  10295. for (auto methodDef : attrTypeDef->mMethods)
  10296. {
  10297. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mProtection == BfProtection_Public))
  10298. {
  10299. customAttribute.mType = attrType->ToTypeInstance();
  10300. customAttribute.mCtor = methodDef;
  10301. isBypassedAttr = true;
  10302. break;
  10303. }
  10304. }
  10305. }
  10306. }
  10307. if (isBypassedAttr)
  10308. {
  10309. customAttribute.mAwaitingValidation = false;
  10310. customAttributes->mAttributes.push_back(customAttribute);
  10311. continue;
  10312. }
  10313. SetAndRestoreValue<BfTypeInstance*> prevCurTypeInst(mContext->mUnreifiedModule->mCurTypeInstance, mCurTypeInstance);
  10314. SetAndRestoreValue<BfMethodInstance*> prevCurMethodInst(mContext->mUnreifiedModule->mCurMethodInstance, mCurMethodInstance);
  10315. if (mContext->mCurTypeState != NULL)
  10316. {
  10317. SetAndRestoreValue<BfTypeReference*> prevTypeRef(mContext->mCurTypeState->mCurAttributeTypeRef, attributesDirective->mAttributeTypeRef);
  10318. mContext->mUnreifiedModule->ResolveTypeResult(attributesDirective->mAttributeTypeRef, attrType, BfPopulateType_BaseType, (BfResolveTypeRefFlags)0);
  10319. }
  10320. else
  10321. {
  10322. mContext->mUnreifiedModule->ResolveTypeResult(attributesDirective->mAttributeTypeRef, attrType, BfPopulateType_BaseType, (BfResolveTypeRefFlags)0);
  10323. }
  10324. }
  10325. BfTypeInstance* attrTypeInst = NULL;
  10326. if (attrType == NULL)
  10327. continue;
  10328. attrTypeInst = attrType->ToTypeInstance();
  10329. if ((attrTypeInst != NULL) && (attrTypeInst->mDefineState != BfTypeDefineState_DefinedAndMethodsSlotting))
  10330. mContext->mUnreifiedModule->PopulateType(attrType, BfPopulateType_DataAndMethods);
  10331. if ((attrTypeInst == NULL) || (!TypeIsSubTypeOf(attrTypeInst, baseAttrTypeInst)) || (attrTypeInst->mAttributeData == NULL))
  10332. {
  10333. Fail(StrFormat("'%s' is not an attribute class", TypeToString(attrType).c_str()), attributesDirective->mAttributeTypeRef); //CS0616
  10334. continue;
  10335. }
  10336. if ((mIsReified) && (attrTypeInst->mAttributeData != NULL) && ((attrTypeInst->mAttributeData->mFlags & BfAttributeFlag_ReflectAttribute) != 0))
  10337. {
  10338. // Reify attribute
  10339. PopulateType(attrTypeInst);
  10340. }
  10341. if (mCurTypeInstance != NULL)
  10342. AddDependency(attrTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  10343. customAttribute.mType = attrTypeInst;
  10344. bool allocatedMethodState = NULL;
  10345. defer(
  10346. {
  10347. if (allocatedMethodState)
  10348. {
  10349. delete mCurMethodState;
  10350. mCurMethodState = NULL;
  10351. }
  10352. });
  10353. if (mCurMethodState == NULL)
  10354. {
  10355. allocatedMethodState = true;
  10356. mCurMethodState = new BfMethodState();
  10357. mCurMethodState->mTempKind = BfMethodState::TempKind_Static;
  10358. }
  10359. BfConstResolver constResolver(this);
  10360. if (allowNonConstArgs)
  10361. constResolver.mBfEvalExprFlags = (BfEvalExprFlags)(constResolver.mBfEvalExprFlags | BfEvalExprFlags_AllowNonConst);
  10362. bool inPropSet = false;
  10363. SizedArray<BfResolvedArg, 2> argValues;
  10364. for (BfExpression* arg : attributesDirective->mArguments)
  10365. {
  10366. if (arg == NULL)
  10367. {
  10368. continue;
  10369. }
  10370. if (autoComplete != NULL)
  10371. autoComplete->mShowAttributeProperties = attrTypeInst;
  10372. if (auto assignExpr = BfNodeDynCast<BfAssignmentExpression>(arg))
  10373. {
  10374. inPropSet = true;
  10375. if (autoComplete != NULL)
  10376. autoComplete->CheckNode(assignExpr->mLeft, true);
  10377. String findName = assignExpr->mLeft->ToString();
  10378. BfPropertyDef* bestProp = NULL;
  10379. BfTypeInstance* bestPropTypeInst = NULL;
  10380. BfFieldDef* bestField = NULL;
  10381. BfTypeInstance* bestFieldTypeInst = NULL;
  10382. auto checkTypeInst = attrTypeInst;
  10383. while (checkTypeInst != NULL)
  10384. {
  10385. mContext->mUnreifiedModule->PopulateType(checkTypeInst, BfPopulateType_Data);
  10386. for (auto prop : checkTypeInst->mTypeDef->mProperties)
  10387. {
  10388. if (prop->mName == findName)
  10389. {
  10390. if ((bestProp == NULL) || (bestProp->mProtection != BfProtection_Public))
  10391. {
  10392. bestProp = prop;
  10393. bestPropTypeInst = checkTypeInst;
  10394. }
  10395. }
  10396. }
  10397. for (auto field : checkTypeInst->mTypeDef->mFields)
  10398. {
  10399. if (field->mName == findName)
  10400. {
  10401. if ((bestField == NULL) || (bestField->mProtection != BfProtection_Public))
  10402. {
  10403. bestField = field;
  10404. bestFieldTypeInst = checkTypeInst;
  10405. }
  10406. }
  10407. }
  10408. if ((bestProp != NULL) || (bestField != NULL))
  10409. break;
  10410. checkTypeInst = checkTypeInst->mBaseType;
  10411. }
  10412. bool handledExpr = false;
  10413. if (bestField != NULL)
  10414. {
  10415. handledExpr = true;
  10416. if (mCompiler->mResolvePassData != NULL)
  10417. {
  10418. mCompiler->mResolvePassData->HandleFieldReference(assignExpr->mLeft, attrTypeDef, bestField);
  10419. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(assignExpr->mLeft)))
  10420. {
  10421. autoComplete->mDefField = bestField;
  10422. autoComplete->mDefType = attrTypeDef;
  10423. }
  10424. }
  10425. if (bestField->mProtection != BfProtection_Public)
  10426. Fail(StrFormat("'%s.%s' is inaccessible due to its protection level", TypeToString(bestFieldTypeInst).c_str(), findName.c_str()), assignExpr->mLeft); // CS0122
  10427. AddDependency(bestFieldTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  10428. BfCustomAttributeSetField setField;
  10429. setField.mFieldRef = BfFieldRef(bestFieldTypeInst, bestField);
  10430. auto& fieldTypeInst = checkTypeInst->mFieldInstances[bestField->mIdx];
  10431. if (assignExpr->mRight != NULL)
  10432. {
  10433. BfTypedValue result = constResolver.Resolve(assignExpr->mRight, fieldTypeInst.mResolvedType, BfConstResolveFlag_NoActualizeValues);
  10434. if (result)
  10435. {
  10436. if (!keepConstsInModule)
  10437. CurrentAddToConstHolder(result.mValue);
  10438. setField.mParam = result;
  10439. customAttribute.mSetField.push_back(setField);
  10440. }
  10441. }
  10442. }
  10443. else if (bestProp == NULL)
  10444. {
  10445. Fail(StrFormat("'%s' does not contain a field or property named '%s'", TypeToString(attrTypeInst).c_str(), findName.c_str()), assignExpr->mLeft);
  10446. }
  10447. else
  10448. {
  10449. BfMethodDef* setMethod = NULL;
  10450. for (auto methodDef : bestProp->mMethods)
  10451. {
  10452. if (methodDef->mMethodType == BfMethodType_PropertySetter)
  10453. {
  10454. setMethod = methodDef;
  10455. break;
  10456. }
  10457. }
  10458. if (setMethod == NULL)
  10459. {
  10460. Fail("Property has no setter", assignExpr->mLeft);
  10461. }
  10462. else
  10463. {
  10464. if (mCompiler->mResolvePassData != NULL)
  10465. {
  10466. mCompiler->mResolvePassData->HandlePropertyReference(assignExpr->mLeft, attrTypeDef, bestProp);
  10467. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(assignExpr->mLeft)))
  10468. {
  10469. autoComplete->mDefProp = bestProp;
  10470. autoComplete->mDefType = attrTypeDef;
  10471. }
  10472. }
  10473. handledExpr = true;
  10474. if (bestProp->mProtection != BfProtection_Public)
  10475. Fail(StrFormat("'%s.%s' is inaccessible due to its protection level", TypeToString(bestPropTypeInst).c_str(), findName.c_str()), assignExpr->mLeft); // CS0122
  10476. BfResolvedArg resolvedArg;
  10477. AddDependency(bestPropTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  10478. BfCustomAttributeSetProperty setProperty;
  10479. setProperty.mPropertyRef = BfPropertyRef(bestPropTypeInst, bestProp);
  10480. // We don't actually need the mFunc, so get the ModuleMethodInstance from the native module
  10481. auto methodInstance = bestPropTypeInst->mModule->GetMethodInstance(bestPropTypeInst, setMethod, BfTypeVector());
  10482. if (methodInstance.mMethodInstance != NULL)
  10483. {
  10484. auto propType = methodInstance.mMethodInstance->GetParamType(0);
  10485. if (assignExpr->mRight != NULL)
  10486. {
  10487. BfTypedValue result = constResolver.Resolve(assignExpr->mRight, propType, BfConstResolveFlag_NoActualizeValues);
  10488. if ((result) && (!result.mType->IsVar()))
  10489. {
  10490. if (!result.mValue.IsConst())
  10491. result = GetDefaultTypedValue(result.mType);
  10492. BF_ASSERT(result.mType == propType);
  10493. if (!keepConstsInModule)
  10494. CurrentAddToConstHolder(result.mValue);
  10495. setProperty.mParam = result;
  10496. customAttribute.mSetProperties.push_back(setProperty);
  10497. }
  10498. }
  10499. }
  10500. }
  10501. }
  10502. if ((!handledExpr) && (assignExpr->mRight != NULL))
  10503. constResolver.Resolve(assignExpr->mRight, NULL, BfConstResolveFlag_NoActualizeValues);
  10504. }
  10505. else
  10506. {
  10507. if (inPropSet)
  10508. {
  10509. Fail("Named attribute argument expected", arg); // CS1016
  10510. }
  10511. BfDeferEvalChecker deferEvalChecker;
  10512. arg->Accept(&deferEvalChecker);
  10513. bool deferParamEval = deferEvalChecker.mNeedsDeferEval;
  10514. BfResolvedArg resolvedArg;
  10515. resolvedArg.mExpression = arg;
  10516. if (deferParamEval)
  10517. {
  10518. resolvedArg.mArgFlags = BfArgFlag_DeferredEval;
  10519. }
  10520. else
  10521. resolvedArg.mTypedValue = constResolver.Resolve(arg, NULL, BfConstResolveFlag_NoActualizeValues);
  10522. if (!inPropSet)
  10523. {
  10524. argValues.push_back(resolvedArg);
  10525. }
  10526. }
  10527. if (autoComplete != NULL)
  10528. autoComplete->mShowAttributeProperties = NULL;
  10529. }
  10530. auto wasCapturingMethodInfo = false;
  10531. if (autoComplete != NULL)
  10532. {
  10533. wasCapturingMethodInfo = autoComplete->mIsCapturingMethodMatchInfo;
  10534. if (attributesDirective->mCtorOpenParen != NULL)
  10535. autoComplete->CheckInvocation(attributesDirective, attributesDirective->mCtorOpenParen, attributesDirective->mCtorCloseParen, attributesDirective->mCommas);
  10536. }
  10537. BfMethodMatcher methodMatcher(attributesDirective, this, "", argValues, BfMethodGenericArguments());
  10538. methodMatcher.mBfEvalExprFlags = constResolver.mBfEvalExprFlags;
  10539. attrTypeDef = attrTypeInst->mTypeDef;
  10540. bool success = true;
  10541. bool isFailurePass = false;
  10542. for (int pass = 0; pass < 2; pass++)
  10543. {
  10544. bool isFailurePass = pass == 1;
  10545. for (auto checkMethod : attrTypeDef->mMethods)
  10546. {
  10547. if ((isFailurePass) && (checkMethod->mMethodDeclaration == NULL))
  10548. continue; // Don't match private default ctor if there's a user-defined one
  10549. if ((checkMethod->mIsStatic) || (checkMethod->mMethodType != BfMethodType_Ctor))
  10550. continue;
  10551. if ((!isFailurePass) && (!CheckProtection(checkMethod->mProtection, attrTypeInst->mTypeDef, false, false)))
  10552. continue;
  10553. methodMatcher.CheckMethod(NULL, attrTypeInst, checkMethod, isFailurePass);
  10554. }
  10555. if ((methodMatcher.mBestMethodDef != NULL) || (methodMatcher.mBackupMethodDef != NULL))
  10556. break;
  10557. }
  10558. if (autoComplete != NULL)
  10559. {
  10560. if ((wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo))
  10561. {
  10562. autoComplete->mIsCapturingMethodMatchInfo = true;
  10563. BF_ASSERT(autoComplete->mMethodMatchInfo != NULL);
  10564. }
  10565. else
  10566. autoComplete->mIsCapturingMethodMatchInfo = false;
  10567. }
  10568. if (methodMatcher.mBestMethodDef == NULL)
  10569. methodMatcher.mBestMethodDef = methodMatcher.mBackupMethodDef;
  10570. BF_ASSERT(methodMatcher.mBestMethodDef != NULL);
  10571. customAttribute.mCtor = methodMatcher.mBestMethodDef;
  10572. if (methodMatcher.mBestMethodTypeInstance == mCurTypeInstance)
  10573. {
  10574. Fail("Custom attribute circular reference", attributesDirective);
  10575. }
  10576. if (mCurTypeInstance != NULL)
  10577. AddDependency(methodMatcher.mBestMethodTypeInstance, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  10578. if (!constResolver.PrepareMethodArguments(attributesDirective->mAttributeTypeRef, &methodMatcher, customAttribute.mCtorArgs))
  10579. success = false;
  10580. for (auto& arg : argValues)
  10581. {
  10582. if ((arg.mArgFlags & BfArgFlag_DeferredEval) != 0)
  10583. {
  10584. if (auto expr = BfNodeDynCast<BfExpression>(arg.mExpression))
  10585. constResolver.Resolve(expr, NULL, BfConstResolveFlag_NoActualizeValues);
  10586. }
  10587. }
  10588. // Move all those to the constHolder
  10589. if (!keepConstsInModule)
  10590. {
  10591. for (auto& ctorArg : customAttribute.mCtorArgs)
  10592. {
  10593. if (ctorArg.IsConst())
  10594. CurrentAddToConstHolder(ctorArg);
  10595. }
  10596. }
  10597. if (attributesDirective->mAttributeTargetSpecifier != NULL)
  10598. {
  10599. targetOverride = BfAttributeTargets_ReturnValue;
  10600. if (attrTarget != BfAttributeTargets_Method)
  10601. {
  10602. 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.",
  10603. GetAttributesTargetListString(targetOverride).c_str(), GetAttributesTargetListString(attrTarget).c_str()), attributesDirective->mAttributeTargetSpecifier); // CS0657
  10604. success = false;
  10605. }
  10606. }
  10607. if ((success) && (targetOverride != (BfAttributeTargets)0))
  10608. {
  10609. if ((mCurMethodInstance != NULL) && (targetOverride == BfAttributeTargets_ReturnValue) && (attrTarget == BfAttributeTargets_Method))
  10610. {
  10611. auto methodInfoEx = mCurMethodInstance->GetMethodInfoEx();
  10612. if (methodInfoEx->mMethodCustomAttributes == NULL)
  10613. methodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  10614. if (success)
  10615. {
  10616. if (methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes == NULL)
  10617. methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes = new BfCustomAttributes();
  10618. methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes->mAttributes.push_back(customAttribute);
  10619. }
  10620. }
  10621. // Mark as failed since we don't actually want to add this to the custom attributes set
  10622. success = false;
  10623. }
  10624. if (success)
  10625. {
  10626. if ((attrTypeInst->mAttributeData->mFlags & BfAttributeFlag_DisallowAllowMultiple) != 0)
  10627. {
  10628. for (auto& prevCustomAttribute : customAttributes->mAttributes)
  10629. {
  10630. if (prevCustomAttribute.mType == attrTypeInst)
  10631. {
  10632. Fail(StrFormat("Duplicate '%s' attribute", attributesDirective->mAttributeTypeRef->ToCleanAttributeString().c_str()), attributesDirective->mAttributeTypeRef); // CS0579
  10633. }
  10634. }
  10635. }
  10636. }
  10637. if (success)
  10638. {
  10639. customAttributes->mAttributes.push_back(customAttribute);
  10640. }
  10641. }
  10642. ValidateCustomAttributes(customAttributes, attrTarget);
  10643. }
  10644. BfCustomAttributes* BfModule::GetCustomAttributes(BfAttributeDirective* attributesDirective, BfAttributeTargets attrType, BfGetCustomAttributesFlags flags, BfCaptureInfo* captureInfo)
  10645. {
  10646. BfCustomAttributes* customAttributes = new BfCustomAttributes();
  10647. GetCustomAttributes(customAttributes, attributesDirective, attrType, flags, captureInfo);
  10648. return customAttributes;
  10649. }
  10650. BfCustomAttributes* BfModule::GetCustomAttributes(BfTypeDef* typeDef)
  10651. {
  10652. BF_ASSERT(mCompiler->IsAutocomplete());
  10653. BfAttributeTargets attrTarget;
  10654. if (typeDef->mIsDelegate)
  10655. attrTarget = BfAttributeTargets_Delegate;
  10656. else if (typeDef->mIsFunction)
  10657. attrTarget = BfAttributeTargets_Function;
  10658. else if (typeDef->mTypeCode == BfTypeCode_Enum)
  10659. attrTarget = BfAttributeTargets_Enum;
  10660. else if (typeDef->mTypeCode == BfTypeCode_Interface)
  10661. attrTarget = BfAttributeTargets_Interface;
  10662. else if (typeDef->mTypeCode == BfTypeCode_Struct)
  10663. attrTarget = BfAttributeTargets_Struct;
  10664. else
  10665. attrTarget = BfAttributeTargets_Class;
  10666. return GetCustomAttributes(typeDef->mTypeDeclaration->mAttributes, attrTarget);
  10667. }
  10668. void BfModule::FinishAttributeState(BfAttributeState* attributeState)
  10669. {
  10670. if ((!attributeState->mUsed) && (attributeState->mSrc != NULL))
  10671. Warn(0, "Unused attributes", attributeState->mSrc);
  10672. }
  10673. void BfModule::ProcessTypeInstCustomAttributes(int& packing, bool& isUnion, bool& isCRepr, bool& isOrdered, int& alignOverride, BfType*& underlyingArrayType, int& underlyingArraySize)
  10674. {
  10675. if (mCurTypeInstance->mTypeDef->mIsAlwaysInclude)
  10676. mCurTypeInstance->mAlwaysIncludeFlags = (BfAlwaysIncludeFlags)(mCurTypeInstance->mAlwaysIncludeFlags | BfAlwaysIncludeFlag_Type);
  10677. if (mCurTypeInstance->mCustomAttributes != NULL)
  10678. {
  10679. for (auto& customAttribute : mCurTypeInstance->mCustomAttributes->mAttributes)
  10680. {
  10681. String typeName = TypeToString(customAttribute.mType);
  10682. if (typeName == "System.PackedAttribute")
  10683. {
  10684. packing = 1;
  10685. if (customAttribute.mCtorArgs.size() >= 1)
  10686. {
  10687. auto alignConstant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  10688. int checkPacking = alignConstant->mInt32;
  10689. if (((checkPacking & (checkPacking - 1)) == 0) && (packing > 0) && (packing < 256))
  10690. packing = checkPacking;
  10691. else
  10692. Fail("Packing must be a power of 2", customAttribute.GetRefNode());
  10693. }
  10694. }
  10695. else if (typeName == "System.UnionAttribute")
  10696. {
  10697. isUnion = true;
  10698. }
  10699. else if (typeName == "System.CReprAttribute")
  10700. {
  10701. isCRepr = true;
  10702. isOrdered = true;
  10703. }
  10704. else if (typeName == "System.OrderedAttribute")
  10705. {
  10706. isOrdered = true;
  10707. }
  10708. else if (typeName == "System.AlwaysIncludeAttribute")
  10709. {
  10710. mCurTypeInstance->mAlwaysIncludeFlags = (BfAlwaysIncludeFlags)(mCurTypeInstance->mAlwaysIncludeFlags | BfAlwaysIncludeFlag_Type);
  10711. for (auto setProp : customAttribute.mSetProperties)
  10712. {
  10713. BfPropertyDef* propertyDef = setProp.mPropertyRef;
  10714. if (propertyDef->mName == "AssumeInstantiated")
  10715. {
  10716. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  10717. if ((constant != NULL) && (constant->mBool))
  10718. mCurTypeInstance->mAlwaysIncludeFlags = (BfAlwaysIncludeFlags)(mCurTypeInstance->mAlwaysIncludeFlags | BfAlwaysIncludeFlag_AssumeInstantiated);
  10719. }
  10720. else if (propertyDef->mName == "IncludeAllMethods")
  10721. {
  10722. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  10723. if ((constant != NULL) && (constant->mBool))
  10724. mCurTypeInstance->mAlwaysIncludeFlags = (BfAlwaysIncludeFlags)(mCurTypeInstance->mAlwaysIncludeFlags | BfAlwaysIncludeFlag_IncludeAllMethods);
  10725. }
  10726. }
  10727. }
  10728. else if (typeName == "System.AlignAttribute")
  10729. {
  10730. if (customAttribute.mCtorArgs.size() >= 1)
  10731. {
  10732. auto alignConstant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  10733. int checkAlign = alignConstant->mInt32;
  10734. if ((checkAlign & (checkAlign - 1)) == 0)
  10735. alignOverride = checkAlign;
  10736. else
  10737. Fail("Alignment must be a power of 2", customAttribute.GetRefNode());
  10738. }
  10739. }
  10740. else if (typeName == "System.UnderlyingArrayAttribute")
  10741. {
  10742. if (customAttribute.mCtorArgs.size() >= 2)
  10743. {
  10744. auto typeConstant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  10745. auto sizeConstant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[1]);
  10746. if ((typeConstant != NULL) && (sizeConstant != NULL) && (typeConstant->mConstType == BfConstType_TypeOf))
  10747. {
  10748. underlyingArrayType = (BfType*)(intptr)typeConstant->mInt64;
  10749. underlyingArraySize = sizeConstant->mInt32;
  10750. }
  10751. }
  10752. }
  10753. if (customAttribute.mType->mAttributeData == NULL)
  10754. PopulateType(customAttribute.mType);
  10755. BF_ASSERT(customAttribute.mType->mAttributeData != NULL);
  10756. if ((customAttribute.mType->mAttributeData != NULL) && ((customAttribute.mType->mAttributeData->mAlwaysIncludeUser & BfAlwaysIncludeFlag_AssumeInstantiated) != 0))
  10757. mCurTypeInstance->mAlwaysIncludeFlags = (BfAlwaysIncludeFlags)(mCurTypeInstance->mAlwaysIncludeFlags | customAttribute.mType->mAttributeData->mAlwaysIncludeUser);
  10758. }
  10759. }
  10760. }
  10761. // Checking to see if we're an attribute or not
  10762. void BfModule::ProcessCustomAttributeData()
  10763. {
  10764. if (mCurTypeInstance->mAttributeData != NULL)
  10765. return;
  10766. bool isAttribute = false;
  10767. auto checkTypeInst = mCurTypeInstance->mBaseType;
  10768. while (checkTypeInst != NULL)
  10769. {
  10770. if (checkTypeInst->IsInstanceOf(mCompiler->mAttributeTypeDef))
  10771. isAttribute = true;
  10772. checkTypeInst = checkTypeInst->mBaseType;
  10773. }
  10774. if (!isAttribute)
  10775. return;
  10776. auto attributeData = new BfAttributeData();
  10777. bool hasCustomAttribute = false;
  10778. if (mCurTypeInstance->mCustomAttributes != NULL)
  10779. {
  10780. for (auto& customAttribute : mCurTypeInstance->mCustomAttributes->mAttributes)
  10781. {
  10782. if (customAttribute.mType->IsInstanceOf(mCompiler->mAttributeUsageAttributeTypeDef))
  10783. {
  10784. if (customAttribute.mCtorArgs.size() > 0)
  10785. {
  10786. auto constant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  10787. if ((constant != NULL) && (mBfIRBuilder->IsInt(constant->mTypeCode)))
  10788. attributeData->mAttributeTargets = (BfAttributeTargets)constant->mInt32;
  10789. }
  10790. if (customAttribute.mCtorArgs.size() == 2)
  10791. {
  10792. auto constant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  10793. if ((constant != NULL) && (mBfIRBuilder->IsInt(constant->mTypeCode)))
  10794. {
  10795. attributeData->mFlags = (BfAttributeFlags)constant->mInt32;
  10796. }
  10797. }
  10798. for (auto& setProp : customAttribute.mSetProperties)
  10799. {
  10800. BfPropertyDef* propDef = setProp.mPropertyRef;
  10801. if (propDef->mName == "AllowMultiple")
  10802. {
  10803. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  10804. if ((constant != NULL) && (constant->mBool))
  10805. attributeData->mFlags = (BfAttributeFlags)(attributeData->mFlags & ~BfAttributeFlag_DisallowAllowMultiple);
  10806. else
  10807. attributeData->mFlags = (BfAttributeFlags)(attributeData->mFlags | BfAttributeFlag_DisallowAllowMultiple);
  10808. }
  10809. else if (propDef->mName == "Inherited")
  10810. {
  10811. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  10812. if ((constant != NULL) && (constant->mBool))
  10813. attributeData->mFlags = (BfAttributeFlags)(attributeData->mFlags & ~BfAttributeFlag_NotInherited);
  10814. else
  10815. attributeData->mFlags = (BfAttributeFlags)(attributeData->mFlags | BfAttributeFlag_NotInherited);
  10816. }
  10817. else if (propDef->mName == "ValidOn")
  10818. {
  10819. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  10820. if (constant != NULL)
  10821. attributeData->mAttributeTargets = (BfAttributeTargets)constant->mInt32;
  10822. }
  10823. else if (propDef->mName == "AlwaysIncludeUser")
  10824. {
  10825. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  10826. if (constant != NULL)
  10827. attributeData->mAlwaysIncludeUser = (BfAlwaysIncludeFlags)constant->mInt32;
  10828. }
  10829. }
  10830. hasCustomAttribute = true;
  10831. }
  10832. }
  10833. }
  10834. if ((!hasCustomAttribute) && (mCurTypeInstance->mBaseType->mAttributeData != NULL))
  10835. {
  10836. attributeData->mAttributeTargets = mCurTypeInstance->mBaseType->mAttributeData->mAttributeTargets;
  10837. attributeData->mFlags = mCurTypeInstance->mBaseType->mAttributeData->mFlags;
  10838. attributeData->mAlwaysIncludeUser = mCurTypeInstance->mBaseType->mAttributeData->mAlwaysIncludeUser;
  10839. }
  10840. mCurTypeInstance->mAttributeData = attributeData;
  10841. }
  10842. bool BfModule::TryGetConstString(BfIRConstHolder* constHolder, BfIRValue irValue, StringImpl& str)
  10843. {
  10844. auto constant = constHolder->GetConstant(irValue);
  10845. if (constant == NULL)
  10846. return false;
  10847. if (constant->mTypeCode != BfTypeCode_StringId)
  10848. return false;
  10849. int stringId = constant->mInt32;
  10850. BfStringPoolEntry* entry = NULL;
  10851. if (mContext->mStringObjectIdMap.TryGetValue(stringId, &entry))
  10852. {
  10853. str += entry->mString;
  10854. }
  10855. else
  10856. {
  10857. BF_DBG_FATAL("Failed to find string by id");
  10858. }
  10859. return true;
  10860. }
  10861. BfVariant BfModule::TypedValueToVariant(BfAstNode* refNode, const BfTypedValue& value, bool allowUndef)
  10862. {
  10863. BfVariant variant;
  10864. variant.mTypeCode = BfTypeCode_None;
  10865. BfType* primType = NULL;
  10866. if (value.mType->IsPrimitiveType())
  10867. primType = (BfPrimitiveType*)value.mType;
  10868. else if (value.mType->IsTypedPrimitive())
  10869. primType = value.mType->GetUnderlyingType();
  10870. else if (value.mType->IsInstanceOf(mCompiler->mStringTypeDef))
  10871. primType = value.mType;
  10872. if (primType)
  10873. {
  10874. auto constant = mBfIRBuilder->GetConstant(value.mValue);
  10875. if (constant != NULL)
  10876. {
  10877. if ((allowUndef) && (constant->mConstType == BfConstType_Undef))
  10878. {
  10879. variant.mUInt64 = 0;
  10880. variant.mTypeCode = BfTypeCode_Let;
  10881. return variant;
  10882. }
  10883. if (constant->mConstType == BfConstType_GlobalVar)
  10884. {
  10885. int stringIdx = GetStringPoolIdx(value.mValue, mBfIRBuilder);
  10886. if (stringIdx != -1)
  10887. {
  10888. variant.mTypeCode = BfTypeCode_StringId;
  10889. variant.mInt64 = stringIdx;
  10890. return variant;
  10891. }
  10892. }
  10893. switch (constant->mTypeCode)
  10894. {
  10895. case BfTypeCode_Boolean:
  10896. case BfTypeCode_Int8:
  10897. case BfTypeCode_UInt8:
  10898. case BfTypeCode_Int16:
  10899. case BfTypeCode_UInt16:
  10900. case BfTypeCode_Int32:
  10901. case BfTypeCode_UInt32:
  10902. case BfTypeCode_Int64:
  10903. case BfTypeCode_UInt64:
  10904. case BfTypeCode_IntPtr:
  10905. case BfTypeCode_UIntPtr:
  10906. case BfTypeCode_IntUnknown:
  10907. case BfTypeCode_UIntUnknown:
  10908. case BfTypeCode_Double:
  10909. case BfTypeCode_Char8:
  10910. case BfTypeCode_Char16:
  10911. case BfTypeCode_Char32:
  10912. case BfTypeCode_StringId:
  10913. variant.mTypeCode = constant->mTypeCode;
  10914. variant.mInt64 = constant->mInt64;
  10915. break;
  10916. case BfTypeCode_Float:
  10917. variant.mTypeCode = constant->mTypeCode;
  10918. variant.mSingle = (float)constant->mDouble;
  10919. break;
  10920. default:
  10921. if (refNode != NULL)
  10922. Fail("Invalid const expression type", refNode);
  10923. break;
  10924. }
  10925. }
  10926. }
  10927. return variant;
  10928. }
  10929. BfTypedValue BfModule::RemoveRef(BfTypedValue typedValue)
  10930. {
  10931. if ((typedValue.mType != NULL) && (typedValue.mType->IsRef()))
  10932. {
  10933. auto refType = (BfRefType*)typedValue.mType;
  10934. auto elementType = typedValue.mType->GetUnderlyingType();
  10935. if (typedValue.IsAddr())
  10936. {
  10937. if (elementType->IsValuelessType())
  10938. {
  10939. BF_ASSERT(!typedValue.mValue);
  10940. typedValue = BfTypedValue(typedValue.mValue, elementType, true);
  10941. }
  10942. else
  10943. typedValue = BfTypedValue(mBfIRBuilder->CreateAlignedLoad(typedValue.mValue, elementType->mAlign), elementType, true);
  10944. }
  10945. else
  10946. typedValue = BfTypedValue(typedValue.mValue, elementType, true);
  10947. if (typedValue.mType->IsValuelessType())
  10948. {
  10949. BF_ASSERT(typedValue.mValue.IsFake());
  10950. }
  10951. if (refType->mRefKind == BfRefType::RefKind_In)
  10952. {
  10953. if (typedValue.mKind == BfTypedValueKind_Addr)
  10954. typedValue.mKind = BfTypedValueKind_ReadOnlyAddr;
  10955. }
  10956. }
  10957. return typedValue;
  10958. }
  10959. BfTypedValue BfModule::SanitizeAddr(BfTypedValue typedValue)
  10960. {
  10961. if (!typedValue)
  10962. return typedValue;
  10963. if (typedValue.mType->IsRef())
  10964. {
  10965. typedValue = LoadValue(typedValue);
  10966. auto copiedVal = BfTypedValue(CreateAlloca(typedValue.mType), typedValue.mType, true);
  10967. mBfIRBuilder->CreateStore(typedValue.mValue, copiedVal.mValue);
  10968. return copiedVal;
  10969. }
  10970. return typedValue;
  10971. }
  10972. BfTypedValue BfModule::ToRef(BfTypedValue typedValue, BfRefType* refType)
  10973. {
  10974. if (refType == NULL)
  10975. refType = CreateRefType(typedValue.mType);
  10976. if ((refType->mRefKind == BfRefType::RefKind_Mut) && (typedValue.mType->IsObjectOrInterface()))
  10977. {
  10978. return LoadValue(typedValue);
  10979. }
  10980. if (refType->mRefKind == BfRefType::RefKind_Mut)
  10981. refType = CreateRefType(typedValue.mType);
  10982. if (!typedValue.mType->IsValuelessType())
  10983. typedValue = MakeAddressable(typedValue, false, true);
  10984. return BfTypedValue(typedValue.mValue, refType);
  10985. }
  10986. BfTypedValue BfModule::LoadValue(BfTypedValue typedValue, BfAstNode* refNode, bool isVolatile)
  10987. {
  10988. if (!typedValue.IsAddr())
  10989. return typedValue;
  10990. PopulateType(typedValue.mType);
  10991. if ((typedValue.mType->IsValuelessType()) || (typedValue.mType->IsVar()))
  10992. return BfTypedValue(mBfIRBuilder->GetFakeVal(), typedValue.mType, false);
  10993. if (typedValue.mValue.IsConst())
  10994. {
  10995. auto constantValue = mBfIRBuilder->GetConstant(typedValue.mValue);
  10996. if (constantValue != NULL)
  10997. {
  10998. if (constantValue->mConstType == BfConstType_GlobalVar)
  10999. {
  11000. auto globalVar = (BfGlobalVar*)constantValue;
  11001. if (globalVar->mName[0] == '#')
  11002. {
  11003. BfTypedValue result = GetCompilerFieldValue(globalVar->mName);
  11004. if (result)
  11005. {
  11006. // We want to avoid 'unreachable code' issues from values that
  11007. // are technically constant but change depending on compilation context
  11008. if (mCurMethodState != NULL)
  11009. {
  11010. auto checkScope = mCurMethodState->mCurScope;
  11011. while (checkScope != NULL)
  11012. {
  11013. checkScope->mSupressNextUnreachable = true;
  11014. checkScope = checkScope->mPrevScope;
  11015. }
  11016. }
  11017. return result;
  11018. }
  11019. if (!mIsComptimeModule)
  11020. return GetDefaultTypedValue(typedValue.mType);
  11021. }
  11022. }
  11023. if ((mIsComptimeModule) && (mCompiler->mCeMachine->mDebugger != NULL) && (mCompiler->mCeMachine->mDebugger->mCurDbgState != NULL))
  11024. {
  11025. auto ceDebugger = mCompiler->mCeMachine->mDebugger;
  11026. auto ceContext = ceDebugger->mCurDbgState->mCeContext;
  11027. auto activeFrame = ceDebugger->mCurDbgState->mActiveFrame;
  11028. auto ceTypedValue = ceDebugger->GetAddr(constantValue);
  11029. if (ceTypedValue)
  11030. {
  11031. if ((typedValue.mType->IsObjectOrInterface()) || (typedValue.mType->IsPointer()) || (typedValue.mType->IsRef()))
  11032. {
  11033. void* data = ceContext->GetMemoryPtr((addr_ce)ceTypedValue.mAddr, sizeof(addr_ce));
  11034. if (data == NULL)
  11035. {
  11036. Fail("Invalid address", refNode);
  11037. return GetDefaultTypedValue(typedValue.mType);
  11038. }
  11039. uint64 dataAddr;
  11040. if (mSystem->mPtrSize == 4)
  11041. dataAddr = *(uint32*)data;
  11042. else
  11043. dataAddr = *(uint64*)data;
  11044. return BfTypedValue(mBfIRBuilder->CreateIntToPtr(
  11045. mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, dataAddr), mBfIRBuilder->MapType(typedValue.mType)), typedValue.mType);
  11046. }
  11047. auto constVal = ceContext->CreateConstant(this, ceContext->mMemory.mVals + ceTypedValue.mAddr, typedValue.mType);
  11048. if (!constVal)
  11049. {
  11050. Fail("Failed to create const", refNode);
  11051. return GetDefaultTypedValue(typedValue.mType);
  11052. }
  11053. return BfTypedValue(constVal, typedValue.mType);
  11054. }
  11055. }
  11056. }
  11057. }
  11058. BfIRValue loadedVal = typedValue.mValue;
  11059. if (loadedVal)
  11060. {
  11061. if (typedValue.mType->IsVar())
  11062. {
  11063. return BfTypedValue(loadedVal, typedValue.mType, false);
  11064. }
  11065. PopulateType(typedValue.mType, BfPopulateType_Data);
  11066. loadedVal = mBfIRBuilder->CreateAlignedLoad(loadedVal, std::max(1, (int)typedValue.mType->mAlign), isVolatile || typedValue.IsVolatile());
  11067. }
  11068. return BfTypedValue(loadedVal, typedValue.mType, false);
  11069. }
  11070. BfTypedValue BfModule::PrepareConst(BfTypedValue& typedValue)
  11071. {
  11072. if (!typedValue.mValue.IsConst())
  11073. return typedValue;
  11074. auto constant = mBfIRBuilder->GetConstant(typedValue.mValue);
  11075. if (constant->mTypeCode == BfTypeCode_StringId)
  11076. return GetTypedValueFromConstant(constant, mBfIRBuilder, typedValue.mType);
  11077. return typedValue;
  11078. }
  11079. BfTypedValue BfModule::LoadOrAggregateValue(BfTypedValue typedValue)
  11080. {
  11081. if (typedValue.IsSplat())
  11082. return AggregateSplat(typedValue);
  11083. if (typedValue.IsAddr())
  11084. return LoadValue(typedValue);
  11085. return typedValue;
  11086. }
  11087. BfTypedValue BfModule::AggregateSplat(BfTypedValue typedValue, BfIRValue* valueArrPtr)
  11088. {
  11089. if (!typedValue.IsSplat())
  11090. return typedValue;
  11091. BF_ASSERT(!mIsComptimeModule);
  11092. if (typedValue.mType->IsValuelessType())
  11093. return typedValue;
  11094. int elementIdx = 0;
  11095. auto _ExtractValue = [&](BfType* checkType)
  11096. {
  11097. if (valueArrPtr != NULL)
  11098. return valueArrPtr[elementIdx++];
  11099. return ExtractSplatValue(typedValue, elementIdx++, checkType);
  11100. };
  11101. std::function<BfIRValue(BfType*)> checkTypeLambda = [&](BfType* checkType)
  11102. {
  11103. if (checkType->IsStruct())
  11104. {
  11105. BfIRValue curValue = mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(checkType, BfIRPopulateType_Full));
  11106. auto checkTypeInstance = checkType->ToTypeInstance();
  11107. if (checkTypeInstance->mBaseType != NULL)
  11108. {
  11109. mBfIRBuilder->PopulateType(checkTypeInstance->mBaseType, BfIRPopulateType_Full);
  11110. BfIRValue baseValue = checkTypeLambda(checkTypeInstance->mBaseType);
  11111. curValue = mBfIRBuilder->CreateInsertValue(curValue, baseValue, 0);
  11112. }
  11113. if (checkTypeInstance->mIsUnion)
  11114. {
  11115. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  11116. if (!unionInnerType->IsValuelessType())
  11117. {
  11118. BfIRValue fieldValue = checkTypeLambda(unionInnerType);
  11119. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, 1);
  11120. }
  11121. if (checkTypeInstance->IsEnum())
  11122. {
  11123. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  11124. BfIRValue fieldValue = checkTypeLambda(dscrType);
  11125. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, 2);
  11126. }
  11127. }
  11128. else
  11129. {
  11130. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  11131. {
  11132. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  11133. if (fieldInstance->mDataIdx >= 0)
  11134. {
  11135. BfIRValue fieldValue = checkTypeLambda(fieldInstance->GetResolvedType());
  11136. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, fieldInstance->mDataIdx);
  11137. }
  11138. }
  11139. }
  11140. return curValue;
  11141. }
  11142. else if (checkType->IsMethodRef())
  11143. {
  11144. BfMethodRefType* methodRefType = (BfMethodRefType*)checkType;
  11145. BfIRValue curValue = mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(checkType, BfIRPopulateType_Full));
  11146. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  11147. {
  11148. BfIRValue fieldValue;
  11149. auto checkType = methodRefType->GetCaptureType(dataIdx);
  11150. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  11151. {
  11152. fieldValue = checkTypeLambda(checkType);
  11153. }
  11154. else
  11155. {
  11156. fieldValue = _ExtractValue(checkType);
  11157. }
  11158. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, dataIdx);
  11159. }
  11160. return curValue;
  11161. }
  11162. else if (!checkType->IsValuelessType())
  11163. {
  11164. return _ExtractValue(checkType);
  11165. }
  11166. return BfIRValue();
  11167. };
  11168. BfIRValue value = checkTypeLambda(typedValue.mType);
  11169. return BfTypedValue(value, typedValue.mType, typedValue.IsThis() ? BfTypedValueKind_ThisValue : BfTypedValueKind_Value);
  11170. }
  11171. void BfModule::AggregateSplatIntoAddr(BfTypedValue typedValue, BfIRValue addrVal)
  11172. {
  11173. if (!typedValue.IsSplat())
  11174. return;
  11175. if (typedValue.mType->IsValuelessType())
  11176. return;
  11177. BF_ASSERT(!mIsComptimeModule);
  11178. /*static int sCallIdx = 0;
  11179. if (!mCompiler->mIsResolveOnly)
  11180. sCallIdx++;
  11181. int callIdx = sCallIdx;*/
  11182. int elementIdx = 0;
  11183. std::function<void(BfType*, BfIRValue)> checkTypeLambda = [&](BfType* checkType, BfIRValue curAddrVal)
  11184. {
  11185. if (checkType->IsStruct())
  11186. {
  11187. auto checkTypeInstance = checkType->ToTypeInstance();
  11188. if (checkTypeInstance->mBaseType != NULL)
  11189. {
  11190. mBfIRBuilder->PopulateType(checkTypeInstance->mBaseType);
  11191. auto baseAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 0);
  11192. checkTypeLambda(checkTypeInstance->mBaseType, baseAddrVal);
  11193. }
  11194. if (checkTypeInstance->mIsUnion)
  11195. {
  11196. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  11197. if (!unionInnerType->IsValuelessType())
  11198. {
  11199. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 1);
  11200. checkTypeLambda(unionInnerType, fieldAddrVal);
  11201. }
  11202. if (checkTypeInstance->IsEnum())
  11203. {
  11204. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  11205. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 2);
  11206. checkTypeLambda(dscrType, fieldAddrVal);
  11207. }
  11208. }
  11209. else
  11210. {
  11211. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  11212. {
  11213. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  11214. if (fieldInstance->mDataIdx >= 0)
  11215. {
  11216. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, fieldInstance->mDataIdx);
  11217. checkTypeLambda(fieldInstance->mResolvedType, fieldAddrVal);
  11218. }
  11219. }
  11220. }
  11221. }
  11222. else if (checkType->IsMethodRef())
  11223. {
  11224. BfMethodRefType* methodRefType = (BfMethodRefType*)checkType;
  11225. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  11226. {
  11227. auto dataType = methodRefType->GetCaptureType(dataIdx);
  11228. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, dataIdx);
  11229. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  11230. {
  11231. checkTypeLambda(methodRefType->GetCaptureType(dataIdx), fieldAddrVal);
  11232. }
  11233. else
  11234. {
  11235. // static int sItrCount = 0;
  11236. // sItrCount++;
  11237. // int curItr = sItrCount;
  11238. // if (curItr == 1)
  11239. // {
  11240. // NOP;
  11241. // }
  11242. auto val = ExtractSplatValue(typedValue, elementIdx++, dataType);
  11243. mBfIRBuilder->CreateStore(val, fieldAddrVal);
  11244. }
  11245. }
  11246. }
  11247. else if (!checkType->IsValuelessType())
  11248. {
  11249. auto val = ExtractSplatValue(typedValue, elementIdx++, checkType);
  11250. mBfIRBuilder->CreateStore(val, curAddrVal);
  11251. }
  11252. };
  11253. checkTypeLambda(typedValue.mType, addrVal);
  11254. }
  11255. BfTypedValue BfModule::MakeAddressable(BfTypedValue typedVal, bool forceMutable, bool forceAddressable)
  11256. {
  11257. bool wasReadOnly = typedVal.IsReadOnly();
  11258. if ((forceAddressable) ||
  11259. ((typedVal.mType->IsValueType()) &&
  11260. (!typedVal.mType->IsValuelessType())))
  11261. {
  11262. wasReadOnly = true; // Any non-addr is implicitly read-only
  11263. //static int gCallIdx = 0;
  11264. FixValueActualization(typedVal);
  11265. if (typedVal.IsAddr())
  11266. return typedVal;
  11267. BfType* type = typedVal.mType;
  11268. PopulateType(type);
  11269. BfIRValue tempVar;
  11270. if (typedVal.mValue.IsFake())
  11271. tempVar = mBfIRBuilder->GetFakeVal();
  11272. else
  11273. {
  11274. tempVar = CreateAlloca(type);
  11275. if (typedVal.IsSplat())
  11276. AggregateSplatIntoAddr(typedVal, tempVar);
  11277. else
  11278. mBfIRBuilder->CreateAlignedStore(typedVal.mValue, tempVar, type->mAlign);
  11279. }
  11280. if (forceMutable)
  11281. wasReadOnly = false;
  11282. return BfTypedValue(tempVar, type,
  11283. typedVal.IsThis() ?
  11284. (wasReadOnly ? BfTypedValueKind_ReadOnlyThisAddr : BfTypedValueKind_ThisAddr) :
  11285. (wasReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr));
  11286. }
  11287. return LoadValue(typedVal);
  11288. }
  11289. BfTypedValue BfModule::RemoveReadOnly(BfTypedValue typedValue)
  11290. {
  11291. if (typedValue.mKind == BfTypedValueKind_ReadOnlyAddr)
  11292. typedValue.mKind = BfTypedValueKind_Addr;
  11293. return typedValue;
  11294. }
  11295. BfTypedValue BfModule::CopyValue(const BfTypedValue& typedValue)
  11296. {
  11297. return MakeAddressable(LoadValue(typedValue), true);
  11298. }
  11299. BfIRValue BfModule::ExtractSplatValue(BfTypedValue typedValue, int componentIdx, BfType* wantType, bool* isAddr)
  11300. {
  11301. BF_ASSERT(!mIsComptimeModule);
  11302. BfIRValue val;
  11303. if (typedValue.mValue.IsArg())
  11304. {
  11305. val = mBfIRBuilder->GetArgument(typedValue.mValue.mId + componentIdx);
  11306. if (isAddr != NULL)
  11307. {
  11308. if (wantType != NULL)
  11309. *isAddr = wantType->IsComposite();
  11310. else
  11311. *isAddr = false;
  11312. }
  11313. else if (wantType->IsComposite())
  11314. val = mBfIRBuilder->CreateLoad(val);
  11315. }
  11316. if (!val)
  11317. {
  11318. auto checkMethodState = mCurMethodState;
  11319. while (checkMethodState != NULL)
  11320. {
  11321. for (int idx = 0; idx < (int)checkMethodState->mSplatDecompAddrs.size(); idx++)
  11322. {
  11323. auto decompAddr = checkMethodState->mSplatDecompAddrs[idx];
  11324. if (decompAddr == typedValue.mValue)
  11325. {
  11326. val = checkMethodState->mSplatDecompAddrs[idx + componentIdx];
  11327. if ((wantType->IsComposite()) && (typedValue.mType->IsMethodRef()))
  11328. {
  11329. // This is really backing for a POINTER to a composite inside a methodRef
  11330. val = mBfIRBuilder->CreateLoad(val);
  11331. }
  11332. if ((isAddr != NULL) && (typedValue.mKind != BfTypedValueKind_SplatHead_NeedsCasting))
  11333. {
  11334. *isAddr = true;
  11335. return val;
  11336. }
  11337. else
  11338. {
  11339. val = mBfIRBuilder->CreateAlignedLoad(val, wantType->mAlign);
  11340. break;
  11341. }
  11342. }
  11343. }
  11344. if (val)
  11345. break;
  11346. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mCapturing))
  11347. {
  11348. BF_ASSERT(mBfIRBuilder->mIgnoreWrites);
  11349. return mBfIRBuilder->GetFakeVal();
  11350. }
  11351. checkMethodState = checkMethodState->mPrevMethodState;
  11352. }
  11353. }
  11354. if (val)
  11355. {
  11356. if (typedValue.mKind == BfTypedValueKind_SplatHead_NeedsCasting)
  11357. {
  11358. BF_ASSERT(wantType != NULL);
  11359. if (wantType != NULL)
  11360. return mBfIRBuilder->CreateBitCast(val, mBfIRBuilder->MapType(wantType));
  11361. }
  11362. return val;
  11363. }
  11364. BFMODULE_FATAL(this, "Splat not found");
  11365. return BfIRValue();
  11366. }
  11367. BfTypedValue BfModule::ExtractValue(BfTypedValue typedValue, BfFieldInstance* fieldInstance, int fieldIdx)
  11368. {
  11369. int useFieldIdx = fieldIdx;
  11370. BfType* fieldType = NULL;
  11371. if (fieldInstance != NULL)
  11372. {
  11373. fieldType = fieldInstance->mResolvedType;
  11374. if (typedValue.mType->IsUnion())
  11375. {
  11376. if (fieldIdx == 1)
  11377. {
  11378. if (typedValue.IsSplat())
  11379. {
  11380. BfTypedValue innerVal = typedValue;
  11381. innerVal.mType = fieldType;
  11382. return innerVal;
  11383. }
  11384. }
  11385. }
  11386. }
  11387. else
  11388. {
  11389. if (typedValue.mType->IsPayloadEnum())
  11390. {
  11391. auto typeInst = typedValue.mType->ToTypeInstance();
  11392. if (fieldIdx == 1)
  11393. fieldType = typeInst->GetUnionInnerType();
  11394. else if (fieldIdx == 2)
  11395. {
  11396. fieldType = typeInst->GetDiscriminatorType(&useFieldIdx);
  11397. }
  11398. }
  11399. else if (typedValue.mType->IsUnion())
  11400. {
  11401. if (fieldIdx == 1)
  11402. {
  11403. fieldType = typedValue.mType->ToTypeInstance()->GetUnionInnerType();
  11404. if (typedValue.IsSplat())
  11405. {
  11406. BfTypedValue innerVal = typedValue;
  11407. innerVal.mType = fieldType;
  11408. return innerVal;
  11409. }
  11410. }
  11411. }
  11412. }
  11413. BF_ASSERT(typedValue.mType->IsStruct());
  11414. if (typedValue.IsSplat())
  11415. {
  11416. if (typedValue.mType->IsPayloadEnum())
  11417. {
  11418. if (fieldIdx == 1)
  11419. {
  11420. // Payload
  11421. auto typeInst = typedValue.mType->ToTypeInstance();
  11422. auto unionInnerType = typeInst->GetUnionInnerType();
  11423. bool isAddr = false;
  11424. BfIRValue irVal = ExtractSplatValue(typedValue, 0, unionInnerType, &isAddr);
  11425. return BfTypedValue(irVal, unionInnerType, BfTypedValueKind_SplatHead);
  11426. }
  11427. if (fieldIdx == 2)
  11428. {
  11429. // Discriminator
  11430. auto typeInst = typedValue.mType->ToTypeInstance();
  11431. auto unionInnerType = typeInst->GetUnionInnerType();
  11432. auto dscrType = typeInst->GetDiscriminatorType();
  11433. int argIdx = typedValue.mValue.mId;
  11434. int componentIdx = 0;
  11435. BfTypeUtils::SplatIterate([&](BfType* checkType) { componentIdx++; }, unionInnerType);
  11436. bool isAddr;
  11437. BfIRValue irVal = ExtractSplatValue(typedValue, componentIdx, dscrType, &isAddr);
  11438. return BfTypedValue(irVal, dscrType, isAddr);
  11439. }
  11440. }
  11441. int componentIdx = 0;
  11442. BfTypedValue retVal;
  11443. BfFieldInstance* wantFieldInstance = fieldInstance;
  11444. std::function<void(BfType*)> checkTypeLambda = [&](BfType* checkType)
  11445. {
  11446. if (checkType->IsStruct())
  11447. {
  11448. auto checkTypeInstance = checkType->ToTypeInstance();
  11449. if ((checkType->IsUnion()) || (checkType->IsEnum()))
  11450. {
  11451. //TODO: Why did we have this removed? It messed up an extraction from a nullable splattable
  11452. fieldType = checkTypeInstance->GetUnionInnerType();
  11453. checkTypeLambda(fieldType);
  11454. if (checkType->IsEnum())
  11455. {
  11456. // Past discriminator...
  11457. componentIdx++;
  11458. }
  11459. return;
  11460. }
  11461. if (checkTypeInstance->mBaseType != NULL)
  11462. checkTypeLambda(checkTypeInstance->mBaseType);
  11463. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  11464. {
  11465. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  11466. if (fieldInstance == wantFieldInstance)
  11467. {
  11468. if (fieldInstance->mResolvedType->IsValuelessType())
  11469. {
  11470. retVal = GetDefaultTypedValue(fieldInstance->mResolvedType);
  11471. break;
  11472. }
  11473. bool isAddr = false;
  11474. BfIRValue val = ExtractSplatValue(typedValue, componentIdx, fieldInstance->mResolvedType, &isAddr);
  11475. retVal = BfTypedValue(val, fieldInstance->mResolvedType,
  11476. fieldInstance->mResolvedType->IsComposite() ? BfTypedValueKind_SplatHead :
  11477. isAddr ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Value);
  11478. if ((retVal.IsAddr()) && (!fieldInstance->mResolvedType->IsValueType()))
  11479. {
  11480. retVal = LoadValue(retVal);
  11481. }
  11482. break;
  11483. }
  11484. if (fieldInstance->mDataIdx >= 0)
  11485. checkTypeLambda(fieldInstance->GetResolvedType());
  11486. }
  11487. }
  11488. else if (!checkType->IsValuelessType())
  11489. {
  11490. componentIdx++;
  11491. //argIdx++;
  11492. }
  11493. };
  11494. checkTypeLambda(typedValue.mType);
  11495. BF_ASSERT(retVal);
  11496. return retVal;
  11497. }
  11498. if (typedValue.IsAddr())
  11499. {
  11500. BF_ASSERT(fieldType != NULL);
  11501. auto valRef = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, useFieldIdx);
  11502. return BfTypedValue(valRef, fieldType, BfTypedValueKind_ReadOnlyAddr);
  11503. }
  11504. else
  11505. {
  11506. BF_ASSERT(fieldType != NULL);
  11507. return BfTypedValue(mBfIRBuilder->CreateExtractValue(typedValue.mValue, useFieldIdx), fieldType, BfTypedValueKind_Value);
  11508. }
  11509. }
  11510. BfIRValue BfModule::ExtractValue(BfTypedValue typedValue, int dataIdx)
  11511. {
  11512. if (typedValue.IsAddr())
  11513. {
  11514. auto addrVal = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, dataIdx);
  11515. return mBfIRBuilder->CreateAlignedLoad(addrVal, typedValue.mType->mAlign);
  11516. }
  11517. return mBfIRBuilder->CreateExtractValue(typedValue.mValue, dataIdx);
  11518. }
  11519. BfIRValue BfModule::CreateIndexedValue(BfType* elementType, BfIRValue value, BfIRValue indexValue, bool isElementIndex)
  11520. {
  11521. if (isElementIndex)
  11522. return mBfIRBuilder->CreateInBoundsGEP(value, GetConstValue(0), indexValue);
  11523. else
  11524. return mBfIRBuilder->CreateInBoundsGEP(value, indexValue);
  11525. // if (elementType->IsSizeAligned())
  11526. // {
  11527. // if (isElementIndex)
  11528. // return mBfIRBuilder->CreateInBoundsGEP(value, GetConstValue(0), indexValue);
  11529. // else
  11530. // return mBfIRBuilder->CreateInBoundsGEP(value, indexValue);
  11531. // }
  11532. //
  11533. // auto ptrType = CreatePointerType(elementType);
  11534. // auto ofsVal = mBfIRBuilder->CreateNumericCast(indexValue, true, BfTypeCode_IntPtr);
  11535. // auto ofsScaledVal = mBfIRBuilder->CreateMul(ofsVal, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, elementType->GetStride()));
  11536. // auto i8PtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8));
  11537. // BfIRValue origPtrValue = mBfIRBuilder->CreateBitCast(value, i8PtrType);
  11538. // BfIRValue newPtrValue = mBfIRBuilder->CreateInBoundsGEP(origPtrValue, ofsScaledVal);
  11539. // return mBfIRBuilder->CreateBitCast(newPtrValue, mBfIRBuilder->MapType(ptrType));
  11540. }
  11541. BfIRValue BfModule::CreateIndexedValue(BfType* elementType, BfIRValue value, int indexValue, bool isElementIndex)
  11542. {
  11543. if (elementType->IsSizeAligned())
  11544. {
  11545. if (isElementIndex)
  11546. return mBfIRBuilder->CreateInBoundsGEP(value, 0, indexValue);
  11547. else
  11548. return mBfIRBuilder->CreateInBoundsGEP(value, indexValue);
  11549. }
  11550. return CreateIndexedValue(elementType, value, GetConstValue(indexValue), isElementIndex);
  11551. }
  11552. bool BfModule::CheckModifyValue(BfTypedValue& typedValue, BfAstNode* refNode, const char* modifyType)
  11553. {
  11554. if (modifyType == NULL)
  11555. modifyType = "modify";
  11556. if (typedValue.mType->IsVar())
  11557. return true;
  11558. if (typedValue.IsReadOnly())
  11559. {
  11560. Fail(StrFormat("Cannot %s read-only variable", modifyType), refNode);
  11561. return false;
  11562. }
  11563. if ((!typedValue.IsAddr()) && (!typedValue.mType->IsValuelessType()))
  11564. {
  11565. Fail(StrFormat("Cannot %s value", modifyType), refNode);
  11566. return false;
  11567. }
  11568. if (typedValue.mKind == BfTypedValueKind_RestrictedTempAddr)
  11569. {
  11570. Fail(StrFormat("Cannot %s temporary value", modifyType), refNode);
  11571. return false;
  11572. }
  11573. return true;
  11574. }
  11575. bool BfModule::CompareMethodSignatures(BfMethodInstance* methodA, BfMethodInstance* methodB)
  11576. {
  11577. // If one is an interface and the other is an impl, B is the impl
  11578. auto implOwner = methodB->GetOwner();
  11579. if (methodA->mMethodDef->mIsLocalMethod)
  11580. {
  11581. int sepPosA = (int)BF_MIN(methodA->mMethodDef->mName.IndexOf('@'), methodA->mMethodDef->mName.length());
  11582. int sepPosB = (int)BF_MIN(methodB->mMethodDef->mName.IndexOf('@'), methodB->mMethodDef->mName.length());
  11583. if (sepPosA != sepPosB)
  11584. return false;
  11585. if (strncmp(methodA->mMethodDef->mName.c_str(), methodB->mMethodDef->mName.c_str(), sepPosA) != 0)
  11586. return false;
  11587. }
  11588. else if (methodA->mMethodDef->mName != methodB->mMethodDef->mName)
  11589. return false;
  11590. if (methodA->mMethodDef->mCheckedKind != methodB->mMethodDef->mCheckedKind)
  11591. return false;
  11592. if (methodA->mMethodDef->mHasComptime != methodB->mMethodDef->mHasComptime)
  11593. return false;
  11594. if ((methodA->mMethodDef->mMethodType == BfMethodType_Mixin) != (methodB->mMethodDef->mMethodType == BfMethodType_Mixin))
  11595. return false;
  11596. if (methodA->mMethodDef->mMethodType == BfMethodType_Ctor)
  11597. {
  11598. if (methodA->mMethodDef->mIsStatic != methodB->mMethodDef->mIsStatic)
  11599. return false;
  11600. }
  11601. if (methodA->mMethodDef->mMethodType == BfMethodType_Operator)
  11602. {
  11603. if (methodB->mMethodDef->mMethodType != BfMethodType_Operator)
  11604. return false;
  11605. auto operatorA = (BfOperatorDef*)methodA->mMethodDef;
  11606. auto operatorB = (BfOperatorDef*)methodB->mMethodDef;
  11607. if (operatorA->mOperatorDeclaration->mUnaryOp != operatorB->mOperatorDeclaration->mUnaryOp)
  11608. return false;
  11609. if (operatorA->mOperatorDeclaration->mBinOp != operatorB->mOperatorDeclaration->mBinOp)
  11610. return false;
  11611. if (operatorA->mOperatorDeclaration->mAssignOp != operatorB->mOperatorDeclaration->mAssignOp)
  11612. return false;
  11613. if (operatorA->mOperatorDeclaration->mIsConvOperator)
  11614. {
  11615. if (!BfTypeUtils::TypeEquals(methodA->mReturnType, methodB->mReturnType, implOwner))
  11616. return false;
  11617. }
  11618. }
  11619. int implicitParamCountA = methodA->GetImplicitParamCount();
  11620. int implicitParamCountB = methodB->GetImplicitParamCount();
  11621. if (methodA->GetParamCount() - implicitParamCountA != methodB->GetParamCount() - implicitParamCountB)
  11622. return false;
  11623. if (methodA->mHadGenericDelegateParams != methodB->mHadGenericDelegateParams)
  11624. return false;
  11625. for (int paramIdx = 0; paramIdx < (int)methodA->GetParamCount() - implicitParamCountA; paramIdx++)
  11626. {
  11627. if ((!BfTypeUtils::TypeEquals(methodA->GetParamType(paramIdx + implicitParamCountA), methodB->GetParamType(paramIdx + implicitParamCountB), implOwner)) ||
  11628. (methodA->GetParamKind(paramIdx + implicitParamCountA) != methodB->GetParamKind(paramIdx + implicitParamCountB)))
  11629. return false;
  11630. }
  11631. // Compare generic params. Generic params are part of the method signature here
  11632. if (methodA->GetNumGenericParams() != methodB->GetNumGenericParams())
  11633. return false;
  11634. for (int genericParamIdx = 0; genericParamIdx < (int)methodA->GetNumGenericParams(); genericParamIdx++)
  11635. {
  11636. auto genericParamA = methodA->mMethodInfoEx->mGenericParams[genericParamIdx];
  11637. auto genericParamB = methodB->mMethodInfoEx->mGenericParams[genericParamIdx];
  11638. if (genericParamA->mGenericParamFlags != genericParamB->mGenericParamFlags)
  11639. return false;
  11640. if (genericParamA->mTypeConstraint != genericParamB->mTypeConstraint)
  11641. return false;
  11642. if (genericParamA->mInterfaceConstraints.size() != genericParamB->mInterfaceConstraints.size())
  11643. return false;
  11644. for (int interfaceIdx = 0; interfaceIdx < (int)genericParamA->mInterfaceConstraints.size(); interfaceIdx++)
  11645. if (genericParamA->mInterfaceConstraints[interfaceIdx] != genericParamB->mInterfaceConstraints[interfaceIdx])
  11646. return false;
  11647. }
  11648. return true;
  11649. }
  11650. bool BfModule::StrictCompareMethodSignatures(BfMethodInstance* methodA, BfMethodInstance* methodB)
  11651. {
  11652. if (!CompareMethodSignatures(methodA, methodB))
  11653. return false;
  11654. if (methodA->mReturnType != methodB->mReturnType)
  11655. return false;
  11656. if (methodA->mMethodDef->mIsStatic != methodB->mMethodDef->mIsStatic)
  11657. return false;
  11658. return true;
  11659. }
  11660. bool BfModule::IsCompatibleInterfaceMethod(BfMethodInstance* iMethodInst, BfMethodInstance* methodInstance)
  11661. {
  11662. if ((iMethodInst->GetNumGenericParams() != 0) || (methodInstance->GetNumGenericParams() != 0))
  11663. return false;
  11664. if (iMethodInst->mMethodDef->mName != methodInstance->mMethodDef->mName)
  11665. return false;
  11666. if (iMethodInst->mMethodDef->mIsOperator != methodInstance->mMethodDef->mIsOperator)
  11667. return false;
  11668. if (iMethodInst->mMethodDef->mIsOperator)
  11669. {
  11670. auto iOperatorDef = (BfOperatorDef*)iMethodInst->mMethodDef;
  11671. auto operatorDef = (BfOperatorDef*)methodInstance->mMethodDef;
  11672. if (iOperatorDef->mOperatorDeclaration->mUnaryOp != operatorDef->mOperatorDeclaration->mUnaryOp)
  11673. return false;
  11674. if (iOperatorDef->mOperatorDeclaration->mBinOp != operatorDef->mOperatorDeclaration->mBinOp)
  11675. return false;
  11676. }
  11677. if (iMethodInst->GetParamCount() != methodInstance->GetParamCount())
  11678. return false;
  11679. auto selfType = methodInstance->GetOwner();
  11680. for (int paramIdx = 0; paramIdx < (int)iMethodInst->GetParamCount(); paramIdx++)
  11681. {
  11682. if (iMethodInst->GetParamKind(paramIdx) != methodInstance->GetParamKind(paramIdx))
  11683. return false;
  11684. BfType* iParamType = iMethodInst->GetParamType(paramIdx);
  11685. BfType* methodParamType = methodInstance->GetParamType(paramIdx);
  11686. iParamType = ResolveSelfType(iParamType, selfType);
  11687. methodParamType = ResolveSelfType(methodParamType, selfType);
  11688. if (!iParamType->IsGenericParam())
  11689. {
  11690. if (methodParamType != iParamType)
  11691. return false;
  11692. }
  11693. else
  11694. {
  11695. if (!methodParamType->IsGenericParam())
  11696. return false;
  11697. auto genericParamType = (BfGenericParamType*)methodParamType;
  11698. if (genericParamType->mGenericParamKind == BfGenericParamKind_Type)
  11699. return false;
  11700. auto genericParam = methodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  11701. bool hadInterface = false;
  11702. for (auto interfaceConstraint : genericParam->mInterfaceConstraints)
  11703. if (interfaceConstraint == iParamType)
  11704. hadInterface = true;
  11705. if (!hadInterface)
  11706. return false;
  11707. }
  11708. }
  11709. return true;
  11710. }
  11711. void BfModule::AddMethodReference(const BfMethodRef& methodRef, BfGetMethodInstanceFlags flags)
  11712. {
  11713. BfMethodInstance* methodInstance = methodRef;
  11714. if ((mCurTypeInstance != NULL) && (!mCompiler->IsAutocomplete()))
  11715. {
  11716. auto methodInstanceGroup = methodInstance->mMethodInstanceGroup;
  11717. if ((methodInstance->IsSpecializedGenericMethod()) || (methodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_AlwaysInclude))
  11718. {
  11719. BF_ASSERT(!methodRef.mTypeInstance->IsFunction());
  11720. // This ensures we rebuild - there are some cases where we get a method reference but never call it, so this is required here
  11721. AddDependency(methodInstance->GetOwner(), mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  11722. BfMethodRef methodRef = methodInstance;
  11723. BfSpecializedMethodRefInfo* specializedMethodRefInfo = NULL;
  11724. bool isNew = mCurTypeInstance->mSpecializedMethodReferences.TryAdd(methodRef, NULL, &specializedMethodRefInfo);
  11725. if (((flags & BfGetMethodInstanceFlag_Unreified) == 0) &&
  11726. ((flags & BfGetMethodInstanceFlag_NoForceReification) == 0) &&
  11727. (mIsReified))
  11728. {
  11729. specializedMethodRefInfo->mHasReifiedRef = true;
  11730. }
  11731. }
  11732. }
  11733. }
  11734. BfModuleMethodInstance BfModule::ReferenceExternalMethodInstance(BfMethodInstance* methodInstance, BfGetMethodInstanceFlags flags)
  11735. {
  11736. if ((flags & BfGetMethodInstanceFlag_ResultNotUsed) != 0)
  11737. return BfModuleMethodInstance(methodInstance, BfIRValue());
  11738. if (mBfIRBuilder == NULL)
  11739. return BfModuleMethodInstance(methodInstance, BfIRValue());
  11740. if (methodInstance->GetOwner()->IsFunction())
  11741. {
  11742. // No actual ref needed- not an actual generated function
  11743. return BfModuleMethodInstance(methodInstance, BfIRValue());
  11744. }
  11745. bool isGenFunction = methodInstance->mMethodInstanceGroup->mMethodIdx < 0;
  11746. if (!isGenFunction)
  11747. AddMethodReference(methodInstance, flags);
  11748. if ((mBfIRBuilder->mIgnoreWrites) || ((flags & BfGetMethodInstanceFlag_Unreified) != 0))
  11749. return BfModuleMethodInstance(methodInstance, mBfIRBuilder->GetFakeVal());
  11750. if (IsSkippingExtraResolveChecks())
  11751. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  11752. if (methodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)
  11753. {
  11754. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  11755. }
  11756. bool isInlined = (methodInstance->mAlwaysInline) || ((flags & BfGetMethodInstanceFlag_ForceInline) != 0);
  11757. if ((methodInstance->mIsIntrinsic) || (methodInstance->mMethodDef->mIsExtern))
  11758. isInlined = false;
  11759. BfMethodRef methodRef = methodInstance;
  11760. if (isInlined)
  11761. methodRef.mMethodRefFlags = (BfMethodRefFlags)(methodRef.mMethodRefFlags | BfMethodRefFlag_AlwaysInclude);
  11762. else
  11763. methodRef.mMethodRefFlags = BfMethodRefFlag_None;
  11764. if (!isGenFunction)
  11765. {
  11766. BfIRValue* irFuncPtr = NULL;
  11767. if (mFuncReferences.TryGetValue(methodRef, &irFuncPtr))
  11768. return BfModuleMethodInstance(methodInstance, *irFuncPtr);
  11769. }
  11770. if (mAwaitingInitFinish)
  11771. FinishInit();
  11772. BfIRValue func = CreateFunctionFrom(methodInstance, isGenFunction, isInlined);
  11773. if (!isGenFunction)
  11774. {
  11775. BF_ASSERT(func || methodInstance->mMethodInstanceGroup->mOwner->IsInterface());
  11776. mFuncReferences[methodRef] = func;
  11777. }
  11778. BfLogSysM("Adding func reference. Module:%p MethodInst:%p NewLLVMFunc:%d OldLLVMFunc:%d\n", this, methodInstance, func.mId, methodInstance->mIRFunction.mId);
  11779. if ((isInlined) && (!mIsScratchModule) && ((flags & BfGetMethodInstanceFlag_NoInline) == 0))
  11780. {
  11781. // We can't just add a dependency to mCurTypeInstance because we may have nested inlined functions, and
  11782. // mCurTypeInstance will just reflect the owner of the method currently being inlined, not the top-level
  11783. // type instance
  11784. // Be smarter about this if we ever insert a lot of type instances into a single module - track in a field
  11785. BF_ASSERT(mOwnedTypeInstances.size() <= 1);
  11786. for (auto ownedTypeInst : mOwnedTypeInstances)
  11787. AddDependency(methodInstance->GetOwner(), ownedTypeInst, BfDependencyMap::DependencyFlag_InlinedCall);
  11788. if ((!mCompiler->mIsResolveOnly) && (mIsReified) && (!methodInstance->mIsUnspecialized))
  11789. {
  11790. mIncompleteMethodCount++;
  11791. BfInlineMethodRequest* inlineMethodRequest = mContext->mInlineMethodWorkList.Alloc();
  11792. inlineMethodRequest->mType = methodInstance->GetOwner();
  11793. inlineMethodRequest->mFromModule = this;
  11794. inlineMethodRequest->mFunc = func;
  11795. inlineMethodRequest->mFromModuleRevision = mRevision;
  11796. inlineMethodRequest->mMethodInstance = methodInstance;
  11797. BF_ASSERT(mIsModuleMutable);
  11798. BfLogSysM("mInlineMethodWorkList %p for method %p in module %p in ReferenceExternalMethodInstance\n", inlineMethodRequest, methodInstance, this);
  11799. }
  11800. }
  11801. return BfModuleMethodInstance(methodInstance, func);
  11802. }
  11803. BfModule* BfModule::GetOrCreateMethodModule(BfMethodInstance* methodInstance)
  11804. {
  11805. BfTypeInstance* typeInst = methodInstance->mMethodInstanceGroup->mOwner;
  11806. if (mBfIRBuilder == NULL)
  11807. {
  11808. // To allow for custom attribute data
  11809. PrepareForIRWriting(typeInst);
  11810. }
  11811. BfModule* declareModule = this;
  11812. // Get to the optionless branch head -- but this could still be a specialized method module, not the true root
  11813. while ((declareModule->mParentModule != NULL) && (!declareModule->mIsSpecializedMethodModuleRoot))
  11814. declareModule = declareModule->mParentModule;
  11815. // Check for attributes
  11816. if (typeInst == mContext->mBfObjectType)
  11817. {
  11818. auto methodDecl = methodInstance->mMethodDef->GetMethodDeclaration();
  11819. if (methodDecl != NULL)
  11820. {
  11821. auto attributesDirective = methodDecl->mAttributes;
  11822. if ((attributesDirective != NULL) && (mCompiler->mResolvePassData != NULL))
  11823. {
  11824. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(attributesDirective))
  11825. sourceClassifier->VisitChild(attributesDirective);
  11826. }
  11827. }
  11828. }
  11829. else
  11830. {
  11831. // Only allow attributes on System.Object methods that can be handled inside the DefBuilder
  11832. GetMethodCustomAttributes(methodInstance);
  11833. }
  11834. BF_ASSERT(mModuleOptions == NULL);
  11835. if (methodInstance->GetCustomAttributes() != NULL)
  11836. {
  11837. auto project = typeInst->mTypeDef->mProject;
  11838. BfModuleOptions moduleOptions = declareModule->GetModuleOptions();
  11839. BfModuleOptions wantOptions = moduleOptions;
  11840. auto typeOptions = mSystem->GetTypeOptions(typeInst->mTypeOptionsIdx);
  11841. if (typeOptions != NULL)
  11842. {
  11843. wantOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)wantOptions.mOptLevel, (int)typeOptions->mOptimizationLevel);
  11844. wantOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mSIMDSetting, typeOptions->mSIMDSetting);
  11845. wantOptions.mEmitDebugInfo = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mEmitDebugInfo, typeOptions->mEmitDebugInfo);
  11846. }
  11847. if (!mCompiler->mAttributeTypeOptionMap.IsEmpty())
  11848. {
  11849. StringT<128> attrName;
  11850. for (auto& customAttrs : methodInstance->GetCustomAttributes()->mAttributes)
  11851. {
  11852. attrName.Clear();
  11853. customAttrs.mType->mTypeDef->mFullName.ToString(attrName);
  11854. Array<int>* arrPtr;
  11855. if (mCompiler->mAttributeTypeOptionMap.TryGetValue(attrName, &arrPtr))
  11856. {
  11857. for (auto optionsIdx : *arrPtr)
  11858. {
  11859. auto& typeOptions = mCompiler->mSystem->mTypeOptions[optionsIdx];
  11860. wantOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)wantOptions.mOptLevel, (int)typeOptions.mOptimizationLevel);
  11861. wantOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mSIMDSetting, typeOptions.mSIMDSetting);
  11862. wantOptions.mEmitDebugInfo = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mEmitDebugInfo, typeOptions.mEmitDebugInfo);
  11863. }
  11864. }
  11865. }
  11866. }
  11867. if ((HasCompiledOutput()) && (wantOptions != moduleOptions) && (!mIsScratchModule))
  11868. {
  11869. auto lastCheckModule = this;
  11870. auto checkModule = this->mNextAltModule;
  11871. while (checkModule != NULL)
  11872. {
  11873. if (*checkModule->mModuleOptions == wantOptions)
  11874. {
  11875. declareModule = checkModule;
  11876. break;
  11877. }
  11878. lastCheckModule = checkModule;
  11879. checkModule = checkModule->mNextAltModule;
  11880. }
  11881. // Not found?
  11882. if (declareModule == this)
  11883. {
  11884. String specModuleName = mModuleName + "@@";
  11885. if (wantOptions.mOptLevel != moduleOptions.mOptLevel)
  11886. specModuleName += StrFormat("O%d", wantOptions.mOptLevel);
  11887. if (wantOptions.mSIMDSetting != moduleOptions.mSIMDSetting)
  11888. specModuleName += StrFormat("SIMD%d", wantOptions.mSIMDSetting);
  11889. declareModule = new BfModule(mContext, specModuleName);
  11890. declareModule->mProject = project;
  11891. declareModule->mModuleOptions = new BfModuleOptions();
  11892. *declareModule->mModuleOptions = wantOptions;
  11893. declareModule->mParentModule = lastCheckModule;
  11894. declareModule->Init();
  11895. lastCheckModule->mNextAltModule = declareModule;
  11896. }
  11897. }
  11898. }
  11899. declareModule->PrepareForIRWriting(typeInst);
  11900. return declareModule;
  11901. }
  11902. BfModuleMethodInstance BfModule::GetMethodInstance(BfTypeInstance* typeInst, BfMethodDef* methodDef, const BfTypeVector& methodGenericArguments, BfGetMethodInstanceFlags flags, BfTypeInstance* foreignType)
  11903. {
  11904. if (methodDef->mMethodType == BfMethodType_Init)
  11905. return BfModuleMethodInstance();
  11906. if (((flags & BfGetMethodInstanceFlag_ForceInline) != 0) && (mCompiler->mIsResolveOnly))
  11907. {
  11908. // Don't bother inlining for resolve-only
  11909. flags = (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline);
  11910. }
  11911. if (methodDef->mIsExtern)
  11912. flags = (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline);
  11913. bool processNow = false;
  11914. bool keepInCurrentModule = false;
  11915. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsUnspecialized))
  11916. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_NoForceReification);
  11917. if (!typeInst->IsTypeMemberIncluded(methodDef->mDeclaringType))
  11918. {
  11919. return BfModuleMethodInstance();
  11920. }
  11921. if (methodDef->mIsLocalMethod)
  11922. {
  11923. auto rootMethodState = mCurMethodState->GetRootMethodState();
  11924. BfLocalMethod* localMethod;
  11925. if (rootMethodState->mLocalMethodCache.TryGetValue(methodDef->mName, &localMethod))
  11926. {
  11927. // Handle the def in the correct method state
  11928. return GetLocalMethodInstance(localMethod, methodGenericArguments);
  11929. }
  11930. BFMODULE_FATAL(this, "Cannot find local method");
  11931. return BfModuleMethodInstance();
  11932. }
  11933. #ifdef _DEBUG
  11934. for (auto arg : methodGenericArguments)
  11935. BF_ASSERT(!arg->IsVar());
  11936. #endif
  11937. BF_ASSERT(methodDef->mMethodType != BfMethodType_Ignore);
  11938. // We need to do the 'mNeedsMethodProcessing' check because we want to do a proper initial "awaiting reference" population
  11939. // on the methods before we handle an on-demand situation. This also ensures that our type options are set before doing
  11940. // a FinishInit
  11941. if ((typeInst->IsIncomplete()) &&
  11942. (!typeInst->mResolvingVarField) && (!typeInst->mTypeFailed))
  11943. {
  11944. // For autocomplete, we still may not actually generate methods. This shouldn't matter, and on-demand works differently
  11945. // for resolve-only because we don't differentiate between reified/unreified there
  11946. if ((methodDef->mIsStatic) /*&& (mIsComptimeModule)*/)
  11947. {
  11948. if (!typeInst->DefineStateAllowsStaticMethods())
  11949. PopulateType(typeInst, BfPopulateType_AllowStaticMethods);
  11950. }
  11951. else
  11952. PopulateType(typeInst, BfPopulateType_Full);
  11953. if (typeInst->mDefineState < BfTypeDefineState_Defined)
  11954. {
  11955. if (!mCompiler->EnsureCeUnpaused(typeInst))
  11956. {
  11957. BfLogSysM("GetMethodInstance (DefineState < BfTypeDefineState_Defined)) bailing due to IsCePaused\n");
  11958. return BfModuleMethodInstance();
  11959. }
  11960. }
  11961. }
  11962. bool tryModuleMethodLookup = false;
  11963. BfModuleMethodInstance moduleMethodInst;
  11964. BfModule* instModule = typeInst->mModule;
  11965. if (keepInCurrentModule)
  11966. {
  11967. // Stay here
  11968. instModule = this;
  11969. }
  11970. if (this == mContext->mUnreifiedModule)
  11971. {
  11972. // Stay in this 'resolve only' module here
  11973. }
  11974. else if (flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass)
  11975. {
  11976. BF_ASSERT(this == mContext->mUnreifiedModule);
  11977. }
  11978. else if (flags & BfGetMethodInstanceFlag_ExplicitSpecializedModule)
  11979. {
  11980. BF_ASSERT(instModule == mParentModule);
  11981. }
  11982. else if (instModule != this)
  11983. {
  11984. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mMinDependDepth >= 32))
  11985. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_DepthExceeded);
  11986. if ((!mIsComptimeModule) && (!mIsReified) && (instModule->mIsReified))
  11987. {
  11988. BF_ASSERT(!mCompiler->mIsResolveOnly);
  11989. // A resolve-only module is specializing a method from a type in a reified module,
  11990. // we need to take care that this doesn't cause anything new to become reified
  11991. BfModuleMethodInstance moduleMethodInstance = mContext->mUnreifiedModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ExplicitResolveOnlyPass), foreignType);
  11992. if (!moduleMethodInstance)
  11993. return moduleMethodInstance;
  11994. SetMethodDependency(moduleMethodInstance.mMethodInstance);
  11995. return moduleMethodInstance;
  11996. }
  11997. else
  11998. {
  11999. if ((!mIsComptimeModule) && (mIsReified) && (!instModule->mIsReified))
  12000. {
  12001. if (!typeInst->IsUnspecializedType())
  12002. {
  12003. if (!instModule->mReifyQueued)
  12004. {
  12005. BF_ASSERT((instModule != mContext->mUnreifiedModule) && (instModule != mContext->mScratchModule));
  12006. BF_ASSERT((mCompiler->mCompileState != BfCompiler::CompileState_Unreified) && (mCompiler->mCompileState != BfCompiler::CompileState_VData));
  12007. BfLogSysM("Queueing ReifyModule: %p\n", instModule);
  12008. mContext->mReifyModuleWorkList.Add(instModule);
  12009. instModule->mReifyQueued = true;
  12010. }
  12011. // This ensures that the method will actually be created when it gets reified
  12012. BfMethodSpecializationRequest* specializationRequest = mContext->mMethodSpecializationWorkList.Alloc();
  12013. specializationRequest->mFromModule = typeInst->mModule;
  12014. specializationRequest->mFromModuleRevision = typeInst->mModule->mRevision;
  12015. specializationRequest->Init(typeInst, foreignType, methodDef);
  12016. //specializationRequest->mMethodDef = methodDef;
  12017. specializationRequest->mMethodGenericArguments = methodGenericArguments;
  12018. specializationRequest->mType = typeInst;
  12019. specializationRequest->mFlags = flags;
  12020. }
  12021. }
  12022. auto defFlags = (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline);
  12023. defFlags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_NoReference);
  12024. if (mIsComptimeModule)
  12025. {
  12026. defFlags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_MethodInstanceOnly);
  12027. if (!mCompiler->mIsResolveOnly)
  12028. defFlags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_NoForceReification | BfGetMethodInstanceFlag_Unreified | BfGetMethodInstanceFlag_MethodInstanceOnly);
  12029. }
  12030. // Not extern
  12031. // Create the instance in the proper module and then create a reference in this one
  12032. moduleMethodInst = instModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, defFlags, foreignType);
  12033. if (!moduleMethodInst)
  12034. return moduleMethodInst;
  12035. tryModuleMethodLookup = true;
  12036. if ((mIsReified) && (!moduleMethodInst.mMethodInstance->mIsReified))
  12037. {
  12038. CheckHotMethod(moduleMethodInst.mMethodInstance, "");
  12039. }
  12040. }
  12041. }
  12042. if (tryModuleMethodLookup)
  12043. {
  12044. SetMethodDependency(moduleMethodInst.mMethodInstance);
  12045. return ReferenceExternalMethodInstance(moduleMethodInst.mMethodInstance, flags);
  12046. }
  12047. if (((flags & BfGetMethodInstanceFlag_ForceInline) != 0) && (!methodDef->mAlwaysInline))
  12048. {
  12049. auto moduleMethodInstance = GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline), foreignType);
  12050. if (moduleMethodInstance)
  12051. return ReferenceExternalMethodInstance(moduleMethodInstance.mMethodInstance, flags);
  12052. return moduleMethodInst;
  12053. }
  12054. bool isReified = mIsReified /* || ((flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass) != 0)*/;
  12055. bool hadConcreteInterfaceGenericArgument = false;
  12056. if ((flags & BfGetMethodInstanceFlag_Unreified) != 0)
  12057. isReified = false;
  12058. if ((flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass) != 0)
  12059. {
  12060. isReified = false;
  12061. }
  12062. BfTypeVector sanitizedMethodGenericArguments;
  12063. SizedArray<BfProject*, 4> projectList;
  12064. bool isUnspecializedPass = (flags & BfGetMethodInstanceFlag_UnspecializedPass) != 0;
  12065. if ((isUnspecializedPass) && (methodDef->mGenericParams.size() == 0))
  12066. isUnspecializedPass = false;
  12067. // 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
  12068. bool isExternalExtensionMethod = false;
  12069. if ((!typeInst->IsUnspecializedType()) && (!isUnspecializedPass))
  12070. {
  12071. if (((flags & BfGetMethodInstanceFlag_ForeignMethodDef) == 0) &&
  12072. (methodDef->mDeclaringType != NULL) &&
  12073. (methodDef->mDeclaringType->mProject != typeInst->mTypeDef->mProject))
  12074. {
  12075. auto specProject = methodDef->mDeclaringType->mProject;
  12076. isExternalExtensionMethod = true;
  12077. if (typeInst->IsGenericTypeInstance())
  12078. {
  12079. auto genericTypeInst = (BfTypeInstance*)typeInst;
  12080. if (genericTypeInst->mGenericTypeInfo->mProjectsReferenced.empty())
  12081. genericTypeInst->GenerateProjectsReferenced();
  12082. if (genericTypeInst->mGenericTypeInfo->mProjectsReferenced.Contains(specProject))
  12083. {
  12084. // This is a generic type where a generic param is already confined to the project in question
  12085. isExternalExtensionMethod = false;
  12086. }
  12087. }
  12088. if (isExternalExtensionMethod)
  12089. {
  12090. BF_ASSERT(typeInst->mTypeDef->mIsCombinedPartial);
  12091. projectList.push_back(methodDef->mDeclaringType->mProject);
  12092. }
  12093. }
  12094. }
  12095. if ((!isUnspecializedPass) && (methodGenericArguments.size() != 0))
  12096. {
  12097. int typeProjectsCounts = 0;
  12098. if (typeInst->IsGenericTypeInstance())
  12099. {
  12100. auto genericTypeInst = (BfTypeInstance*)typeInst;
  12101. if (genericTypeInst->mGenericTypeInfo->mProjectsReferenced.empty())
  12102. genericTypeInst->GenerateProjectsReferenced();
  12103. typeProjectsCounts = (int)genericTypeInst->mGenericTypeInfo->mProjectsReferenced.size();
  12104. projectList.Insert(0, &genericTypeInst->mGenericTypeInfo->mProjectsReferenced[0], genericTypeInst->mGenericTypeInfo->mProjectsReferenced.size());
  12105. }
  12106. else
  12107. {
  12108. typeProjectsCounts = 1;
  12109. projectList.Insert(0, typeInst->mTypeDef->mProject);
  12110. }
  12111. isUnspecializedPass = true;
  12112. for (int genericArgIdx = 0; genericArgIdx < (int) methodGenericArguments.size(); genericArgIdx++)
  12113. {
  12114. auto genericArgType = methodGenericArguments[genericArgIdx];
  12115. //BF_ASSERT(!genericArgType->IsRef());
  12116. if (genericArgType->IsConcreteInterfaceType())
  12117. {
  12118. hadConcreteInterfaceGenericArgument = true;
  12119. auto concreteInterfaceType = (BfConcreteInterfaceType*)genericArgType;
  12120. genericArgType = concreteInterfaceType->mInterface;
  12121. }
  12122. if (genericArgType->IsGenericParam())
  12123. {
  12124. auto genericParam = (BfGenericParamType*) genericArgType;
  12125. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  12126. isUnspecializedPass = false;
  12127. }
  12128. else
  12129. {
  12130. BfTypeUtils::GetProjectList(genericArgType, &projectList, typeProjectsCounts);
  12131. isUnspecializedPass = false;
  12132. }
  12133. sanitizedMethodGenericArguments.push_back(genericArgType);
  12134. }
  12135. if ((int)projectList.size() > typeProjectsCounts)
  12136. {
  12137. // Just leave the new items
  12138. projectList.RemoveRange(0, typeProjectsCounts);
  12139. std::sort(projectList.begin(), projectList.end(), [](BfProject* lhs, BfProject*rhs)
  12140. {
  12141. return lhs->mName < rhs->mName;
  12142. });
  12143. }
  12144. else
  12145. {
  12146. projectList.Clear();
  12147. }
  12148. }
  12149. const BfTypeVector& lookupMethodGenericArguments = isUnspecializedPass ? BfTypeVector() : sanitizedMethodGenericArguments;
  12150. BfMethodInstanceGroup* methodInstGroup = NULL;
  12151. if ((flags & BfGetMethodInstanceFlag_ForeignMethodDef) != 0)
  12152. {
  12153. BF_ASSERT(!typeInst->IsInterface());
  12154. //for (auto& checkGroup : typeInst->mMethodInstanceGroups)
  12155. for (int methodIdx = (int)typeInst->mTypeDef->mMethods.size(); methodIdx < (int)typeInst->mMethodInstanceGroups.size(); methodIdx++)
  12156. {
  12157. auto& checkGroup = typeInst->mMethodInstanceGroups[methodIdx];
  12158. // if (checkGroup.mDefault == NULL)
  12159. // {
  12160. // // This should only be for when we explicitly add a spot so we can set mOnDemandKind
  12161. // BF_ASSERT(methodIdx == typeInst->mMethodInstanceGroups.size() - 1);
  12162. // methodInstGroup = &checkGroup;
  12163. // break;
  12164. // }
  12165. if ((checkGroup.mDefault != NULL) && (checkGroup.mDefault->mMethodDef == methodDef))
  12166. {
  12167. methodInstGroup = &checkGroup;
  12168. break;
  12169. }
  12170. }
  12171. if (methodInstGroup == NULL)
  12172. {
  12173. if (lookupMethodGenericArguments.size() != 0)
  12174. {
  12175. BF_ASSERT((flags & BfGetMethodInstanceFlag_ForeignMethodDef) != 0);
  12176. auto defaultMethodInstance = GetMethodInstance(typeInst, methodDef, BfTypeVector(),
  12177. (BfGetMethodInstanceFlags)((flags & (BfGetMethodInstanceFlag_ForeignMethodDef)) | BfGetMethodInstanceFlag_UnspecializedPass | BfGetMethodInstanceFlag_MethodInstanceOnly), foreignType);
  12178. methodInstGroup = defaultMethodInstance.mMethodInstance->mMethodInstanceGroup;
  12179. }
  12180. else
  12181. {
  12182. // Allocate a new entry
  12183. typeInst->mMethodInstanceGroups.Resize(typeInst->mMethodInstanceGroups.size() + 1);
  12184. methodInstGroup = &typeInst->mMethodInstanceGroups.back();
  12185. methodInstGroup->mMethodIdx = (int)typeInst->mMethodInstanceGroups.size() - 1;
  12186. methodInstGroup->mOwner = typeInst;
  12187. // if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet)
  12188. // methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  12189. if (mCompiler->mOptions.mCompileOnDemandKind == BfCompileOnDemandKind_AlwaysInclude)
  12190. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  12191. else
  12192. {
  12193. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingDecl;
  12194. if (!mIsScratchModule)
  12195. mOnDemandMethodCount++;
  12196. }
  12197. }
  12198. }
  12199. }
  12200. else
  12201. {
  12202. methodInstGroup = &typeInst->mMethodInstanceGroups[methodDef->mIdx];
  12203. }
  12204. if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet)
  12205. {
  12206. if (typeInst->mDefineState > BfTypeDefineState_DefinedAndMethodsSlotted)
  12207. {
  12208. BfLogSysM("Forcing BfMethodOnDemandKind_NotSet to BfMethodOnDemandKind_AlwaysInclude for Method:%s in Type:%p\n", methodDef->mName.c_str(), typeInst);
  12209. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  12210. }
  12211. }
  12212. BfIRFunction prevIRFunc;
  12213. bool doingRedeclare = false;
  12214. BfMethodInstance* methodInstance = NULL;
  12215. auto _SetReified = [&]()
  12216. {
  12217. if (!mCompiler->mIsResolveOnly)
  12218. BF_ASSERT(mCompiler->mCompileState <= BfCompiler::CompileState_Normal);
  12219. methodInstance->mIsReified = true;
  12220. };
  12221. if (lookupMethodGenericArguments.size() == 0)
  12222. {
  12223. methodInstance = methodInstGroup->mDefault;
  12224. if ((methodInstance != NULL) && ((flags & BfGetMethodInstanceFlag_MethodInstanceOnly) != 0))
  12225. return methodInstance;
  12226. if ((methodInstance != NULL) && (isReified) && (!methodInstance->mIsReified))
  12227. {
  12228. MarkDerivedDirty(typeInst);
  12229. if (!HasCompiledOutput())
  12230. {
  12231. BfLogSysM("Marking non-compiled-output module method instance as reified: %p\n", methodInstance);
  12232. _SetReified();
  12233. CheckHotMethod(methodInstance, "");
  12234. }
  12235. else if ((flags & BfGetMethodInstanceFlag_NoForceReification) != 0)
  12236. {
  12237. // We don't need to force reification if we're in an unspecialized generic- we can wait for
  12238. // the specializations to handle that for us
  12239. return BfModuleMethodInstance(methodInstance);
  12240. }
  12241. else if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_Referenced)
  12242. {
  12243. if (methodDef->mIsAbstract)
  12244. {
  12245. BfLogSysM("Reifying abstract unreified method instance: %p IRFunction:%d\n", methodInstance, methodInstance->mIRFunction.mId);
  12246. _SetReified();
  12247. }
  12248. else
  12249. {
  12250. BfLogSysM("Re-declaring processed but unreified method instance: %p IRFunction:%d\n", methodInstance, methodInstance->mIRFunction.mId);
  12251. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_NoDecl_AwaitingReference;
  12252. methodInstance->UndoDeclaration(!methodInstance->mIRFunction.IsFake());
  12253. doingRedeclare = true;
  12254. mOnDemandMethodCount++;
  12255. VerifyOnDemandMethods();
  12256. }
  12257. }
  12258. else
  12259. {
  12260. BfLogSysM("Marking unprocessed method instance as reified: %p\n", methodInstance);
  12261. // We haven't processed it yet
  12262. _SetReified();
  12263. CheckHotMethod(methodInstance, "");
  12264. if (methodInstance->mDeclModule == this)
  12265. {
  12266. if (methodInstance->mMethodProcessRequest != NULL)
  12267. {
  12268. // Disconnect method process request
  12269. BF_ASSERT(methodInstance->mMethodProcessRequest->mFromModule == this);
  12270. }
  12271. }
  12272. else
  12273. {
  12274. if (methodInstance->mMethodProcessRequest != NULL)
  12275. {
  12276. // Disconnect method process request
  12277. methodInstance->mMethodProcessRequest->mMethodInstance = NULL;
  12278. methodInstance->mMethodProcessRequest = NULL;
  12279. }
  12280. if (methodInstance->mDeclModule == mContext->mUnreifiedModule)
  12281. {
  12282. // Add new request in proper module
  12283. methodInstance->mDeclModule = this;
  12284. }
  12285. else
  12286. {
  12287. if (methodInstance->mDeclModule == NULL)
  12288. {
  12289. //
  12290. }
  12291. else if (methodInstance->mDeclModule != this)
  12292. {
  12293. // Is from specialized module?
  12294. BF_ASSERT(methodInstance->mDeclModule->mParentModule == this);
  12295. }
  12296. }
  12297. if ((!methodInstance->mIRFunction) || (methodInstance->mIRFunction.IsFake()))
  12298. {
  12299. methodInstance->mIRFunction = BfIRFunction();
  12300. if (!mIsModuleMutable)
  12301. StartExtension();
  12302. if ((!mBfIRBuilder->mIgnoreWrites) && (methodInstance->mDeclModule != NULL))
  12303. {
  12304. StringT<512> mangledName;
  12305. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  12306. bool isIntrinsic = false;
  12307. SetupIRFunction(methodInstance, mangledName, false, &isIntrinsic);
  12308. BfLogSysM("Creating new IRFunction %d\n", methodInstance->mIRFunction.mId);
  12309. }
  12310. }
  12311. AddMethodToWorkList(methodInstance);
  12312. }
  12313. }
  12314. }
  12315. }
  12316. else
  12317. {
  12318. if (methodInstGroup->mDefault == NULL)
  12319. {
  12320. auto defaultMethodInstance = GetMethodInstance(typeInst, methodDef, BfTypeVector(),
  12321. (BfGetMethodInstanceFlags)((flags & (BfGetMethodInstanceFlag_ForeignMethodDef)) | BfGetMethodInstanceFlag_UnspecializedPass | BfGetMethodInstanceFlag_MethodInstanceOnly), foreignType);
  12322. methodInstGroup = defaultMethodInstance.mMethodInstance->mMethodInstanceGroup;
  12323. }
  12324. BF_ASSERT(lookupMethodGenericArguments.size() != 0);
  12325. if (methodInstGroup->mMethodSpecializationMap == NULL)
  12326. methodInstGroup->mMethodSpecializationMap = new BfMethodInstanceGroup::MapType();
  12327. BfMethodInstance** methodInstancePtr = NULL;
  12328. if (methodInstGroup->mMethodSpecializationMap->TryGetValue(lookupMethodGenericArguments, &methodInstancePtr))
  12329. {
  12330. methodInstance = *methodInstancePtr;
  12331. if ((flags & BfGetMethodInstanceFlag_MethodInstanceOnly) != 0)
  12332. return methodInstance;
  12333. if ((methodInstance->mRequestedByAutocomplete) && (!mCompiler->IsAutocomplete()))
  12334. {
  12335. BfLogSysM("Setting mRequestedByAutocomplete=false for method instance %p\n", methodInstance);
  12336. // We didn't want to process this message yet if it was autocomplete-specific, but now we will
  12337. if (methodInstance->mMethodProcessRequest == NULL)
  12338. AddMethodToWorkList(methodInstance);
  12339. methodInstance->mRequestedByAutocomplete = false;
  12340. }
  12341. if ((isReified) && (!methodInstance->mIsReified))
  12342. {
  12343. MarkDerivedDirty(typeInst);
  12344. if (methodInstance->mHasBeenProcessed)
  12345. {
  12346. BfLogSysM("Deleting processed but unreified specialized method instance %p\n", methodInstance);
  12347. delete methodInstance;
  12348. methodInstGroup->mMethodSpecializationMap->Remove(lookupMethodGenericArguments);
  12349. methodInstance = NULL;
  12350. }
  12351. else if ((!methodInstance->mIRFunction) || (methodInstance->mIRFunction.IsFake()))
  12352. {
  12353. BfLogSysM("Deleting declared but uncreated specialized method instance %p\n", methodInstance);
  12354. delete methodInstance;
  12355. methodInstGroup->mMethodSpecializationMap->Remove(lookupMethodGenericArguments);
  12356. methodInstance = NULL;
  12357. }
  12358. else
  12359. {
  12360. BfLogSysM("Reifying declared but unreified method instance %p\n", methodInstance);
  12361. // We haven't processed it yet
  12362. _SetReified();
  12363. CheckHotMethod(methodInstance, "");
  12364. if (methodInstance->mMethodProcessRequest == NULL)
  12365. AddMethodToWorkList(methodInstance);
  12366. }
  12367. }
  12368. }
  12369. }
  12370. if ((methodInstance != NULL) && (!doingRedeclare))
  12371. {
  12372. SetMethodDependency(methodInstance);
  12373. if (methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference)
  12374. {
  12375. /*if ((!mCompiler->mIsResolveOnly) && (!isReified))
  12376. BF_ASSERT(!methodInstance->mIsReified);*/
  12377. if (methodInstance->mIsReified != isReified)
  12378. BfLogSysM("GetMethodInstance %p Decl_AwaitingReference setting reified to %d\n", methodInstance, isReified);
  12379. if ((!isReified) &&
  12380. ((methodInstance->mDeclModule == NULL) || (!methodInstance->mDeclModule->mIsModuleMutable)))
  12381. {
  12382. methodInstance->mDeclModule = mContext->mUnreifiedModule;
  12383. methodInstance->mIRFunction = BfIRFunction();
  12384. }
  12385. methodInstance->mIsReified = isReified;
  12386. if ((methodInstance->mHotMethod != NULL) && (!mCompiler->IsHotCompile()) && (isReified))
  12387. {
  12388. methodInstance->mHotMethod->mFlags = (BfHotDepDataFlags)(methodInstance->mHotMethod->mFlags | BfHotDepDataFlag_IsOriginalBuild);
  12389. }
  12390. if (!methodInstance->mMethodDef->mIsAbstract)
  12391. {
  12392. if ((methodInstance->mMethodDef->mMethodType == BfMethodType_Mixin) && (!methodInstance->mDeclModule->mIsModuleMutable))
  12393. {
  12394. // Wait until unreified
  12395. }
  12396. else
  12397. AddMethodToWorkList(methodInstance);
  12398. }
  12399. else
  12400. {
  12401. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Referenced;
  12402. auto owningModule = methodInstance->GetOwner()->mModule;
  12403. if (!owningModule->mIsScratchModule)
  12404. {
  12405. owningModule->mOnDemandMethodCount--;
  12406. owningModule->VerifyOnDemandMethods();
  12407. }
  12408. }
  12409. }
  12410. if (mExtensionCount > 0)
  12411. {
  12412. if ((mIsModuleMutable) && (!methodInstance->mIRFunction) &&
  12413. ((projectList.IsEmpty() || ((flags & BfGetMethodInstanceFlag_ExplicitSpecializedModule) != 0))))
  12414. {
  12415. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, false);
  12416. if (mAwaitingInitFinish)
  12417. FinishInit();
  12418. // We need to refer to a function that was defined in a prior module
  12419. bool isInlined = (methodInstance->mAlwaysInline) || ((flags & BfGetMethodInstanceFlag_ForceInline) != 0);
  12420. if (methodInstance->mIsIntrinsic)
  12421. isInlined = false;
  12422. methodInstance->mIRFunction = CreateFunctionFrom(methodInstance, false, isInlined);
  12423. BF_ASSERT((methodInstance->mDeclModule == this) || (methodInstance->mDeclModule == mContext->mUnreifiedModule) || (methodInstance->mDeclModule == NULL));
  12424. methodInstance->mDeclModule = this;
  12425. // Add this inlined def to ourselves
  12426. if ((methodInstance->mAlwaysInline) && (HasCompiledOutput()) && (!methodInstance->mIsUnspecialized) && ((flags & BfGetMethodInstanceFlag_NoInline) == 0))
  12427. {
  12428. mIncompleteMethodCount++;
  12429. BfInlineMethodRequest* inlineMethodRequest = mContext->mInlineMethodWorkList.Alloc();
  12430. inlineMethodRequest->mType = typeInst;
  12431. inlineMethodRequest->mFromModule = this;
  12432. inlineMethodRequest->mFunc = methodInstance->mIRFunction;
  12433. inlineMethodRequest->mFromModuleRevision = mRevision;
  12434. inlineMethodRequest->mMethodInstance = methodInstance;
  12435. BfLogSysM("mInlineMethodWorkList %p for method %p in module %p in GetMethodInstance\n", inlineMethodRequest, methodInstance, this);
  12436. BF_ASSERT(mIsModuleMutable);
  12437. }
  12438. }
  12439. }
  12440. if (IsSkippingExtraResolveChecks())
  12441. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  12442. else
  12443. {
  12444. if ((flags & (BfGetMethodInstanceFlag_MethodInstanceOnly | BfGetMethodInstanceFlag_NoReference)) != 0)
  12445. return methodInstance;
  12446. if (methodInstance->mDeclModule != this)
  12447. return ReferenceExternalMethodInstance(methodInstance, flags);
  12448. if ((!methodInstance->mIRFunction) && (mIsModuleMutable) && (!mBfIRBuilder->mIgnoreWrites))
  12449. {
  12450. auto importKind = methodInstance->GetImportCallKind();
  12451. if (importKind != BfImportCallKind_None)
  12452. {
  12453. BfLogSysM("DllImportGlobalVar creating %p\n", methodInstance);
  12454. methodInstance->mIRFunction = mBfIRBuilder->GetFakeVal();
  12455. auto func = CreateDllImportGlobalVar(methodInstance, true);
  12456. BF_ASSERT(func);
  12457. mFuncReferences[methodInstance] = func;
  12458. }
  12459. }
  12460. return BfModuleMethodInstance(methodInstance);
  12461. }
  12462. }
  12463. if (!doingRedeclare)
  12464. {
  12465. BfModule* specModule = NULL;
  12466. if ((!keepInCurrentModule) && (projectList.size() > 0) && (!isUnspecializedPass) && (HasCompiledOutput()) && (!mIsScratchModule))
  12467. {
  12468. specModule = GetSpecializedMethodModule(projectList);
  12469. }
  12470. if ((specModule != NULL) && (specModule != this))
  12471. {
  12472. auto specMethodInstance = specModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ExplicitSpecializedModule));
  12473. if (mAwaitingInitFinish)
  12474. return BfModuleMethodInstance(specMethodInstance.mMethodInstance, BfIRFunction());
  12475. if ((flags & (BfGetMethodInstanceFlag_MethodInstanceOnly | BfGetMethodInstanceFlag_NoReference)) != 0)
  12476. return specMethodInstance.mMethodInstance;
  12477. return ReferenceExternalMethodInstance(specMethodInstance.mMethodInstance, flags);
  12478. }
  12479. if ((!isUnspecializedPass) && (methodGenericArguments.size() != 0) && (methodInstGroup->mDefault == NULL))
  12480. {
  12481. // We are attempting to specialize but we don't have the unspecialized method yet. Generate that first.
  12482. GetMethodInstance(typeInst, methodDef, BfTypeVector(), BfGetMethodInstanceFlag_UnspecializedPass);
  12483. }
  12484. }
  12485. if (methodInstance == NULL)
  12486. {
  12487. if (!mCompiler->EnsureCeUnpaused(typeInst))
  12488. {
  12489. BfLogSysM("GetMethodInstance (methodInstance == NULL) bailing due to IsCePaused\n");
  12490. return BfModuleMethodInstance();
  12491. }
  12492. if (lookupMethodGenericArguments.size() == 0)
  12493. {
  12494. BF_ASSERT(methodInstGroup->mDefault == NULL);
  12495. methodInstance = new BfMethodInstance();
  12496. methodInstGroup->mDefault = methodInstance;
  12497. BF_ASSERT(typeInst->mDefineState > BfTypeDefineState_Declared);
  12498. BfLogSysM("Created Default MethodInst: %p TypeInst: %p Group: %p\n", methodInstance, typeInst, methodInstGroup);
  12499. }
  12500. else
  12501. {
  12502. bool depthExceeded = ((flags & BfGetMethodInstanceFlag_DepthExceeded) != 0);
  12503. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mMinDependDepth >= 32))
  12504. depthExceeded = true;
  12505. if (depthExceeded)
  12506. {
  12507. Fail("Generic method dependency depth exceeded", methodDef->GetRefNode());
  12508. return BfModuleMethodInstance();
  12509. }
  12510. BfMethodInstance** methodInstancePtr = NULL;
  12511. bool added = methodInstGroup->mMethodSpecializationMap->TryAdd(lookupMethodGenericArguments, NULL, &methodInstancePtr);
  12512. BF_ASSERT(added);
  12513. methodInstance = new BfMethodInstance();
  12514. *methodInstancePtr = methodInstance;
  12515. if (mCompiler->IsAutocomplete())
  12516. methodInstance->mRequestedByAutocomplete = true;
  12517. BfLogSysM("Created Specialized MethodInst: %p TypeInst: %p\n", methodInstance, typeInst);
  12518. }
  12519. if ((prevIRFunc) && (!prevIRFunc.IsFake()))
  12520. methodInstance->mIRFunction = prevIRFunc; // Take it over
  12521. }
  12522. methodInstance->mMethodDef = methodDef;
  12523. methodInstance->mAlwaysInline = methodDef->mAlwaysInline;
  12524. methodInstance->mMethodInstanceGroup = methodInstGroup;
  12525. methodInstance->mIsReified = isReified;
  12526. SetupMethodIdHash(methodInstance);
  12527. if (hadConcreteInterfaceGenericArgument)
  12528. methodInstance->mIgnoreBody = true;
  12529. if ((flags & BfGetMethodInstanceFlag_ForeignMethodDef) != 0)
  12530. {
  12531. methodInstance->mIsForeignMethodDef = true;
  12532. BF_ASSERT(foreignType != NULL);
  12533. methodInstance->GetMethodInfoEx()->mForeignType = foreignType;
  12534. }
  12535. if ((typeInst->IsInstanceOf(mCompiler->mValueTypeTypeDef)) && (methodDef->mName == BF_METHODNAME_EQUALS))
  12536. {
  12537. if (!lookupMethodGenericArguments.empty())
  12538. {
  12539. auto compareType = lookupMethodGenericArguments[0];
  12540. PopulateType(compareType, BfPopulateType_Data);
  12541. if (compareType->IsSplattable())
  12542. methodInstance->mAlwaysInline = true;
  12543. }
  12544. }
  12545. if (methodDef->mMethodType == BfMethodType_Init)
  12546. {
  12547. methodInstance->mMangleWithIdx = true;
  12548. }
  12549. BF_ASSERT(typeInst == methodInstance->GetOwner());
  12550. auto methodDeclaration = methodDef->GetMethodDeclaration();
  12551. if (isUnspecializedPass)
  12552. {
  12553. for (int genericParamIdx = 0; genericParamIdx < (int) methodDef->mGenericParams.size(); genericParamIdx++)
  12554. {
  12555. auto genericParamType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  12556. methodInstance->GetMethodInfoEx()->mMethodGenericArguments.Add(genericParamType);
  12557. }
  12558. }
  12559. else if ((methodDeclaration != NULL) && (methodDeclaration->mGenericParams != NULL))
  12560. {
  12561. if (!sanitizedMethodGenericArguments.IsEmpty())
  12562. methodInstance->GetMethodInfoEx()->mMethodGenericArguments = sanitizedMethodGenericArguments;
  12563. if (methodDef->mGenericParams.size() != sanitizedMethodGenericArguments.size())
  12564. {
  12565. Fail("Internal error");
  12566. BFMODULE_FATAL(this, "Generic method argument counts mismatch");
  12567. return NULL;
  12568. }
  12569. for (auto genericArg : sanitizedMethodGenericArguments)
  12570. {
  12571. if (genericArg->IsPrimitiveType())
  12572. genericArg = GetWrappedStructType(genericArg);
  12573. if (genericArg != NULL)
  12574. AddDependency(genericArg, typeInst, BfDependencyMap::DependencyFlag_MethodGenericArg);
  12575. }
  12576. }
  12577. // Generic constraints
  12578. if (!methodDef->mGenericParams.IsEmpty())
  12579. {
  12580. BF_ASSERT(methodInstance->GetMethodInfoEx()->mGenericParams.IsEmpty());
  12581. for (int genericParamIdx = 0; genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  12582. {
  12583. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, genericParamIdx);
  12584. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  12585. }
  12586. }
  12587. for (int externConstraintIdx = 0; externConstraintIdx < (int)methodDef->mExternalConstraints.size(); externConstraintIdx++)
  12588. {
  12589. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, externConstraintIdx + (int)methodDef->mGenericParams.size());
  12590. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  12591. }
  12592. bool addToWorkList = !processNow;
  12593. if (mCompiler->GetAutoComplete() != NULL)
  12594. {
  12595. if (typeInst->IsSpecializedByAutoCompleteMethod())
  12596. addToWorkList = false;
  12597. if (methodInstance->mRequestedByAutocomplete)
  12598. addToWorkList = false;
  12599. }
  12600. BfModule* declareModule;
  12601. //
  12602. {
  12603. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  12604. declareModule = GetOrCreateMethodModule(methodInstance);
  12605. }
  12606. if ((doingRedeclare) && (methodInstance->mDeclModule != mContext->mUnreifiedModule))
  12607. declareModule = methodInstance->mDeclModule;
  12608. BF_ASSERT(declareModule != NULL);
  12609. methodInstance->mDeclModule = declareModule;
  12610. if ((!methodInstance->mIsReified) && (mCompiler->mCompileState != BfCompiler::CompileState_Normal))
  12611. {
  12612. // We can be sure this method won't become reified later. Normally we can "go either way" with an unreified method
  12613. // of a reified module -
  12614. // If we declare it in the reified module then we can switch it to "reified" before actual processing without any extra work,
  12615. // BUT if we don't reify it then we have to remove the body after processing.
  12616. // 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
  12617. // the proper reified module.
  12618. declareModule = mContext->mUnreifiedModule;
  12619. }
  12620. else if ((!declareModule->mIsModuleMutable) && (!mCompiler->mIsResolveOnly))
  12621. {
  12622. if (!methodInstance->mIsReified)
  12623. {
  12624. declareModule = mContext->mUnreifiedModule;
  12625. }
  12626. else
  12627. {
  12628. declareModule->PrepareForIRWriting(methodInstance->GetOwner());
  12629. }
  12630. }
  12631. SetMethodDependency(methodInstance);
  12632. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  12633. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(declareModule->mCurTypeInstance, typeInst);
  12634. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  12635. if ((methodDef->mMethodType == BfMethodType_Mixin) && (methodDef->mGenericParams.size() != 0) && (!isUnspecializedPass))
  12636. {
  12637. // For mixins we only process the unspecialized version
  12638. addToWorkList = false;
  12639. }
  12640. if (((flags & BfGetMethodInstanceFlag_MethodInstanceOnly) != 0) && (methodInstGroup->mOnDemandKind != BfMethodOnDemandKind_AlwaysInclude))
  12641. {
  12642. addToWorkList = false;
  12643. }
  12644. // if ((flags & BfGetMethodInstanceFlag_NoReference) != 0)
  12645. // addToWorkList = false;
  12646. declareModule->DoMethodDeclaration(methodDef->GetMethodDeclaration(), false, addToWorkList);
  12647. if (processNow)
  12648. {
  12649. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, NULL);
  12650. ProcessMethod(methodInstance);
  12651. }
  12652. if (IsSkippingExtraResolveChecks())
  12653. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  12654. if (methodInstance->mDeclModule != this)
  12655. return ReferenceExternalMethodInstance(methodInstance, flags);
  12656. return BfModuleMethodInstance(methodInstance);
  12657. }
  12658. BfModuleMethodInstance BfModule::GetMethodInstance(BfMethodInstance* methodInstance, BfGetMethodInstanceFlags flags)
  12659. {
  12660. BF_ASSERT((methodInstance->mMethodInfoEx == NULL) || (methodInstance->mMethodInfoEx->mGenericParams.IsEmpty()));
  12661. if (methodInstance->mIsForeignMethodDef)
  12662. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ForeignMethodDef);
  12663. return GetMethodInstance(methodInstance->GetOwner(), methodInstance->mMethodDef, BfTypeVector(), flags);
  12664. }
  12665. BfMethodInstance* BfModule::GetOuterMethodInstance(BfMethodInstance* methodInstance)
  12666. {
  12667. if (!methodInstance->mMethodDef->mIsLocalMethod)
  12668. return NULL;
  12669. auto outerLocal = methodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod->mOuterLocalMethod;
  12670. if (outerLocal == NULL)
  12671. return NULL;
  12672. BfTypeVector genericArgs;
  12673. for (int i = 0; i < (int)outerLocal->mMethodDef->mGenericParams.size(); i++)
  12674. genericArgs.Add(methodInstance->mMethodInfoEx->mMethodGenericArguments[i]);
  12675. return GetLocalMethodInstance(outerLocal, genericArgs).mMethodInstance;
  12676. }
  12677. void BfModule::SetupMethodIdHash(BfMethodInstance* methodInstance)
  12678. {
  12679. HashContext hashCtx;
  12680. std::function<void(BfMethodInstance*)> _MixinMethodInstance = [&](BfMethodInstance* methodInstance)
  12681. {
  12682. hashCtx.Mixin(methodInstance->GetOwner()->mTypeId);
  12683. hashCtx.Mixin(methodInstance->mMethodDef->mIdx);
  12684. if (methodInstance->GetNumGenericArguments() != 0)
  12685. {
  12686. hashCtx.Mixin((int32)methodInstance->mMethodInfoEx->mMethodGenericArguments.size());
  12687. for (auto methodGenericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  12688. hashCtx.Mixin(methodGenericArg->mTypeId);
  12689. }
  12690. };
  12691. _MixinMethodInstance(methodInstance);
  12692. if (methodInstance->mMethodDef->mIsLocalMethod)
  12693. {
  12694. auto outmostMethodInstance = mCurMethodState->GetRootMethodState()->mMethodInstance;
  12695. if (outmostMethodInstance != NULL)
  12696. {
  12697. BF_ASSERT((outmostMethodInstance->mIdHash != 0) || (outmostMethodInstance->mIsAutocompleteMethod));
  12698. hashCtx.Mixin(outmostMethodInstance->mIdHash);
  12699. }
  12700. }
  12701. methodInstance->mIdHash = (int64)hashCtx.Finish64();
  12702. }
  12703. bool BfModule::CheckUseMethodInstance(BfMethodInstance* methodInstance, BfAstNode* refNode)
  12704. {
  12705. if (methodInstance->mHasBeenDeclared)
  12706. return true;
  12707. Fail(StrFormat("Circular reference in method instance '%s'", MethodToString(methodInstance).c_str()), refNode);
  12708. return false;
  12709. }
  12710. BfIRValue BfModule::GetInterfaceSlotNum(BfTypeInstance* ifaceType)
  12711. {
  12712. BfIRValue globalValue;
  12713. BfIRValue* globalValuePtr = NULL;
  12714. if (mInterfaceSlotRefs.TryGetValue(ifaceType, &globalValuePtr))
  12715. {
  12716. globalValue = *globalValuePtr;
  12717. }
  12718. if (!globalValue)
  12719. {
  12720. // This is necessary to reify the interface type
  12721. PopulateType(ifaceType);
  12722. StringT<512> slotVarName;
  12723. BfMangler::MangleStaticFieldName(slotVarName, mCompiler->GetMangleKind(), ifaceType, "sBfSlotOfs");
  12724. BfType* intType = GetPrimitiveType(BfTypeCode_Int32);
  12725. BfIRValue value;
  12726. if ((mCompiler->mHotState != NULL) && (ifaceType->mSlotNum >= 0))
  12727. {
  12728. /*// If this interface already existed before this hot compile but we never indirectly called any of its methods
  12729. // then the sBfSlotOfs could have gotten its symbol stripped, so actually define it here.
  12730. int virtSlotIdx = ifaceType->mSlotNum + 1;
  12731. value = GetConstValue32(virtSlotIdx);*/
  12732. mCompiler->mHotState->mSlotDefineTypeIds.Add(ifaceType->mTypeId);
  12733. ifaceType->mDirty = true; // Makes sure we create interface in vdata
  12734. }
  12735. globalValue = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(intType), true, BfIRLinkageType_External, value, slotVarName);
  12736. mInterfaceSlotRefs[ifaceType] = globalValue;
  12737. }
  12738. return mBfIRBuilder->CreateAlignedLoad(globalValue/*, "slotOfs"*/, 4);
  12739. }
  12740. void BfModule::HadSlotCountDependency()
  12741. {
  12742. if (mCompiler->mIsResolveOnly)
  12743. return;
  12744. BF_ASSERT(!mBfIRBuilder->mIgnoreWrites);
  12745. BF_ASSERT((mUsedSlotCount == BF_MAX(mCompiler->mMaxInterfaceSlots, 0)) || (mUsedSlotCount == -1));
  12746. mUsedSlotCount = BF_MAX(mCompiler->mMaxInterfaceSlots, 0);
  12747. }
  12748. BfTypedValue BfModule::GetCompilerFieldValue(const StringImpl& str)
  12749. {
  12750. if (str == "#IsComptime")
  12751. {
  12752. return BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Boolean, mIsComptimeModule ? 1 : 0), GetPrimitiveType(BfTypeCode_Boolean));
  12753. }
  12754. if (str == "#IsBuilding")
  12755. {
  12756. return BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Boolean, (!mCompiler->mIsResolveOnly) ? 1 : 0), GetPrimitiveType(BfTypeCode_Boolean));
  12757. }
  12758. if (str == "#IsReified")
  12759. {
  12760. return BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Boolean, mIsReified ? 1 : 0), GetPrimitiveType(BfTypeCode_Boolean));
  12761. }
  12762. if (str == "#CompileRev")
  12763. {
  12764. return BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Int32, mCompiler->mRevision), GetPrimitiveType(BfTypeCode_Int32));
  12765. }
  12766. if (str == "#NextId")
  12767. {
  12768. return BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Int64, (uint64)++mCompiler->mUniqueId), GetPrimitiveType(BfTypeCode_Int32));
  12769. }
  12770. if (str == "#ModuleName")
  12771. {
  12772. return BfTypedValue(GetStringObjectValue(mModuleName), ResolveTypeDef(mCompiler->mStringTypeDef));
  12773. }
  12774. if (str == "#ProjectName")
  12775. {
  12776. if (mProject != NULL)
  12777. return BfTypedValue(GetStringObjectValue(mProject->mName), ResolveTypeDef(mCompiler->mStringTypeDef));
  12778. }
  12779. if (str == "#AllocStackCount")
  12780. {
  12781. return BfTypedValue(mBfIRBuilder->CreateConst(BfTypeCode_Int32, mCompiler->mOptions.mAllocStackCount), GetPrimitiveType(BfTypeCode_Int32));
  12782. }
  12783. if (mCurMethodState->mMixinState != NULL)
  12784. {
  12785. if (str == "#CallerLineNum")
  12786. {
  12787. return BfTypedValue(GetConstValue(mCurMethodState->mMixinState->mInjectFilePosition.mCurLine + 1), GetPrimitiveType(BfTypeCode_Int32));
  12788. }
  12789. else if (str == "#CallerFilePath")
  12790. {
  12791. String filePath = "";
  12792. if (mCurMethodState->mMixinState->mInjectFilePosition.mFileInstance != NULL)
  12793. filePath = mCurMethodState->mMixinState->mInjectFilePosition.mFileInstance->mParser->mFileName;
  12794. return BfTypedValue(GetStringObjectValue(filePath), ResolveTypeDef(mCompiler->mStringTypeDef));
  12795. }
  12796. else if (str == "#CallerFileName")
  12797. {
  12798. String filePath = "";
  12799. if (mCurMethodState->mMixinState->mInjectFilePosition.mFileInstance != NULL)
  12800. filePath = mCurMethodState->mMixinState->mInjectFilePosition.mFileInstance->mParser->mFileName;
  12801. return BfTypedValue(GetStringObjectValue(GetFileName(filePath)), ResolveTypeDef(mCompiler->mStringTypeDef));
  12802. }
  12803. else if (str == "#CallerFileDir")
  12804. {
  12805. String filePath = "";
  12806. if (mCurMethodState->mMixinState->mInjectFilePosition.mFileInstance != NULL)
  12807. filePath = mCurMethodState->mMixinState->mInjectFilePosition.mFileInstance->mParser->mFileName;
  12808. return BfTypedValue(GetStringObjectValue(GetFileDir(filePath)), ResolveTypeDef(mCompiler->mStringTypeDef));
  12809. }
  12810. else if (str == "#CallerTypeName")
  12811. {
  12812. String typeName = "";
  12813. if (mCurMethodState->mMixinState->mMixinMethodInstance)
  12814. typeName = TypeToString(mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner());
  12815. return BfTypedValue(GetStringObjectValue(typeName), ResolveTypeDef(mCompiler->mStringTypeDef));
  12816. }
  12817. else if (str == "#CallerType")
  12818. {
  12819. auto typeType = ResolveTypeDef(mCompiler->mTypeTypeDef);
  12820. BfType* type = NULL;
  12821. if (mCurMethodState->mMixinState->mMixinMethodInstance)
  12822. type = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  12823. if (type != NULL)
  12824. {
  12825. AddDependency(type, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  12826. return BfTypedValue(CreateTypeDataRef(type), typeType);
  12827. }
  12828. }
  12829. else if (str == "#CallerMemberName")
  12830. {
  12831. String memberName = "";
  12832. if (mCurMethodState->mMixinState->mMixinMethodInstance)
  12833. memberName = MethodToString(mCurMethodState->mMixinState->mMixinMethodInstance);
  12834. return BfTypedValue(GetStringObjectValue(memberName), ResolveTypeDef(mCompiler->mStringTypeDef));
  12835. }
  12836. else if (str == "#CallerProject")
  12837. {
  12838. BfProject* project = NULL;
  12839. project = mCurMethodState->mMixinState->mMixinMethodInstance->mMethodDef->mDeclaringType->mProject;
  12840. if (project != NULL)
  12841. return BfTypedValue(GetStringObjectValue(mProject->mName), ResolveTypeDef(mCompiler->mStringTypeDef));
  12842. }
  12843. }
  12844. if (str == "#TimeLocal")
  12845. {
  12846. time_t rawtime;
  12847. time(&rawtime);
  12848. tm* timeinfo = localtime(&rawtime);
  12849. char result[32];
  12850. sprintf(result, "%d/%.2d/%.2d %.2d:%.2d:%.2d",
  12851. 1900 + timeinfo->tm_year,
  12852. timeinfo->tm_mon,
  12853. timeinfo->tm_mday,
  12854. timeinfo->tm_hour,
  12855. timeinfo->tm_min,
  12856. timeinfo->tm_sec);
  12857. return BfTypedValue(GetStringObjectValue(result), ResolveTypeDef(mCompiler->mStringTypeDef));
  12858. }
  12859. return BfTypedValue();
  12860. }
  12861. BfTypedValue BfModule::GetCompilerFieldValue(BfTypedValue typedValue)
  12862. {
  12863. if (!typedValue.IsAddr())
  12864. return BfTypedValue();
  12865. if (typedValue.mValue.IsConst())
  12866. {
  12867. auto constantValue = mBfIRBuilder->GetConstant(typedValue.mValue);
  12868. if (constantValue != NULL)
  12869. {
  12870. if (constantValue->mConstType == BfConstType_GlobalVar)
  12871. {
  12872. auto globalVar = (BfGlobalVar*)constantValue;
  12873. if (globalVar->mName[0] == '#')
  12874. {
  12875. BfTypedValue result = GetCompilerFieldValue(globalVar->mName);
  12876. return result;
  12877. }
  12878. }
  12879. }
  12880. }
  12881. return BfTypedValue();
  12882. }
  12883. BfTypedValue BfModule::ReferenceStaticField(BfFieldInstance* fieldInstance)
  12884. {
  12885. BfIRValue globalValue;
  12886. auto fieldDef = fieldInstance->GetFieldDef();
  12887. if ((fieldDef->mIsConst) && (!fieldDef->mIsExtern))
  12888. {
  12889. if (fieldInstance->mConstIdx != -1)
  12890. {
  12891. auto constant = fieldInstance->mOwner->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  12892. return BfTypedValue(ConstantToCurrent(constant, fieldInstance->mOwner->mConstHolder, fieldInstance->GetResolvedType()), fieldInstance->GetResolvedType());
  12893. }
  12894. else
  12895. {
  12896. return GetDefaultTypedValue(fieldInstance->GetResolvedType());
  12897. }
  12898. }
  12899. if ((mIsScratchModule) && (mCompiler->mIsResolveOnly) && (!fieldInstance->mOwner->IsInstanceOf(mCompiler->mCompilerTypeDef)))
  12900. {
  12901. // Just fake it for the extern and unspecialized modules
  12902. // We can't do this for compilation because unreified methods with default params need to get actual global variable refs
  12903. return BfTypedValue(mBfIRBuilder->CreateConstNull(), fieldInstance->GetResolvedType(), true);
  12904. }
  12905. BfIRValue* globalValuePtr = NULL;
  12906. if (mStaticFieldRefs.TryGetValue(fieldInstance, &globalValuePtr))
  12907. {
  12908. globalValue = *globalValuePtr;
  12909. BF_ASSERT(globalValue);
  12910. auto globalVar = (BfGlobalVar*)mBfIRBuilder->GetConstant(globalValue);
  12911. if ((globalVar->mStreamId == -1) && (!mBfIRBuilder->mIgnoreWrites))
  12912. {
  12913. mBfIRBuilder->MapType(fieldInstance->mResolvedType);
  12914. mBfIRBuilder->CreateGlobalVariable(globalValue);
  12915. }
  12916. }
  12917. else
  12918. {
  12919. StringT<512> staticVarName;
  12920. BfMangler::Mangle(staticVarName, mCompiler->GetMangleKind(), fieldInstance);
  12921. auto typeType = fieldInstance->GetResolvedType();
  12922. if ((fieldDef->mIsExtern) && (fieldDef->mIsConst) && (typeType->IsPointer()))
  12923. {
  12924. typeType = typeType->GetUnderlyingType();
  12925. }
  12926. if (mIsComptimeModule)
  12927. {
  12928. mCompiler->mCeMachine->QueueStaticField(fieldInstance, staticVarName);
  12929. }
  12930. PopulateType(typeType);
  12931. if ((typeType != NULL) && (!typeType->IsValuelessType()))
  12932. {
  12933. BfIRType irType = mBfIRBuilder->MapType(typeType);
  12934. if (fieldInstance->IsAppendedObject())
  12935. irType = mBfIRBuilder->MapTypeInst(typeType->ToTypeInstance());
  12936. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mBfIRBuilder->mIgnoreWrites || staticVarName.StartsWith('#'));
  12937. globalValue = mBfIRBuilder->CreateGlobalVariable(
  12938. irType,
  12939. false,
  12940. BfIRLinkageType_External,
  12941. BfIRValue(),
  12942. staticVarName,
  12943. IsThreadLocal(fieldInstance));
  12944. BF_ASSERT(globalValue);
  12945. mStaticFieldRefs[fieldInstance] = globalValue;
  12946. BfLogSysM("Mod:%p Type:%p ReferenceStaticField %p -> %p\n", this, fieldInstance->mOwner, fieldInstance, globalValue);
  12947. }
  12948. }
  12949. auto type = fieldInstance->GetResolvedType();
  12950. if (type->IsValuelessType())
  12951. return BfTypedValue(globalValue, type);
  12952. if (fieldDef->mIsVolatile)
  12953. return BfTypedValue(globalValue, type, BfTypedValueKind_VolatileAddr);
  12954. return BfTypedValue(globalValue, type, !fieldDef->mIsConst && !fieldInstance->IsAppendedObject());
  12955. }
  12956. BfFieldInstance* BfModule::GetFieldInstance(BfTypeInstance* typeInst, int fieldIdx, const char* fieldName)
  12957. {
  12958. if (typeInst->IsDataIncomplete())
  12959. PopulateType(typeInst);
  12960. if (fieldIdx >= typeInst->mFieldInstances.mSize)
  12961. {
  12962. Fail(StrFormat("Invalid field data in type '%s'", TypeToString(typeInst).c_str()));
  12963. return 0;
  12964. }
  12965. return &typeInst->mFieldInstances[fieldIdx];
  12966. }
  12967. void BfModule::MarkUsingThis()
  12968. {
  12969. auto useMethodState = mCurMethodState;
  12970. while ((useMethodState != NULL) && (useMethodState->mClosureState != NULL) && (useMethodState->mClosureState->mCapturing))
  12971. {
  12972. useMethodState = useMethodState->mPrevMethodState;
  12973. }
  12974. if ((useMethodState != NULL) && (!useMethodState->mLocals.IsEmpty()))
  12975. {
  12976. auto localVar = useMethodState->mLocals[0];
  12977. if (localVar->mIsThis)
  12978. localVar->mReadFromId = useMethodState->GetRootMethodState()->mCurAccessId++;
  12979. }
  12980. }
  12981. BfTypedValue BfModule::GetThis(bool markUsing)
  12982. {
  12983. if ((mIsComptimeModule) && (mCompiler->mCeMachine->mDebugger != NULL) && (mCompiler->mCeMachine->mDebugger->mCurDbgState != NULL))
  12984. {
  12985. if (mCompiler->mCeMachine->mDebugger->mCurDbgState->mExplicitThis)
  12986. return mCompiler->mCeMachine->mDebugger->mCurDbgState->mExplicitThis;
  12987. auto ceDebugger = mCompiler->mCeMachine->mDebugger;
  12988. auto activeFrame = ceDebugger->mCurDbgState->mActiveFrame;
  12989. if ((activeFrame != NULL) && (activeFrame->mFunction->mDbgInfo != NULL))
  12990. {
  12991. for (auto& dbgVar : activeFrame->mFunction->mDbgInfo->mVariables)
  12992. {
  12993. if (dbgVar.mName == "this")
  12994. return BfTypedValue(mBfIRBuilder->CreateConstAggCE(mBfIRBuilder->MapType(dbgVar.mType), activeFrame->mFrameAddr + dbgVar.mValue.mFrameOfs), dbgVar.mType,
  12995. dbgVar.mIsConst ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  12996. }
  12997. }
  12998. return BfTypedValue();
  12999. }
  13000. auto useMethodState = mCurMethodState;
  13001. while ((useMethodState != NULL) && (useMethodState->mClosureState != NULL) && (useMethodState->mClosureState->mCapturing))
  13002. {
  13003. useMethodState = useMethodState->mPrevMethodState;
  13004. }
  13005. if (useMethodState != NULL)
  13006. {
  13007. // Fake a 'this' for var field resolution
  13008. if (useMethodState->mTempKind == BfMethodState::TempKind_NonStatic)
  13009. {
  13010. auto thisType = mCurTypeInstance;
  13011. if (thisType->IsValueType())
  13012. return BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(thisType)), thisType, BfTypedValueKind_ThisAddr);
  13013. else
  13014. return BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInst(thisType)), thisType, BfTypedValueKind_ThisValue);
  13015. }
  13016. else if (useMethodState->mTempKind == BfMethodState::TempKind_Static)
  13017. {
  13018. return BfTypedValue();
  13019. }
  13020. }
  13021. else
  13022. {
  13023. //TODO: Do we allow useMethodState to be NULL anymore?
  13024. return BfTypedValue();
  13025. }
  13026. // Check mixin state for 'this'
  13027. {
  13028. auto checkMethodState = mCurMethodState;
  13029. while (checkMethodState != NULL)
  13030. {
  13031. if (checkMethodState->mMixinState != NULL)
  13032. {
  13033. BfTypedValue thisValue = checkMethodState->mMixinState->mTarget;
  13034. if (thisValue.HasType())
  13035. {
  13036. checkMethodState->mMixinState->mLastTargetAccessId = useMethodState->GetRootMethodState()->mCurAccessId++;
  13037. if (!thisValue.mType->IsValueType())
  13038. thisValue = LoadValue(thisValue);
  13039. return thisValue;
  13040. }
  13041. }
  13042. checkMethodState = checkMethodState->mPrevMethodState;
  13043. }
  13044. }
  13045. auto curMethodInstance = mCurMethodInstance;
  13046. if (useMethodState->mMethodInstance != NULL)
  13047. curMethodInstance = useMethodState->mMethodInstance;
  13048. if ((curMethodInstance == NULL) /*|| (!mCurMethodInstance->mIRFunction)*/ || (curMethodInstance->mMethodDef->mIsStatic))
  13049. {
  13050. if ((useMethodState->mClosureState != NULL) && (!useMethodState->mClosureState->mConstLocals.empty()))
  13051. {
  13052. auto& constLocal = useMethodState->mClosureState->mConstLocals[0];
  13053. if (constLocal.mIsThis)
  13054. {
  13055. BF_ASSERT(constLocal.mResolvedType->IsValuelessType());
  13056. return BfTypedValue(mBfIRBuilder->GetFakeVal(), constLocal.mResolvedType);
  13057. }
  13058. }
  13059. return BfTypedValue();
  13060. }
  13061. if (useMethodState->mLocals.IsEmpty())
  13062. {
  13063. // 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
  13064. BF_ASSERT(useMethodState->mPrevMethodState != NULL);
  13065. return BfTypedValue();
  13066. }
  13067. auto thisLocal = useMethodState->mLocals[0];
  13068. BF_ASSERT(thisLocal->mIsThis);
  13069. bool preferValue = !IsTargetingBeefBackend();
  13070. if (!thisLocal->mAddr)
  13071. preferValue = true;
  13072. bool usedVal = false;
  13073. BfIRValue thisValue;
  13074. if ((preferValue) && (!thisLocal->mIsLowered))
  13075. {
  13076. thisValue = thisLocal->mValue;
  13077. usedVal = true;
  13078. }
  13079. else if ((thisLocal->mIsSplat) || (thisLocal->mIsLowered))
  13080. thisValue = thisLocal->mAddr;
  13081. else
  13082. thisValue = mBfIRBuilder->CreateAlignedLoad(thisLocal->mAddr, thisLocal->mResolvedType->mAlign);
  13083. if (markUsing)
  13084. useMethodState->mLocals[0]->mReadFromId = useMethodState->GetRootMethodState()->mCurAccessId++;
  13085. if (useMethodState->mClosureState != NULL)
  13086. {
  13087. auto closureTypeInst = useMethodState->mClosureState->mClosureType;
  13088. if (closureTypeInst != NULL)
  13089. {
  13090. if (closureTypeInst->mFieldInstances.size() > 0)
  13091. {
  13092. auto& field = closureTypeInst->mFieldInstances[0];
  13093. auto fieldDef = field.GetFieldDef();
  13094. if (fieldDef->mName == "__this")
  13095. {
  13096. if (mCurMethodState->mClosureState->mCapturing)
  13097. mCurMethodState->mClosureState->mReferencedOuterClosureMembers.Add(&field);
  13098. // This is a captured 'this'
  13099. BfTypedValue result = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(thisValue, 0, field.mDataIdx), field.mResolvedType, true);
  13100. if (field.mResolvedType->IsRef())
  13101. {
  13102. auto refType = (BfRefType*)field.mResolvedType;
  13103. auto underlyingType = refType->GetUnderlyingType();
  13104. result = BfTypedValue(mBfIRBuilder->CreateLoad(result.mValue), underlyingType, true);
  13105. }
  13106. if (field.mResolvedType->IsObject())
  13107. {
  13108. result = LoadValue(result);
  13109. result.mKind = BfTypedValueKind_ThisValue;
  13110. }
  13111. else
  13112. {
  13113. if (fieldDef->mIsReadOnly)
  13114. result.mKind = BfTypedValueKind_ReadOnlyThisAddr;
  13115. else
  13116. result.mKind = BfTypedValueKind_ThisAddr;
  13117. }
  13118. return result;
  13119. }
  13120. }
  13121. return BfTypedValue();
  13122. }
  13123. if (useMethodState->mClosureState->mCapturing)
  13124. {
  13125. auto thisType = useMethodState->mLocals[0]->mResolvedType;
  13126. if (thisType->IsValueType())
  13127. return BfTypedValue(CreateAlloca(thisType), thisType, BfTypedValueKind_ThisAddr);
  13128. else
  13129. return BfTypedValue(GetDefaultValue(thisType), thisType, BfTypedValueKind_ThisValue);
  13130. }
  13131. }
  13132. if (mCurMethodInstance == NULL)
  13133. return BfTypedValue();
  13134. auto localDef = useMethodState->mLocals[0];
  13135. auto curMethodOwner = mCurMethodInstance->mMethodInstanceGroup->mOwner;
  13136. if ((curMethodOwner->IsStruct()) || (curMethodOwner->IsTypedPrimitive()))
  13137. {
  13138. if ((localDef->mResolvedType->IsTypedPrimitive()) && (!mCurMethodInstance->mMethodDef->mIsMutating))
  13139. {
  13140. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, BfTypedValueKind_ReadOnlyThisValue);
  13141. }
  13142. if (localDef->mIsSplat)
  13143. {
  13144. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, BfTypedValueKind_ThisSplatHead);
  13145. }
  13146. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, localDef->mIsReadOnly ? BfTypedValueKind_ReadOnlyThisAddr : BfTypedValueKind_ThisAddr);
  13147. }
  13148. return BfTypedValue(thisValue, mCurMethodInstance->mMethodInstanceGroup->mOwner, BfTypedValueKind_ThisValue);
  13149. }
  13150. BfLocalVariable* BfModule::GetThisVariable()
  13151. {
  13152. if (mCurMethodState == NULL)
  13153. return NULL;
  13154. auto methodState = mCurMethodState->GetNonCaptureState();
  13155. if ((methodState->mLocals.size() > 0) && (methodState->mLocals[0]->mIsThis))
  13156. return methodState->mLocals[0];
  13157. return NULL;
  13158. }
  13159. bool BfModule::IsInGeneric()
  13160. {
  13161. return ((mCurMethodInstance != NULL) && (mCurMethodInstance->GetNumGenericArguments() != 0)) || (mCurTypeInstance->IsGenericTypeInstance());
  13162. }
  13163. bool BfModule::InDefinitionSection()
  13164. {
  13165. if (mCurTypeInstance != NULL)
  13166. {
  13167. if (mCurTypeInstance->IsUnspecializedTypeVariation())
  13168. return false;
  13169. }
  13170. return !IsInSpecializedSection();
  13171. }
  13172. bool BfModule::IsInSpecializedGeneric()
  13173. {
  13174. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsSpecializedType()))
  13175. return true;
  13176. if ((mCurMethodInstance == NULL) || (mCurMethodInstance->mIsUnspecialized))
  13177. return false;
  13178. return (mCurMethodInstance->GetNumGenericArguments() != 0);
  13179. }
  13180. bool BfModule::IsInSpecializedSection()
  13181. {
  13182. return IsInSpecializedGeneric() ||
  13183. ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL));
  13184. }
  13185. bool BfModule::IsInUnspecializedGeneric()
  13186. {
  13187. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsUnspecialized))
  13188. return true;
  13189. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsUnspecializedType()))
  13190. return true;
  13191. return false;
  13192. }
  13193. //////////////////////////////////////////////////////////////////////////
  13194. BfIRValue BfModule::AllocLocalVariable(BfType* type, const StringImpl& name, bool doLifetimeEnd)
  13195. {
  13196. //if ((type->IsValuelessType()) || (type->IsMethodRef()))
  13197. if (type->IsValuelessType())
  13198. return mBfIRBuilder->GetFakeVal();
  13199. auto allocaInst = CreateAlloca(type, doLifetimeEnd, name.c_str());
  13200. if ((!doLifetimeEnd) && (WantsLifetimes()))
  13201. {
  13202. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  13203. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  13204. }
  13205. bool initLocalVariables = mCompiler->mOptions.mInitLocalVariables;
  13206. auto typeOptions = GetTypeOptions();
  13207. if (typeOptions != NULL)
  13208. initLocalVariables = typeOptions->Apply(initLocalVariables, BfOptionFlags_InitLocalVariables);
  13209. // Local variable inits are implicitly handled in the Beef Backend
  13210. if ((initLocalVariables) && (!IsTargetingBeefBackend()))
  13211. {
  13212. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  13213. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  13214. auto storeInst = mBfIRBuilder->CreateAlignedStore(GetDefaultValue(type), allocaInst, type->mAlign);
  13215. mBfIRBuilder->ClearDebugLocation(storeInst);
  13216. mBfIRBuilder->SetInsertPoint(prevBlock);
  13217. }
  13218. return allocaInst;
  13219. }
  13220. void BfModule::DoAddLocalVariable(BfLocalVariable* localVar)
  13221. {
  13222. while (localVar->mName.StartsWith('@'))
  13223. {
  13224. localVar->mNamePrefixCount++;
  13225. localVar->mName.Remove(0);
  13226. }
  13227. if (mCurMethodState->mLocals.mAllocSize == 0)
  13228. {
  13229. mCurMethodState->mLocals.Reserve(16);
  13230. mCurMethodState->mLocalVarSet.Reserve(16);
  13231. }
  13232. localVar->mLocalVarIdx = (int)mCurMethodState->mLocals.size();
  13233. mCurMethodState->mLocals.push_back(localVar);
  13234. BfLocalVarEntry* localVarEntryPtr;
  13235. if (!mCurMethodState->mLocalVarSet.TryAdd(BfLocalVarEntry(localVar), &localVarEntryPtr))
  13236. {
  13237. localVar->mShadowedLocal = localVarEntryPtr->mLocalVar;
  13238. localVarEntryPtr->mLocalVar = localVar;
  13239. }
  13240. }
  13241. void BfModule::DoLocalVariableDebugInfo(BfLocalVariable* localVarDef, bool doAliasValue, BfIRValue declareBefore, BfIRInitType initType)
  13242. {
  13243. if (localVarDef->mResolvedType->IsVar())
  13244. return;
  13245. if ((mBfIRBuilder->DbgHasInfo()) &&
  13246. ((mCurMethodInstance == NULL) || (!mCurMethodInstance->mIsUnspecialized)) &&
  13247. (mHasFullDebugInfo) &&
  13248. ((mCurMethodState->mClosureState == NULL) || (!mCurMethodState->mClosureState->mCapturing)))
  13249. {
  13250. auto varType = localVarDef->mResolvedType;
  13251. if (localVarDef->mResolvedType->IsValuelessType())
  13252. {
  13253. }
  13254. else
  13255. {
  13256. bool isByAddr = false;
  13257. auto diValue = localVarDef->mValue;
  13258. if (localVarDef->mConstValue)
  13259. diValue = localVarDef->mConstValue;
  13260. else if (localVarDef->mAddr)
  13261. {
  13262. diValue = localVarDef->mAddr;
  13263. isByAddr = true;
  13264. }
  13265. if (diValue.IsConst())
  13266. {
  13267. auto constant = mBfIRBuilder->GetConstant(diValue);
  13268. if ((constant->mConstType == BfConstType_TypeOf) || (constant->mConstType == BfConstType_TypeOf_WithData))
  13269. {
  13270. // Ignore for now
  13271. return;
  13272. }
  13273. }
  13274. auto diType = mBfIRBuilder->DbgGetType(localVarDef->mResolvedType);
  13275. bool didConstToMem = false;
  13276. bool isConstant = false;
  13277. if ((localVarDef->mIsReadOnly) && (localVarDef->mAddr))
  13278. diType = mBfIRBuilder->DbgCreateConstType(diType);
  13279. else if (localVarDef->mConstValue)
  13280. {
  13281. auto constant = mBfIRBuilder->GetConstant(localVarDef->mConstValue);
  13282. isConstant =
  13283. (constant->mConstType < BfConstType_GlobalVar) ||
  13284. (constant->mConstType == BfConstType_AggZero) ||
  13285. (constant->mConstType == BfConstType_Agg);
  13286. if (isConstant)
  13287. {
  13288. if (localVarDef->mResolvedType->IsComposite())
  13289. {
  13290. mBfIRBuilder->PopulateType(localVarDef->mResolvedType);
  13291. auto constMem = mBfIRBuilder->ConstToMemory(localVarDef->mConstValue);
  13292. // if (IsTargetingBeefBackend())
  13293. // {
  13294. // diValue = mBfIRBuilder->CreateAliasValue(constMem);
  13295. // didConstToMem = true;
  13296. //
  13297. // diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  13298. // }
  13299. //else
  13300. {
  13301. isByAddr = true;
  13302. mBfIRBuilder->SaveDebugLocation();
  13303. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  13304. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  13305. mBfIRBuilder->ClearDebugLocation();
  13306. auto ptrType = CreatePointerType(localVarDef->mResolvedType);
  13307. auto addrVal = CreateAlloca(ptrType);
  13308. mBfIRBuilder->CreateStore(constMem, addrVal);
  13309. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  13310. diValue = addrVal;
  13311. didConstToMem = true;
  13312. mBfIRBuilder->SetInsertPoint(prevBlock);
  13313. mBfIRBuilder->RestoreDebugLocation();
  13314. }
  13315. }
  13316. if (mCompiler->mOptions.IsCodeView())
  13317. diType = mBfIRBuilder->DbgCreateConstType(diType);
  13318. }
  13319. }
  13320. if (!mBfIRBuilder->mIgnoreWrites)
  13321. {
  13322. if ((localVarDef->mIsStatic) && (localVarDef->mAddr) && (!localVarDef->mResolvedType->IsValuelessType()))
  13323. {
  13324. auto refType = CreateRefType(localVarDef->mResolvedType);
  13325. diType = mBfIRBuilder->DbgGetType(refType);
  13326. auto refAlloca = CreateAlloca(refType);
  13327. mBfIRBuilder->CreateStore(localVarDef->mAddr, refAlloca);
  13328. diValue = refAlloca;
  13329. }
  13330. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  13331. localVarDef->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, initType);
  13332. localVarDef->mDbgVarInst = diVariable;
  13333. if (mBfIRBuilder->HasDebugLocation())
  13334. {
  13335. if ((isConstant) && (!didConstToMem))
  13336. {
  13337. BfTypedValue result(localVarDef->mConstValue, localVarDef->mResolvedType);
  13338. FixValueActualization(result);
  13339. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(result.mValue, diVariable);
  13340. }
  13341. else
  13342. {
  13343. if ((IsTargetingBeefBackend()) && (doAliasValue) && (!mIsComptimeModule))
  13344. {
  13345. diValue = mBfIRBuilder->CreateAliasValue(diValue);
  13346. mCurMethodState->mCurScope->mDeferredLifetimeEnds.Add(diValue);
  13347. }
  13348. if (isByAddr)
  13349. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertDeclare(diValue, diVariable, declareBefore);
  13350. else if (diValue)
  13351. {
  13352. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(diValue, diVariable);
  13353. }
  13354. else if (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU) // DWARF chokes on this:
  13355. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  13356. }
  13357. }
  13358. }
  13359. }
  13360. }
  13361. }
  13362. BfLocalVariable* BfModule::AddLocalVariableDef(BfLocalVariable* localVarDef, bool addDebugInfo, bool doAliasValue, BfIRValue declareBefore, BfIRInitType initType)
  13363. {
  13364. if ((localVarDef->mValue) && (!localVarDef->mAddr) && (IsTargetingBeefBackend()) && (!localVarDef->mResolvedType->IsValuelessType()))
  13365. {
  13366. if ((!localVarDef->mValue.IsConst()) &&
  13367. (!localVarDef->mValue.IsArg()) && (!localVarDef->mValue.IsFake()))
  13368. {
  13369. mBfIRBuilder->CreateValueScopeRetain(localVarDef->mValue);
  13370. mCurMethodState->mCurScope->mHadScopeValueRetain = true;
  13371. }
  13372. }
  13373. if (addDebugInfo)
  13374. DoLocalVariableDebugInfo(localVarDef, doAliasValue, declareBefore, initType);
  13375. localVarDef->mDeclBlock = mBfIRBuilder->GetInsertBlock();
  13376. DoAddLocalVariable(localVarDef);
  13377. auto rootMethodState = mCurMethodState->GetRootMethodState();
  13378. if (localVarDef->mLocalVarId == -1)
  13379. {
  13380. BF_ASSERT(rootMethodState->mCurLocalVarId >= 0);
  13381. localVarDef->mLocalVarId = rootMethodState->mCurLocalVarId++;
  13382. }
  13383. bool checkLocal = true;
  13384. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Ctor))
  13385. {
  13386. if (auto autoCtorDecl = BfNodeDynCast<BfAutoConstructorDeclaration>(mCurMethodInstance->mMethodDef->mMethodDeclaration))
  13387. checkLocal = false;
  13388. }
  13389. if ((localVarDef->mNameNode != NULL) && (mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL) && (!mIsComptimeModule) && (checkLocal))
  13390. mCompiler->mResolvePassData->mAutoComplete->CheckLocalDef(localVarDef->mNameNode, localVarDef);
  13391. if (((localVarDef->mNameNode != NULL) && (mCurMethodInstance != NULL)) && (checkLocal))
  13392. {
  13393. bool isClosureProcessing = (mCurMethodState->mClosureState != NULL) && (!mCurMethodState->mClosureState->mCapturing);
  13394. if ((!isClosureProcessing) && (mCompiler->mResolvePassData != NULL) && (localVarDef->mNameNode != NULL) && (rootMethodState->mMethodInstance != NULL) && (!mIsComptimeModule))
  13395. mCompiler->mResolvePassData->HandleLocalReference(localVarDef->mNameNode, rootMethodState->mMethodInstance->GetOwner()->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, localVarDef->mLocalVarId);
  13396. }
  13397. return localVarDef;
  13398. }
  13399. void BfModule::CreateDIRetVal()
  13400. {
  13401. if (!WantsDebugInfo())
  13402. return;
  13403. /*if (!mCurMethodState->mRetVal)
  13404. {
  13405. if (mCurMethodInstance->mMethodDef->mName != "Ziggle")
  13406. return;
  13407. }*/
  13408. if ((mCurMethodState->mRetVal) || (mCurMethodState->mRetValAddr))
  13409. {
  13410. BfType* dbgType = mCurMethodInstance->mReturnType;
  13411. BfIRValue dbgValue = mCurMethodState->mRetVal.mValue;
  13412. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1))
  13413. {
  13414. BF_ASSERT(mCurMethodState->mRetValAddr);
  13415. dbgType = CreatePointerType(dbgType);
  13416. dbgValue = mCurMethodState->mRetValAddr;
  13417. }
  13418. else
  13419. {
  13420. BF_ASSERT(!mCurMethodState->mRetValAddr);
  13421. }
  13422. mCurMethodState->mDIRetVal = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  13423. "@return", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(dbgType));
  13424. auto declareCall = mBfIRBuilder->DbgInsertDeclare(dbgValue, mCurMethodState->mDIRetVal);
  13425. }
  13426. }
  13427. BfTypedValue BfModule::CreateTuple(const Array<BfTypedValue>& values, const Array<String>& fieldNames)
  13428. {
  13429. BfTypeVector fieldTypes;
  13430. for (auto arg : values)
  13431. fieldTypes.Add(arg.mType);
  13432. auto tupleType = CreateTupleType(fieldTypes, fieldNames);
  13433. auto tupleTypedValue = BfTypedValue(CreateAlloca(tupleType), tupleType, true);
  13434. for (int fieldIdx = 0; fieldIdx < tupleType->mFieldInstances.size(); fieldIdx++)
  13435. {
  13436. auto& fieldInstance = tupleType->mFieldInstances[fieldIdx];
  13437. if (fieldInstance.mDataIdx <= 0)
  13438. continue;
  13439. auto typedVal = values[fieldIdx];
  13440. typedVal = LoadOrAggregateValue(typedVal);
  13441. mBfIRBuilder->CreateAlignedStore(typedVal.mValue, mBfIRBuilder->CreateInBoundsGEP(tupleTypedValue.mValue, 0, fieldInstance.mDataIdx), typedVal.mType->mAlign);
  13442. }
  13443. return tupleTypedValue;
  13444. }
  13445. void BfModule::CheckVariableDef(BfLocalVariable* variableDef)
  13446. {
  13447. if (variableDef->mName.IsEmpty())
  13448. return;
  13449. BfLocalVarEntry* localVarEntryPtr = NULL;
  13450. if ((mCurMethodState != NULL) && (mCurMethodState->mLocalVarSet.TryGet(BfLocalVarEntry(variableDef), &localVarEntryPtr)))
  13451. {
  13452. auto checkLocal = localVarEntryPtr->mLocalVar;
  13453. if ((checkLocal->mLocalVarIdx >= mCurMethodState->GetLocalStartIdx()) && (!checkLocal->mIsShadow))
  13454. {
  13455. BfError* error;
  13456. if (checkLocal->mIsImplicitParam)
  13457. return; // Ignore 'redefinition'
  13458. if (checkLocal->IsParam())
  13459. {
  13460. if (variableDef->IsParam())
  13461. error = Fail(StrFormat("A parameter named '%s' has already been declared", variableDef->mName.c_str()), variableDef->mNameNode);
  13462. else
  13463. 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);
  13464. }
  13465. else if (checkLocal->mLocalVarIdx < mCurMethodState->mCurScope->mLocalVarStart)
  13466. error = Fail(StrFormat("A variable named '%s' has already been declared in this parent's scope", variableDef->mName.c_str()), variableDef->mNameNode);
  13467. else
  13468. error = Fail(StrFormat("A variable named '%s' has already been declared in this scope", variableDef->mName.c_str()), variableDef->mNameNode);
  13469. if ((checkLocal->mNameNode != NULL) && (error != NULL))
  13470. mCompiler->mPassInstance->MoreInfo("Previous declaration", checkLocal->mNameNode);
  13471. return;
  13472. }
  13473. }
  13474. }
  13475. BfScopeData* BfModule::FindScope(BfAstNode* scopeName, BfMixinState* fromMixinState, bool allowAcrossDeferredBlock)
  13476. {
  13477. bool inMixinDecl = (mCurMethodInstance != NULL) && (mCurMethodInstance->IsMixin());
  13478. if (auto tokenNode = BfNodeDynCast<BfTokenNode>(scopeName))
  13479. {
  13480. if (tokenNode->GetToken() == BfToken_Colon)
  13481. {
  13482. if ((!allowAcrossDeferredBlock) && (mCurMethodState->mInDeferredBlock))
  13483. {
  13484. Fail("Cannot access method scope across deferred block boundary", scopeName);
  13485. return NULL;
  13486. }
  13487. return &mCurMethodState->mHeadScope;
  13488. }
  13489. else if (tokenNode->GetToken() == BfToken_Mixin)
  13490. {
  13491. if (fromMixinState == NULL)
  13492. {
  13493. if (mCurMethodInstance->mMethodDef->mMethodType != BfMethodType_Mixin)
  13494. Fail("'mixin' scope specifier can only be used within a mixin declaration", scopeName);
  13495. return mCurMethodState->mCurScope;
  13496. }
  13497. fromMixinState->mUsedInvocationScope = true;
  13498. return fromMixinState->mTargetScope;
  13499. }
  13500. else if (tokenNode->GetToken() == BfToken_New)
  13501. return NULL;
  13502. }
  13503. if (auto identifier = BfNodeDynCast<BfIdentifierNode>(scopeName))
  13504. {
  13505. auto findLabel = scopeName->ToString();
  13506. bool crossedDeferredBlock = false;
  13507. auto checkScope = mCurMethodState->mCurScope;
  13508. while (checkScope != NULL)
  13509. {
  13510. if (checkScope->mIsDeferredBlock)
  13511. crossedDeferredBlock = true;
  13512. if (checkScope->mLabel == findLabel)
  13513. {
  13514. if ((crossedDeferredBlock) && (!allowAcrossDeferredBlock))
  13515. {
  13516. Fail(StrFormat("Cannot access scope '%s' across deferred block boundary", findLabel.c_str()), scopeName);
  13517. return NULL;
  13518. }
  13519. return checkScope;
  13520. }
  13521. checkScope = checkScope->mPrevScope;
  13522. }
  13523. if (!inMixinDecl)
  13524. Fail(StrFormat("Unable to locate label '%s'", findLabel.c_str()), scopeName);
  13525. }
  13526. if (auto scopeNode = BfNodeDynCast<BfScopeNode>(scopeName))
  13527. {
  13528. return FindScope(scopeNode->mTargetNode, allowAcrossDeferredBlock);
  13529. }
  13530. return mCurMethodState->mCurScope;
  13531. }
  13532. BfScopeData* BfModule::FindScope(BfAstNode* scopeName, bool allowAcrossDeferredBlock)
  13533. {
  13534. return FindScope(scopeName, mCurMethodState->mMixinState, allowAcrossDeferredBlock);
  13535. }
  13536. BfBreakData* BfModule::FindBreakData(BfAstNode* scopeName)
  13537. {
  13538. auto scopeData = FindScope(scopeName, false);
  13539. if (scopeData == NULL)
  13540. return NULL;
  13541. int scopeDepth = scopeData->GetDepth();
  13542. // Find the first break data that is at or below the depth of our requested scope
  13543. auto breakData = mCurMethodState->mBreakData;
  13544. while ((breakData != NULL) && (scopeDepth < breakData->mScope->GetDepth()))
  13545. {
  13546. if (breakData->mScope->mIsConditional)
  13547. return NULL;
  13548. breakData = breakData->mPrevBreakData;
  13549. }
  13550. return breakData;
  13551. }
  13552. void BfModule::EmitLifetimeEnds(BfScopeData* scopeData)
  13553. {
  13554. // LLVM is stricter about the placement of these (ie: they can't occur after a 'ret')
  13555. if (!IsTargetingBeefBackend())
  13556. return;
  13557. for (auto lifetimeEnd : scopeData->mDeferredLifetimeEnds)
  13558. {
  13559. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  13560. }
  13561. }
  13562. void BfModule::ClearLifetimeEnds()
  13563. {
  13564. auto scopeData = mCurMethodState->mCurScope;
  13565. while (scopeData != NULL)
  13566. {
  13567. scopeData->mDeferredLifetimeEnds.Clear();
  13568. scopeData = scopeData->mPrevScope;
  13569. }
  13570. }
  13571. bool BfModule::WantsDebugInfo()
  13572. {
  13573. if ((mCurMethodInstance != NULL) &&
  13574. ((mCurMethodInstance->mIsUnspecialized) || (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)))
  13575. return false;
  13576. return (mBfIRBuilder->DbgHasInfo()) && (mHasFullDebugInfo) &&
  13577. ((mCurMethodState == NULL) || (mCurMethodState->mClosureState == NULL) || (!mCurMethodState->mClosureState->mCapturing));
  13578. }
  13579. BfTypeOptions* BfModule::GetTypeOptions()
  13580. {
  13581. if ((mCurMethodState != NULL) && (mCurMethodState->mMethodTypeOptions != NULL))
  13582. return mCurMethodState->mMethodTypeOptions;
  13583. if (mCurMethodInstance == NULL)
  13584. return NULL;
  13585. return mSystem->GetTypeOptions(mCurTypeInstance->mTypeOptionsIdx);
  13586. }
  13587. BfReflectKind BfModule::GetUserReflectKind(BfTypeInstance* attrType)
  13588. {
  13589. BfReflectKind reflectKind = BfReflectKind_None;
  13590. if (attrType->mCustomAttributes != NULL)
  13591. {
  13592. for (auto& customAttr : attrType->mCustomAttributes->mAttributes)
  13593. {
  13594. if (customAttr.mType->mTypeDef->mName->ToString() == "AttributeUsageAttribute")
  13595. {
  13596. for (auto& prop : customAttr.mSetProperties)
  13597. {
  13598. auto propDef = prop.mPropertyRef.mTypeInstance->mTypeDef->mProperties[prop.mPropertyRef.mPropIdx];
  13599. if (propDef->mName == "ReflectUser")
  13600. {
  13601. if (prop.mParam.mValue.IsConst())
  13602. {
  13603. auto constant = attrType->mConstHolder->GetConstant(prop.mParam.mValue);
  13604. reflectKind = (BfReflectKind)(reflectKind | (BfReflectKind)constant->mInt32);
  13605. }
  13606. }
  13607. }
  13608. // Check for Flags arg
  13609. if (customAttr.mCtorArgs.size() < 2)
  13610. continue;
  13611. auto constant = attrType->mConstHolder->GetConstant(customAttr.mCtorArgs[1]);
  13612. if (constant == NULL)
  13613. continue;
  13614. if (constant->mTypeCode == BfTypeCode_Boolean)
  13615. continue;
  13616. if ((constant->mInt8 & BfCustomAttributeFlags_ReflectAttribute) != 0)
  13617. reflectKind = (BfReflectKind)(reflectKind | BfReflectKind_User);
  13618. }
  13619. }
  13620. }
  13621. return reflectKind;
  13622. }
  13623. BfReflectKind BfModule::GetReflectKind(BfReflectKind reflectKind, BfTypeInstance* typeInstance)
  13624. {
  13625. auto checkTypeInstance = typeInstance;
  13626. while (checkTypeInstance != NULL)
  13627. {
  13628. if (checkTypeInstance->mCustomAttributes != NULL)
  13629. {
  13630. auto checkReflectKind = BfReflectKind_None;
  13631. for (auto& customAttr : checkTypeInstance->mCustomAttributes->mAttributes)
  13632. {
  13633. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  13634. {
  13635. if (customAttr.mCtorArgs.size() > 0)
  13636. {
  13637. auto constant = checkTypeInstance->mConstHolder->GetConstant(customAttr.mCtorArgs[0]);
  13638. checkReflectKind = (BfReflectKind)((int)checkReflectKind | constant->mInt32);
  13639. }
  13640. else
  13641. {
  13642. checkReflectKind = BfReflectKind_All;
  13643. }
  13644. }
  13645. else
  13646. {
  13647. auto userReflectKind = GetUserReflectKind(customAttr.mType);
  13648. checkReflectKind = (BfReflectKind)(checkReflectKind | userReflectKind);
  13649. }
  13650. }
  13651. if ((checkTypeInstance == typeInstance) ||
  13652. ((checkReflectKind & BfReflectKind_ApplyToInnerTypes) != 0))
  13653. {
  13654. reflectKind = (BfReflectKind)(reflectKind | checkReflectKind);
  13655. }
  13656. }
  13657. for (auto ifaceEntry : typeInstance->mInterfaces)
  13658. {
  13659. if (ifaceEntry.mInterfaceType->mCustomAttributes != NULL)
  13660. {
  13661. auto iface = ifaceEntry.mInterfaceType;
  13662. auto customAttr = iface->mCustomAttributes->Get(mCompiler->mReflectAttributeTypeDef);
  13663. if (customAttr != NULL)
  13664. {
  13665. for (auto& prop : customAttr->mSetProperties)
  13666. {
  13667. auto propDef = prop.mPropertyRef.mTypeInstance->mTypeDef->mProperties[prop.mPropertyRef.mPropIdx];
  13668. if (propDef->mName == "ReflectImplementer")
  13669. {
  13670. if (prop.mParam.mValue.IsConst())
  13671. {
  13672. auto constant = iface->mConstHolder->GetConstant(prop.mParam.mValue);
  13673. reflectKind = (BfReflectKind)(reflectKind | (BfReflectKind)constant->mInt32);
  13674. }
  13675. }
  13676. }
  13677. }
  13678. }
  13679. }
  13680. checkTypeInstance = mContext->mUnreifiedModule->GetOuterType(checkTypeInstance);
  13681. }
  13682. return reflectKind;
  13683. }
  13684. bool BfModule::HasDeferredScopeCalls(BfScopeData* scope)
  13685. {
  13686. BfScopeData* checkScope = mCurMethodState->mCurScope;
  13687. while (checkScope != NULL)
  13688. {
  13689. if ((!checkScope->mDeferredCallEntries.IsEmpty()) || (!checkScope->mDeferredLifetimeEnds.empty()))
  13690. return true;
  13691. if (checkScope == scope)
  13692. break;
  13693. checkScope = checkScope->mPrevScope;
  13694. }
  13695. return false;
  13696. }
  13697. void BfModule::EmitDeferredScopeCalls(bool useSrcPositions, BfScopeData* scopeData, BfIRBlock doneBlock)
  13698. {
  13699. // Is there anything we need to do here?
  13700. if (mBfIRBuilder->mIgnoreWrites)
  13701. {
  13702. // Just visit deferred blocks
  13703. BfScopeData* checkScope = mCurMethodState->mCurScope;
  13704. while (checkScope != NULL)
  13705. {
  13706. BfDeferredCallEntry* deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  13707. while (deferredCallEntry != NULL)
  13708. {
  13709. if (deferredCallEntry->mDeferredBlock != NULL)
  13710. {
  13711. SetAndRestoreValue<BfMixinState*> prevMixinState(mCurMethodState->mMixinState, checkScope->mMixinState);
  13712. if (checkScope == &mCurMethodState->mHeadScope)
  13713. CreateRetValLocal();
  13714. SetAndRestoreValue<BfAstNode*> prevCustomAttribute(mCurMethodState->mEmitRefNode, deferredCallEntry->mEmitRefNode);
  13715. VisitEmbeddedStatement(deferredCallEntry->mDeferredBlock, NULL, BfEmbeddedStatementFlags_IsDeferredBlock);
  13716. }
  13717. deferredCallEntry = deferredCallEntry->mNext;
  13718. }
  13719. if (checkScope == scopeData)
  13720. break;
  13721. checkScope = checkScope->mPrevScope;
  13722. }
  13723. return;
  13724. }
  13725. // Why did we want to do SetIllegalSrcPos here?
  13726. // Don't we always want to step onto these instances?
  13727. // Find a case where we don't and perhaps only do it there.
  13728. // The downside was that 'EmitEnsureInstructionAt' on the end of block statements causes
  13729. // a (seemingly) unneeded NOP when we do SetIllegalSrcPos
  13730. //SetIllegalSrcPos();
  13731. bool setSrcPos = false;
  13732. bool wantsNop = true;
  13733. BfAstNode* deferCloseNode = NULL;
  13734. if (mCurMethodState->mInPostReturn)
  13735. {
  13736. // These won't get used, they are post-return
  13737. return;
  13738. }
  13739. SizedArray<BfIRValue, 8> deferredLifetimeEnds;
  13740. BfScopeData* scopeJumpBlock = NULL;
  13741. bool hadExtraDeferredLifetimeEnds = false;
  13742. auto _FlushLifetimeEnds = [&]()
  13743. {
  13744. for (auto lifetimeEnd : deferredLifetimeEnds)
  13745. {
  13746. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  13747. mBfIRBuilder->ClearDebugLocation_Last();
  13748. }
  13749. deferredLifetimeEnds.clear();
  13750. };
  13751. BfScopeData* checkScope = mCurMethodState->mCurScope;
  13752. while (checkScope != NULL)
  13753. {
  13754. if (checkScope->mCloseNode != NULL)
  13755. deferCloseNode = checkScope->mCloseNode;
  13756. if (doneBlock)
  13757. {
  13758. // Try to find a match where we've already emitted these calls and then jumped to the correct block
  13759. for (auto& checkHandler : checkScope->mDeferredHandlers)
  13760. {
  13761. if (checkHandler.mDoneBlock == doneBlock)
  13762. {
  13763. scopeJumpBlock = checkScope;
  13764. mBfIRBuilder->CreateBr(checkHandler.mHandlerBlock);
  13765. mBfIRBuilder->ClearDebugLocation_Last();
  13766. _FlushLifetimeEnds();
  13767. break;
  13768. }
  13769. }
  13770. if (scopeJumpBlock != NULL)
  13771. break;
  13772. }
  13773. bool hasWork = (checkScope->mSavedStack) || (checkScope->mDeferredCallEntries.mHead != NULL);
  13774. if (checkScope != scopeData) // Only emit a block for deferred lifetimes if we're going back beyond this entry
  13775. hasWork |= (!deferredLifetimeEnds.IsEmpty());
  13776. if (hasWork)
  13777. {
  13778. SetAndRestoreValue<BfScopeData*> prevScope(mCurMethodState->mCurScope, checkScope);
  13779. if (deferCloseNode != NULL)
  13780. {
  13781. UpdateSrcPos(deferCloseNode);
  13782. }
  13783. if (checkScope == &mCurMethodState->mHeadScope)
  13784. CreateRetValLocal();
  13785. if (doneBlock)
  13786. {
  13787. bool crossingMixin = mCurMethodState->mCurScope->mMixinDepth != checkScope->mMixinDepth;
  13788. String blockName = "deferredCalls";
  13789. //blockName += StrFormat("_%d", mBfIRBuilder->mBlockCount);
  13790. BfDeferredHandler deferredHandler;
  13791. if ((!crossingMixin) && (deferredLifetimeEnds.IsEmpty()))
  13792. {
  13793. mBfIRBuilder->SaveDebugLocation();
  13794. mBfIRBuilder->ClearDebugLocation();
  13795. deferredHandler.mHandlerBlock = mBfIRBuilder->MaybeChainNewBlock(blockName);
  13796. mBfIRBuilder->RestoreDebugLocation();
  13797. }
  13798. else
  13799. {
  13800. // Definitely chain
  13801. deferredHandler.mHandlerBlock = mBfIRBuilder->CreateBlock(blockName);
  13802. mBfIRBuilder->CreateBr(deferredHandler.mHandlerBlock);
  13803. mBfIRBuilder->ClearDebugLocation_Last();
  13804. _FlushLifetimeEnds();
  13805. mBfIRBuilder->AddBlock(deferredHandler.mHandlerBlock);
  13806. mBfIRBuilder->SetInsertPoint(deferredHandler.mHandlerBlock);
  13807. }
  13808. deferredHandler.mDoneBlock = doneBlock;
  13809. if (!mBfIRBuilder->mIgnoreWrites)
  13810. checkScope->mDeferredHandlers.push_back(deferredHandler);
  13811. if (checkScope == &mCurMethodState->mHeadScope)
  13812. {
  13813. if (!mCurMethodState->mDIRetVal)
  13814. {
  13815. // 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
  13816. // be scoped to the physical method
  13817. /*if (deferCloseNode != NULL)
  13818. {
  13819. UpdateSrcPos(deferCloseNode);
  13820. }*/
  13821. CreateDIRetVal();
  13822. }
  13823. }
  13824. if (checkScope != mCurMethodState->mTailScope)
  13825. {
  13826. if (deferredHandler.mHandlerBlock.IsFake())
  13827. {
  13828. BF_ASSERT(mBfIRBuilder->mIgnoreWrites);
  13829. }
  13830. if (!mBfIRBuilder->mIgnoreWrites)
  13831. checkScope->mAtEndBlocks.push_back(deferredHandler.mHandlerBlock);
  13832. }
  13833. }
  13834. HashSet<BfDeferredCallEntry*> handledSet;
  13835. BfDeferredCallEntry* deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  13836. while (deferredCallEntry != NULL)
  13837. {
  13838. BfDeferredCallEmitState deferredCallEmitState;
  13839. deferredCallEmitState.mCloseNode = deferCloseNode;
  13840. SetAndRestoreValue<BfDeferredCallEmitState*> prevDeferredCallEmitState(mCurMethodState->mDeferredCallEmitState, &deferredCallEmitState);
  13841. SetAndRestoreValue<bool> prevIgnoredWrites(mBfIRBuilder->mIgnoreWrites, deferredCallEntry->mIgnored);
  13842. SetAndRestoreValue<BfMixinState*> prevMixinState(mCurMethodState->mMixinState, checkScope->mMixinState);
  13843. if (deferCloseNode != NULL)
  13844. {
  13845. UpdateSrcPos(deferCloseNode);
  13846. }
  13847. if (wantsNop)
  13848. EmitEnsureInstructionAt();
  13849. wantsNop = false;
  13850. if (deferredCallEntry->mDeferredBlock != NULL)
  13851. {
  13852. BfDeferredCallEntry** entryPtr = NULL;
  13853. if (!handledSet.TryAdd(deferredCallEntry, &entryPtr))
  13854. {
  13855. // Already handled, can happen if we defer again within the block
  13856. deferredCallEntry = deferredCallEntry->mNext;
  13857. continue;
  13858. }
  13859. auto prevHead = checkScope->mDeferredCallEntries.mHead;
  13860. EmitDeferredCall(*deferredCallEntry, true);
  13861. if (prevHead != checkScope->mDeferredCallEntries.mHead)
  13862. {
  13863. // The list changed, start over and ignore anything we've already handled
  13864. deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  13865. }
  13866. else
  13867. deferredCallEntry = deferredCallEntry->mNext;
  13868. }
  13869. else
  13870. {
  13871. EmitDeferredCall(*deferredCallEntry, true);
  13872. deferredCallEntry = deferredCallEntry->mNext;
  13873. }
  13874. }
  13875. if (checkScope->mSavedStack)
  13876. {
  13877. checkScope->mSavedStackUses.Add(mBfIRBuilder->CreateStackRestore(checkScope->mSavedStack));
  13878. if (mCurMethodState->mDynStackRevIdx)
  13879. {
  13880. auto curValue = mBfIRBuilder->CreateLoad(mCurMethodState->mDynStackRevIdx);
  13881. auto newValue = mBfIRBuilder->CreateAdd(curValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  13882. mBfIRBuilder->CreateStore(newValue, mCurMethodState->mDynStackRevIdx);
  13883. }
  13884. }
  13885. }
  13886. if (!checkScope->mIsScopeHead)
  13887. {
  13888. // We manually emit function-level lifetime ends after the 'ret' in ProcessMethod
  13889. if (!IsTargetingBeefBackend())
  13890. {
  13891. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  13892. {
  13893. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  13894. }
  13895. }
  13896. else
  13897. {
  13898. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  13899. {
  13900. deferredLifetimeEnds.Add(lifetimeEnd);
  13901. }
  13902. }
  13903. }
  13904. if (checkScope == scopeData)
  13905. break;
  13906. checkScope = checkScope->mPrevScope;
  13907. }
  13908. if ((doneBlock) && (scopeJumpBlock == NULL))
  13909. {
  13910. mBfIRBuilder->CreateBr(doneBlock);
  13911. mBfIRBuilder->ClearDebugLocation_Last();
  13912. }
  13913. // Keeping CreateLifetimeEnds until the end messes up when we chain to old mDeferredHandlers that
  13914. // may have been created when other scope lifetimes were available
  13915. _FlushLifetimeEnds();
  13916. // Emit lifetimeEnds after the branch for Beef
  13917. /*if (IsTargetingBeefBackend())
  13918. {
  13919. bool needsEnsureInst = (!doneBlock) && (scopeJumpBlock == NULL);
  13920. BfScopeData* checkScope = mCurMethodState->mCurScope;
  13921. while (checkScope != NULL)
  13922. {
  13923. if (checkScope == scopeJumpBlock)
  13924. break;
  13925. if (!checkScope->mIsScopeHead)
  13926. {
  13927. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  13928. {
  13929. if (needsEnsureInst)
  13930. {
  13931. needsEnsureInst = false;
  13932. }
  13933. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  13934. }
  13935. }
  13936. if (checkScope == scopeData)
  13937. break;
  13938. checkScope = checkScope->mPrevScope;
  13939. }
  13940. }*/
  13941. }
  13942. void BfModule::MarkScopeLeft(BfScopeData* scopeData, bool isNoReturn)
  13943. {
  13944. if ((mCurMethodState->mDeferredLocalAssignData != NULL) && (!isNoReturn))
  13945. {
  13946. auto deferredLocalAssignData = mCurMethodState->mDeferredLocalAssignData;
  13947. while (deferredLocalAssignData != NULL)
  13948. {
  13949. if ((deferredLocalAssignData->mScopeData == NULL) || (deferredLocalAssignData->mScopeData->mScopeDepth < scopeData->mScopeDepth))
  13950. break;
  13951. if ((deferredLocalAssignData->mScopeData != NULL) && (deferredLocalAssignData->mScopeData->mScopeDepth == scopeData->mScopeDepth))
  13952. deferredLocalAssignData->mIsUnconditional = false;
  13953. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  13954. }
  13955. }
  13956. // When we leave a scope, mark those as assigned for deferred assignment purposes
  13957. for (int localIdx = scopeData->mLocalVarStart; localIdx < (int)mCurMethodState->mLocals.size(); localIdx++)
  13958. {
  13959. auto localDef = mCurMethodState->mLocals[localIdx];
  13960. if (localDef->mAssignedKind == BfLocalVarAssignKind_None)
  13961. {
  13962. bool hadAssignment = false;
  13963. if (mCurMethodState->mDeferredLocalAssignData != NULL)
  13964. {
  13965. for (auto& entry : mCurMethodState->mDeferredLocalAssignData->mAssignedLocals)
  13966. if (entry.mLocalVar == localDef)
  13967. hadAssignment = true;
  13968. }
  13969. if (!hadAssignment)
  13970. {
  13971. if (!isNoReturn)
  13972. localDef->mHadExitBeforeAssign = true;
  13973. mCurMethodState->LocalDefined(localDef);
  13974. }
  13975. }
  13976. }
  13977. }
  13978. void BfModule::CreateReturn(BfIRValue val)
  13979. {
  13980. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1))
  13981. {
  13982. // Store to sret
  13983. BF_ASSERT(val);
  13984. mBfIRBuilder->CreateStore(val, mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()));
  13985. mBfIRBuilder->CreateRetVoid();
  13986. return;
  13987. }
  13988. if (mCurMethodInstance->mReturnType->IsVar())
  13989. return;
  13990. if (mCurMethodInstance->mReturnType->IsValuelessType())
  13991. {
  13992. mBfIRBuilder->CreateRetVoid();
  13993. return;
  13994. }
  13995. if (mCurMethodInstance->mReturnType->IsStruct())
  13996. {
  13997. BfTypeCode loweredReturnType = BfTypeCode_None;
  13998. BfTypeCode loweredReturnType2 = BfTypeCode_None;
  13999. if (!mIsComptimeModule)
  14000. mCurMethodInstance->GetLoweredReturnType(&loweredReturnType, &loweredReturnType2);
  14001. if (loweredReturnType != BfTypeCode_None)
  14002. {
  14003. auto retVal = CreateAlloca(mCurMethodInstance->mReturnType);
  14004. mBfIRBuilder->CreateStore(val, retVal);
  14005. auto irRetType = GetIRLoweredType(loweredReturnType, loweredReturnType2);
  14006. irRetType = mBfIRBuilder->GetPointerTo(irRetType);
  14007. auto ptrReturnValue = mBfIRBuilder->CreateBitCast(retVal, irRetType);
  14008. auto loadedReturnValue = mBfIRBuilder->CreateLoad(ptrReturnValue);
  14009. mBfIRBuilder->CreateRet(loadedReturnValue);
  14010. return;
  14011. }
  14012. }
  14013. BF_ASSERT(val);
  14014. mBfIRBuilder->CreateRet(val);
  14015. }
  14016. void BfModule::EmitReturn(const BfTypedValue& val)
  14017. {
  14018. if (mCurMethodState->mIRExitBlock)
  14019. {
  14020. if (!mCurMethodInstance->mReturnType->IsValuelessType())
  14021. {
  14022. if (val) // We allow for val to be empty if we know we've already written the value to mRetVal
  14023. {
  14024. if ((mCurMethodState->mRetValAddr) || (mCurMethodState->mRetVal))
  14025. {
  14026. BfIRValue retVal = mCurMethodState->mRetVal.mValue;
  14027. if (!mCurMethodState->mRetVal)
  14028. retVal = mBfIRBuilder->CreateAlignedLoad(mCurMethodState->mRetValAddr, mCurMethodInstance->mReturnType->mAlign);
  14029. mBfIRBuilder->CreateAlignedStore(val.mValue, retVal, mCurMethodInstance->mReturnType->mAlign);
  14030. }
  14031. else if (mIsComptimeModule)
  14032. {
  14033. if (!val.mType->IsValuelessType())
  14034. mBfIRBuilder->CreateSetRet(val.mValue, val.mType->mTypeId);
  14035. else
  14036. mBfIRBuilder->CreateSetRet(BfIRValue(), val.mType->mTypeId);
  14037. }
  14038. else
  14039. {
  14040. // Just ignore
  14041. BF_ASSERT(mCurMethodInstance->mReturnType->IsVar());
  14042. }
  14043. }
  14044. }
  14045. EmitDeferredScopeCalls(true, NULL, mCurMethodState->mIRExitBlock);
  14046. }
  14047. else
  14048. {
  14049. EmitDeferredScopeCalls(false, NULL);
  14050. if (val)
  14051. {
  14052. BF_ASSERT(mBfIRBuilder->mIgnoreWrites);
  14053. }
  14054. }
  14055. mCurMethodState->SetHadReturn(true);
  14056. mCurMethodState->mLeftBlockUncond = true;
  14057. }
  14058. void BfModule::EmitDefaultReturn()
  14059. {
  14060. if (mCurMethodState->mInDeferredBlock)
  14061. return;
  14062. if (mCurMethodState->mIRExitBlock)
  14063. {
  14064. EmitDeferredScopeCalls(true, NULL, mCurMethodState->mIRExitBlock);
  14065. }
  14066. else
  14067. {
  14068. if ((mCurMethodInstance == NULL) || (mCurMethodInstance->mReturnType->IsVar()))
  14069. {
  14070. // Ignore
  14071. }
  14072. else if (mCurMethodInstance->mReturnType->IsVoid())
  14073. mBfIRBuilder->CreateRetVoid();
  14074. else if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() == -1))
  14075. mBfIRBuilder->CreateRet(GetDefaultValue(mCurMethodInstance->mReturnType));
  14076. }
  14077. mCurMethodState->SetHadReturn(true);
  14078. mCurMethodState->mLeftBlockUncond = true;
  14079. }
  14080. void BfModule::AssertErrorState()
  14081. {
  14082. if (mIgnoreErrors)
  14083. return;
  14084. if (mHadBuildError)
  14085. return;
  14086. if (mCurTypeInstance != NULL)
  14087. {
  14088. if (mCurTypeInstance->IsUnspecializedTypeVariation())
  14089. return;
  14090. }
  14091. if (mCurMethodInstance != NULL)
  14092. {
  14093. if (mCurMethodInstance->IsOrInUnspecializedVariation())
  14094. return;
  14095. if (mCurMethodInstance->mHasFailed)
  14096. return;
  14097. }
  14098. // We want the module to be marked as failed even if it's just an error in the parser
  14099. if (mCurMethodInstance != NULL)
  14100. mCurMethodInstance->mHasFailed = true;
  14101. mHadBuildError = true;
  14102. // We check for either the parsing to have failed (possibly on a previous run), or for the current instance to have failed
  14103. if (mCurTypeInstance != NULL)
  14104. {
  14105. if (mCurTypeInstance->mTypeFailed)
  14106. return;
  14107. if ((mCurTypeInstance->mTypeDef->GetDefinition()->mSource != NULL) && (mCurTypeInstance->mTypeDef->GetDefinition()->mSource->mParsingFailed))
  14108. return;
  14109. }
  14110. if (mCurMethodInstance != NULL)
  14111. {
  14112. if ((mCurMethodInstance->mMethodDef->mDeclaringType != NULL) &&
  14113. (mCurMethodInstance->mMethodDef->mDeclaringType->mSource != NULL) &&
  14114. (mCurMethodInstance->mMethodDef->mDeclaringType->mSource->mParsingFailed))
  14115. return;
  14116. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL) &&
  14117. (mCurMethodState->mMixinState->mMixinMethodInstance->mMethodDef->mDeclaringType->mSource != NULL) &&
  14118. (mCurMethodState->mMixinState->mMixinMethodInstance->mMethodDef->mDeclaringType->mSource->mParsingFailed))
  14119. return;
  14120. }
  14121. if (mCompiler->IsAutocomplete())
  14122. return;
  14123. BF_ASSERT(mCompiler->mPassInstance->HasFailed());
  14124. }
  14125. void BfModule::AssertParseErrorState()
  14126. {
  14127. if (mCompiler->mRevision == 1)
  14128. AssertErrorState();
  14129. }
  14130. BfType* BfModule::GetDelegateReturnType(BfType* delegateType)
  14131. {
  14132. BF_ASSERT(delegateType->IsDelegate());
  14133. auto typeInst = delegateType->ToTypeInstance();
  14134. PopulateType(typeInst, BfPopulateType_DataAndMethods);
  14135. BfMethodInstance* invokeMethodInstance = GetRawMethodInstanceAtIdx(typeInst->ToTypeInstance(), 0, "Invoke");
  14136. if (invokeMethodInstance == NULL)
  14137. return GetPrimitiveType(BfTypeCode_Var);
  14138. return invokeMethodInstance->mReturnType;
  14139. }
  14140. BfMethodInstance* BfModule::GetDelegateInvokeMethod(BfTypeInstance* typeInstance)
  14141. {
  14142. return GetRawMethodInstanceAtIdx(typeInstance, 0, "Invoke");
  14143. }
  14144. void BfModule::CreateDelegateInvokeMethod()
  14145. {
  14146. // Clear out debug loc - otherwise we'll single step onto the delegate type declaration
  14147. //mBfIRBuilder->ClearDebugLocation();
  14148. SetIllegalSrcPos();
  14149. auto typeInstance = mCurTypeInstance;
  14150. auto memberFuncType = mBfIRBuilder->MapMethod(mCurMethodInstance);
  14151. SizedArray<BfIRType, 4> staticParamTypes;
  14152. SizedArray<BfIRValue, 4> staticFuncArgs;
  14153. SizedArray<BfIRValue, 4> memberFuncArgs;
  14154. auto multicastDelegateType = typeInstance->mBaseType;
  14155. if (multicastDelegateType->mFieldInstances.size() != 2)
  14156. {
  14157. AssertErrorState();
  14158. return;
  14159. }
  14160. auto multicastDelegate = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapType(multicastDelegateType));
  14161. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 2); // Load 'delegate.mTarget'
  14162. auto fieldVal = mBfIRBuilder->CreateAlignedLoad(fieldPtr, mSystem->mPtrSize);
  14163. BfExprEvaluator exprEvaluator(this);
  14164. SizedArray<BfIRType, 8> origParamTypes;
  14165. BfIRType origReturnType;
  14166. BfIRType staticReturnType;
  14167. mCurMethodInstance->GetIRFunctionInfo(this, origReturnType, origParamTypes);
  14168. if (mCurMethodInstance->mReturnType->IsValueType())
  14169. mBfIRBuilder->PopulateType(mCurMethodInstance->mReturnType, BfIRPopulateType_Full);
  14170. if ((mIsComptimeModule) || (mCurMethodInstance->GetStructRetIdx() != 0))
  14171. memberFuncArgs.push_back(BfIRValue()); // Push 'target'
  14172. int thisIdx = 0;
  14173. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1))
  14174. {
  14175. thisIdx = mCurMethodInstance->GetStructRetIdx() ^ 1;
  14176. memberFuncArgs.push_back(mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()));
  14177. }
  14178. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx(true) != -1))
  14179. staticFuncArgs.push_back(mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()));
  14180. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() == 0))
  14181. memberFuncArgs.push_back(BfIRValue()); // Push 'target'
  14182. mCurMethodInstance->GetIRFunctionInfo(this, staticReturnType, staticParamTypes, true);
  14183. for (int i = 1; i < (int)mCurMethodState->mLocals.size(); i++)
  14184. {
  14185. BfTypedValue localVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[i], true);
  14186. exprEvaluator.PushArg(localVal, staticFuncArgs);
  14187. exprEvaluator.PushArg(localVal, memberFuncArgs);
  14188. }
  14189. auto staticFunc = mBfIRBuilder->CreateFunctionType(staticReturnType, staticParamTypes, false);
  14190. auto staticFuncPtr = mBfIRBuilder->GetPointerTo(staticFunc);
  14191. auto staticFuncPtrPtr = mBfIRBuilder->GetPointerTo(staticFuncPtr);
  14192. auto trueBB = mBfIRBuilder->CreateBlock("if.then", true);
  14193. auto falseBB = mBfIRBuilder->CreateBlock("if.else");
  14194. auto doneBB = mBfIRBuilder->CreateBlock("done");
  14195. auto checkTargetNull = mBfIRBuilder->CreateIsNotNull(fieldVal);
  14196. mBfIRBuilder->CreateCondBr(checkTargetNull, trueBB, falseBB);
  14197. BfIRValue nonStaticResult;
  14198. BfIRValue staticResult;
  14199. auto callingConv = GetIRCallingConvention(mCurMethodInstance);
  14200. /// Non-static invocation
  14201. {
  14202. auto memberFuncPtr = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapMethod(mCurMethodInstance));
  14203. auto memberFuncPtrPtr = mBfIRBuilder->GetPointerTo(memberFuncPtr);
  14204. mBfIRBuilder->SetInsertPoint(trueBB);
  14205. memberFuncArgs[thisIdx] = mBfIRBuilder->CreateBitCast(fieldVal, mBfIRBuilder->MapType(mCurTypeInstance));
  14206. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 1); // Load 'delegate.mFuncPtr'
  14207. auto funcPtrPtr = mBfIRBuilder->CreateBitCast(fieldPtr, memberFuncPtrPtr);
  14208. auto funcPtr = mBfIRBuilder->CreateAlignedLoad(funcPtrPtr, mSystem->mPtrSize);
  14209. nonStaticResult = mBfIRBuilder->CreateCall(funcPtr, memberFuncArgs);
  14210. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1))
  14211. mBfIRBuilder->Call_AddAttribute(nonStaticResult, mCurMethodInstance->GetStructRetIdx() + 1, BfIRAttribute_StructRet);
  14212. if (callingConv != BfIRCallingConv_CDecl)
  14213. mBfIRBuilder->SetCallCallingConv(nonStaticResult, callingConv);
  14214. mCurMethodState->SetHadReturn(false);
  14215. mCurMethodState->mLeftBlockUncond = false;
  14216. mCurMethodState->mLeftBlockCond = false;
  14217. mBfIRBuilder->CreateBr(doneBB);
  14218. }
  14219. // Static invocation
  14220. {
  14221. mBfIRBuilder->AddBlock(falseBB);
  14222. mBfIRBuilder->SetInsertPoint(falseBB);
  14223. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 1); // Load 'delegate.mFuncPtr'
  14224. auto funcPtrPtr = mBfIRBuilder->CreateBitCast(fieldPtr, staticFuncPtrPtr);
  14225. auto funcPtr = mBfIRBuilder->CreateAlignedLoad(funcPtrPtr, mSystem->mPtrSize);
  14226. staticResult = mBfIRBuilder->CreateCall(funcPtr, staticFuncArgs);
  14227. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx(true) != -1))
  14228. {
  14229. // Note: since this is a forced static invocation, we know the sret will be the first parameter
  14230. mBfIRBuilder->Call_AddAttribute(staticResult, 0 + 1, BfIRAttribute_StructRet);
  14231. }
  14232. // We had a sret for the non-static but no sret for the static (because we have a lowered return type there)
  14233. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1) && (mCurMethodInstance->GetStructRetIdx(true) == -1))
  14234. {
  14235. auto sretToType = mBfIRBuilder->GetPointerTo(staticReturnType);
  14236. auto sretCastedPtr = mBfIRBuilder->CreateBitCast(mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()), sretToType);
  14237. mBfIRBuilder->CreateStore(staticResult, sretCastedPtr);
  14238. }
  14239. if (callingConv == BfIRCallingConv_ThisCall)
  14240. callingConv = BfIRCallingConv_CDecl;
  14241. if (callingConv != BfIRCallingConv_CDecl)
  14242. mBfIRBuilder->SetCallCallingConv(staticResult, callingConv);
  14243. mCurMethodState->SetHadReturn(false);
  14244. mCurMethodState->mLeftBlockUncond = false;
  14245. mCurMethodState->mLeftBlockCond = false;
  14246. mBfIRBuilder->CreateBr(doneBB);
  14247. }
  14248. mBfIRBuilder->AddBlock(doneBB);
  14249. mBfIRBuilder->SetInsertPoint(doneBB);
  14250. if (mCurMethodInstance->mReturnType->IsVar())
  14251. {
  14252. // Do nothing
  14253. }
  14254. else if ((mCurMethodInstance->mReturnType->IsValuelessType()) ||
  14255. ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1)))
  14256. {
  14257. mBfIRBuilder->CreateRetVoid();
  14258. }
  14259. else
  14260. {
  14261. BfIRType loweredIRReturnType;
  14262. BfTypeCode loweredTypeCode = BfTypeCode_None;
  14263. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  14264. if ((!mIsComptimeModule) && (mCurMethodInstance->GetLoweredReturnType(&loweredTypeCode, &loweredTypeCode2)))
  14265. loweredIRReturnType = GetIRLoweredType(loweredTypeCode, loweredTypeCode2);
  14266. else
  14267. loweredIRReturnType = mBfIRBuilder->MapType(mCurMethodInstance->mReturnType);
  14268. auto phi = mBfIRBuilder->CreatePhi(loweredIRReturnType, 2);
  14269. mBfIRBuilder->AddPhiIncoming(phi, nonStaticResult, trueBB);
  14270. mBfIRBuilder->AddPhiIncoming(phi, staticResult, falseBB);
  14271. mBfIRBuilder->CreateRet(phi);
  14272. }
  14273. }
  14274. // "Interested" here means every method for a normal compile, and just the method the cursor is on for autocompletion
  14275. bool BfModule::IsInterestedInMethod(BfTypeInstance* typeInstance, BfMethodDef* methodDef)
  14276. {
  14277. auto typeDef = typeInstance->mTypeDef;
  14278. auto methodDeclaration = methodDef->mMethodDeclaration;
  14279. if (!mCompiler->mIsResolveOnly)
  14280. return true;
  14281. if (typeInstance->IsGenericTypeInstance())
  14282. {
  14283. // We only really want to process the unspecialized type for autocompletion
  14284. if ((!typeInstance->IsUnspecializedType()) || (typeInstance->IsUnspecializedTypeVariation()))
  14285. return false;
  14286. }
  14287. BfAstNode* checkNode = methodDeclaration;
  14288. if (methodDeclaration == NULL)
  14289. checkNode = methodDef->mBody;
  14290. if ((!mCompiler->mResolvePassData->mParsers.IsEmpty()) && (typeDef->mTypeDeclaration->IsFromParser(mCompiler->mResolvePassData->mParsers[0])))
  14291. {
  14292. if (mCompiler->mResolvePassData->mAutoComplete == NULL)
  14293. return true;
  14294. }
  14295. return false;
  14296. }
  14297. void BfModule::CalcAppendAlign(BfMethodInstance* methodInst)
  14298. {
  14299. methodInst->mAppendAllocAlign = 1;
  14300. }
  14301. BfTypedValue BfModule::TryConstCalcAppend(BfMethodInstance* methodInst, SizedArrayImpl<BfIRValue>& args, bool force)
  14302. {
  14303. BP_ZONE("BfModule::TryConstCalcAppend");
  14304. BF_ASSERT(methodInst->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend);
  14305. if ((mCompiler->mIsResolveOnly) && (!mIsComptimeModule) && (!force))
  14306. return BfTypedValue();
  14307. // We want to regenerate all ctor calls when the method internals change
  14308. {
  14309. auto checkTypeInst = methodInst->GetOwner();
  14310. while (checkTypeInst->mTypeDef->mHasAppendCtor)
  14311. {
  14312. AddDependency(checkTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_InlinedCall);
  14313. checkTypeInst = GetBaseType(checkTypeInst);
  14314. }
  14315. }
  14316. if (!methodInst->mMayBeConst)
  14317. return BfTypedValue();
  14318. // Do we need to iterate in order to resolve mAppendAllocAlign?
  14319. bool isFirstRun = methodInst->mEndingAppendAllocAlign < 0;
  14320. bool wasAllConst = true;
  14321. int argIdx = 0;
  14322. int paramIdx = 0;
  14323. while (true)
  14324. {
  14325. if (argIdx >= (int)args.size())
  14326. break;
  14327. auto paramType = methodInst->GetParamType(paramIdx);
  14328. PopulateType(paramType);
  14329. int argCount = 0;
  14330. if (!paramType->IsValuelessType())
  14331. {
  14332. if ((!mIsComptimeModule) && (methodInst->GetParamIsSplat(paramIdx)))
  14333. argCount = paramType->GetSplatCount();
  14334. else
  14335. argCount = 1;
  14336. for (int argOfs = 0; argOfs < argCount; argOfs++)
  14337. {
  14338. auto arg = args[argIdx + argOfs];
  14339. if (!arg.IsConst())
  14340. {
  14341. wasAllConst = false;
  14342. if (!isFirstRun)
  14343. {
  14344. auto& param = methodInst->mParams[argIdx];
  14345. if (param.mReferencedInConstPass)
  14346. {
  14347. // If this param is required as part of the const calculation then
  14348. // we require that it be const...
  14349. return BfTypedValue();
  14350. }
  14351. }
  14352. }
  14353. }
  14354. }
  14355. paramIdx++;
  14356. argIdx += argCount;
  14357. }
  14358. auto methodDef = methodInst->mMethodDef;
  14359. auto methodDecl = methodDef->GetMethodDeclaration();
  14360. auto methodDeclBlock = BfNodeDynCast<BfBlock>(methodDecl->mBody);
  14361. if (methodDeclBlock == NULL)
  14362. return GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr)); // Must not have an append alloc at all!
  14363. BfTypedValue constValue;
  14364. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  14365. auto checkState = mCurMethodState->mConstResolveState;
  14366. while (checkState != NULL)
  14367. {
  14368. if (checkState->mMethodInstance == methodInst)
  14369. {
  14370. return BfTypedValue();
  14371. }
  14372. checkState = checkState->mPrevConstResolveState;
  14373. }
  14374. //auto accumValue = GetConstValue(0);
  14375. bool failed = false;
  14376. //
  14377. {
  14378. BfConstResolveState constResolveState;
  14379. constResolveState.mMethodInstance = methodInst;
  14380. constResolveState.mPrevConstResolveState = mCurMethodState->mConstResolveState;
  14381. constResolveState.mInCalcAppend = true;
  14382. SetAndRestoreValue<bool> ignoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  14383. BfMethodState methodState;
  14384. SetAndRestoreValue<BfTypeInstance*> prevTypeInst(mCurTypeInstance, methodInst->GetOwner());
  14385. SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, methodInst);
  14386. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  14387. methodState.mTempKind = BfMethodState::TempKind_NonStatic;
  14388. methodState.mConstResolveState = &constResolveState;
  14389. int argIdx = 0;
  14390. for (int paramIdx = 0; paramIdx < methodInst->GetParamCount(); paramIdx++)
  14391. {
  14392. if (methodInst->GetParamKind(paramIdx) == BfParamKind_AppendIdx)
  14393. continue;
  14394. auto paramType = methodInst->GetParamType(paramIdx);
  14395. // Fix this after we allow structs to be consts
  14396. //BF_ASSERT(!paramType->IsSplattable());
  14397. BfLocalVariable* localVar = new BfLocalVariable();
  14398. localVar->mName = methodInst->GetParamName(paramIdx);
  14399. localVar->mResolvedType = paramType;
  14400. localVar->mConstValue = args[argIdx];
  14401. localVar->mParamIdx = paramIdx;
  14402. AddLocalVariableDef(localVar);
  14403. argIdx++;
  14404. }
  14405. AppendAllocVisitor appendAllocVisitor;
  14406. appendAllocVisitor.mConstAccum = GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr));
  14407. appendAllocVisitor.mIsFirstConstPass = isFirstRun;
  14408. BfTypedValue baseCtorAppendValue = CallBaseCtorCalc(true);
  14409. if (baseCtorAppendValue)
  14410. {
  14411. if (baseCtorAppendValue.mValue.IsFake())
  14412. appendAllocVisitor.mFailed = true;
  14413. else
  14414. appendAllocVisitor.mConstAccum = baseCtorAppendValue;
  14415. }
  14416. appendAllocVisitor.mModule = this;
  14417. appendAllocVisitor.VisitChild(methodDecl->mBody);
  14418. if (constResolveState.mFailed)
  14419. appendAllocVisitor.mFailed = true;
  14420. if (!appendAllocVisitor.mFailed)
  14421. constValue = appendAllocVisitor.mConstAccum;
  14422. if (isFirstRun)
  14423. {
  14424. mCurMethodInstance->mEndingAppendAllocAlign = appendAllocVisitor.mCurAppendAlign;
  14425. if (mCurMethodInstance->mAppendAllocAlign <= 0)
  14426. mCurMethodInstance->mAppendAllocAlign = 1;
  14427. }
  14428. if (isFirstRun)
  14429. {
  14430. for (int paramIdx = 0; paramIdx < methodInst->GetParamCount(); paramIdx++)
  14431. {
  14432. auto localVar = mCurMethodState->mLocals[paramIdx];
  14433. if (localVar->mReadFromId != -1)
  14434. {
  14435. auto& param = methodInst->mParams[paramIdx];
  14436. param.mReferencedInConstPass = true;
  14437. }
  14438. }
  14439. }
  14440. }
  14441. mBfIRBuilder->SetInsertPoint(prevBlock);
  14442. if (!constValue)
  14443. {
  14444. // If we did a 'force' then some params may not have been const -- only clear mMayBeConst if we had
  14445. // all-const args
  14446. if (wasAllConst)
  14447. {
  14448. methodInst->mMayBeConst = false;
  14449. }
  14450. }
  14451. return constValue;
  14452. }
  14453. BfTypedValue BfModule::CallBaseCtorCalc(bool constOnly)
  14454. {
  14455. // Any errors should only be shown in the actual CTOR call
  14456. SetAndRestoreValue<bool> prevIgnoreWrites(mIgnoreErrors, true);
  14457. auto methodDef = mCurMethodInstance->mMethodDef;
  14458. BF_ASSERT((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend));
  14459. auto ctorDeclaration = (BfConstructorDeclaration*)methodDef->mMethodDeclaration;
  14460. BfCustomAttributes* customAttributes = NULL;
  14461. defer(delete customAttributes);
  14462. BfInvocationExpression* ctorInvocation = NULL;
  14463. if (ctorDeclaration != NULL)
  14464. {
  14465. ctorInvocation = BfNodeDynCast<BfInvocationExpression>(ctorDeclaration->mInitializer);
  14466. if (auto attributedExpr = BfNodeDynCast<BfAttributedExpression>(ctorDeclaration->mInitializer))
  14467. {
  14468. ctorInvocation = BfNodeDynCast<BfInvocationExpression>(attributedExpr->mExpression);
  14469. customAttributes = GetCustomAttributes(attributedExpr->mAttributes, BfAttributeTargets_MemberAccess);
  14470. }
  14471. }
  14472. BfTypeInstance* targetType = NULL;
  14473. if (ctorInvocation != NULL)
  14474. {
  14475. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorInvocation->mTarget);
  14476. targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  14477. }
  14478. else
  14479. targetType = mCurTypeInstance->mBaseType;
  14480. if ((targetType == NULL) || (targetType == mContext->mBfObjectType))
  14481. return NULL;
  14482. auto targetRefNode = methodDef->GetRefNode();
  14483. BfType* targetThisType = targetType;
  14484. BfTypedValue target(mBfIRBuilder->GetFakeVal(), targetThisType);
  14485. BfExprEvaluator exprEvaluator(this);
  14486. BfResolvedArgs argValues;
  14487. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL))
  14488. {
  14489. argValues.Init(&ctorInvocation->mArguments);
  14490. }
  14491. //
  14492. {
  14493. }
  14494. BfFunctionBindResult bindResult;
  14495. bindResult.mSkipThis = true;
  14496. bindResult.mWantsArgs = true;
  14497. {
  14498. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  14499. exprEvaluator.ResolveArgValues(argValues, BfResolveArgsFlag_DeferParamEval);
  14500. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(exprEvaluator.mFunctionBindResult, &bindResult);
  14501. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, true);
  14502. }
  14503. if (bindResult.mMethodInstance == NULL)
  14504. {
  14505. AssertErrorState();
  14506. return BfTypedValue();
  14507. }
  14508. if (!bindResult.mMethodInstance->mMethodDef->mHasAppend)
  14509. {
  14510. return BfTypedValue();
  14511. }
  14512. BF_ASSERT(bindResult.mIRArgs[0].IsFake());
  14513. bindResult.mIRArgs.RemoveAt(0);
  14514. auto calcAppendMethodModule = GetMethodInstanceAtIdx(bindResult.mMethodInstance->GetOwner(), bindResult.mMethodInstance->mMethodDef->mIdx + 1, BF_METHODNAME_CALCAPPEND);
  14515. BfTypedValue appendSizeTypedValue = TryConstCalcAppend(calcAppendMethodModule.mMethodInstance, bindResult.mIRArgs, true);
  14516. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mAppendAllocAlign >= 0);
  14517. mCurMethodInstance->mAppendAllocAlign = BF_MAX((int)mCurMethodInstance->mAppendAllocAlign, calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  14518. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign > -1);
  14519. mCurMethodState->mCurAppendAlign = BF_MAX(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign, 0);
  14520. if (appendSizeTypedValue)
  14521. return appendSizeTypedValue;
  14522. if (constOnly)
  14523. return BfTypedValue(mBfIRBuilder->GetFakeVal(), GetPrimitiveType(BfTypeCode_IntPtr));
  14524. bool needsRecalc = false;
  14525. for (auto irArg : bindResult.mIRArgs)
  14526. {
  14527. if (irArg.IsFake())
  14528. needsRecalc = true;
  14529. }
  14530. auto calcAppendArgs = bindResult.mIRArgs;
  14531. if (needsRecalc)
  14532. {
  14533. // Do it again, but without mIgnoreWrites set
  14534. BfResolvedArgs argValues;
  14535. argValues.Init(&ctorInvocation->mArguments);
  14536. exprEvaluator.ResolveArgValues(argValues, BfResolveArgsFlag_DeferParamEval);
  14537. BfFunctionBindResult bindResult;
  14538. bindResult.mSkipThis = true;
  14539. bindResult.mWantsArgs = true;
  14540. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(exprEvaluator.mFunctionBindResult, &bindResult);
  14541. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, true);
  14542. BF_ASSERT(bindResult.mIRArgs[0].IsFake());
  14543. bindResult.mIRArgs.RemoveAt(0);
  14544. calcAppendArgs = bindResult.mIRArgs;
  14545. }
  14546. BF_ASSERT(calcAppendMethodModule.mFunc);
  14547. appendSizeTypedValue = exprEvaluator.CreateCall(NULL, calcAppendMethodModule.mMethodInstance, calcAppendMethodModule.mFunc, false, calcAppendArgs);
  14548. BF_ASSERT(appendSizeTypedValue.mType == GetPrimitiveType(BfTypeCode_IntPtr));
  14549. return appendSizeTypedValue;
  14550. }
  14551. // This method never throws errors - it relies on the proper ctor actually throwing the errors
  14552. void BfModule::EmitCtorCalcAppend()
  14553. {
  14554. if ((mCompiler->mIsResolveOnly) && (!mIsComptimeModule))
  14555. return;
  14556. auto methodDef = mCurMethodInstance->mMethodDef;
  14557. auto methodDecl = methodDef->GetMethodDeclaration();
  14558. Array<BfAstNode*> deferredNodeList;
  14559. auto methodDeclBlock = BfNodeDynCast<BfBlock>(methodDecl->mBody);
  14560. if (methodDeclBlock == NULL)
  14561. return;
  14562. AppendAllocVisitor appendAllocVisitor;
  14563. auto baseCalcAppend = CallBaseCtorCalc(false);
  14564. if (baseCalcAppend)
  14565. {
  14566. mBfIRBuilder->CreateStore(baseCalcAppend.mValue, mCurMethodState->mRetVal.mValue);
  14567. }
  14568. appendAllocVisitor.mModule = this;
  14569. appendAllocVisitor.VisitChild(methodDecl->mBody);
  14570. }
  14571. void BfModule::CreateStaticCtor()
  14572. {
  14573. auto typeDef = mCurTypeInstance->mTypeDef;
  14574. auto methodDef = mCurMethodInstance->mMethodDef;
  14575. BfIRBlock exitBB;
  14576. if ((HasCompiledOutput()) && (!mCurMethodInstance->mIsUnspecialized) && (mCurMethodInstance->mChainType != BfMethodChainType_ChainMember))
  14577. {
  14578. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  14579. auto didStaticInitVarAddr = mBfIRBuilder->CreateGlobalVariable(
  14580. mBfIRBuilder->MapType(boolType),
  14581. false,
  14582. BfIRLinkageType_Internal,
  14583. GetDefaultValue(boolType),
  14584. "didStaticInit");
  14585. auto initBB = mBfIRBuilder->CreateBlock("init", true);
  14586. mCurMethodState->mIRExitBlock = mBfIRBuilder->CreateBlock("exit", true);
  14587. auto didStaticInitVar = mBfIRBuilder->CreateLoad(didStaticInitVarAddr);
  14588. mBfIRBuilder->CreateCondBr(didStaticInitVar, mCurMethodState->mIRExitBlock, initBB);
  14589. mBfIRBuilder->SetInsertPoint(initBB);
  14590. mBfIRBuilder->CreateStore(GetConstValue(1, boolType), didStaticInitVarAddr);
  14591. }
  14592. // Do DLL imports
  14593. if (!mDllImportEntries.empty())
  14594. {
  14595. auto internalType = ResolveTypeDef(mCompiler->mInternalTypeDef);
  14596. PopulateType(internalType);
  14597. auto getSharedProcAddressInstance = GetMethodByName(internalType->ToTypeInstance(), "GetSharedProcAddress");
  14598. if (!getSharedProcAddressInstance)
  14599. {
  14600. if (!mCompiler->mPassInstance->HasFailed())
  14601. Fail("Internal error: System.Internal doesn't contain LoadSharedLibrary method");
  14602. }
  14603. }
  14604. // Fill in initializer values
  14605. if ((!mCompiler->mIsResolveOnly) || (mCompiler->mResolvePassData->mAutoComplete == NULL))
  14606. {
  14607. for (auto fieldDef : typeDef->mFields)
  14608. {
  14609. if ((!fieldDef->mIsConst) && (fieldDef->mIsStatic) && (fieldDef->GetInitializer() != NULL))
  14610. {
  14611. // For extensions, only handle these fields in the appropriate extension
  14612. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  14613. continue;
  14614. UpdateSrcPos(fieldDef->GetInitializer());
  14615. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  14616. if (!fieldInst->mFieldIncluded)
  14617. continue;
  14618. if (fieldInst->mResolvedType->IsVar())
  14619. {
  14620. continue;
  14621. }
  14622. if (fieldInst->IsAppendedObject())
  14623. AppendedObjectInit(fieldInst);
  14624. else
  14625. GetFieldInitializerValue(fieldInst, NULL, NULL, NULL, true);
  14626. }
  14627. }
  14628. auto _CheckInitBlock = [&](BfAstNode* node)
  14629. {
  14630. };
  14631. EmitInitBlocks(_CheckInitBlock);
  14632. }
  14633. else
  14634. {
  14635. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  14636. {
  14637. if (tempTypeDef->mFullName == typeDef->mFullName)
  14638. {
  14639. for (auto fieldDef : tempTypeDef->mFields)
  14640. {
  14641. if ((fieldDef->mIsStatic) && (!fieldDef->mIsConst))
  14642. {
  14643. if (fieldDef->GetInitializer() != NULL)
  14644. {
  14645. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(fieldDef->GetInitializer()))
  14646. {
  14647. sourceClassifier->SetElementType(fieldDef->GetInitializer(), BfSourceElementType_Normal);
  14648. sourceClassifier->VisitChildNoRef(fieldDef->GetInitializer());
  14649. }
  14650. BfType* wantType = NULL;
  14651. if ((!BfNodeIsA<BfVarTypeReference>(fieldDef->mTypeRef)) && (!BfNodeIsA<BfLetTypeReference>(fieldDef->mTypeRef)))
  14652. {
  14653. wantType = ResolveTypeRef(fieldDef->mTypeRef, BfPopulateType_Identity, BfResolveTypeRefFlag_AllowInferredSizedArray);
  14654. }
  14655. BfEvalExprFlags exprFlags = BfEvalExprFlags_FieldInitializer;
  14656. if (fieldDef->mIsAppend)
  14657. exprFlags = (BfEvalExprFlags)(exprFlags | BfEvalExprFlags_AppendFieldInitializer);
  14658. CreateValueFromExpression(fieldDef->GetInitializer(), wantType, exprFlags);
  14659. }
  14660. }
  14661. }
  14662. }
  14663. }
  14664. }
  14665. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  14666. CallChainedMethods(mCurMethodInstance, false);
  14667. }
  14668. void BfModule::EmitDtorBody()
  14669. {
  14670. if (!mCurMethodState->mIRExitBlock)
  14671. mCurMethodState->mIRExitBlock = mBfIRBuilder->CreateBlock("exit", true);
  14672. if (mCurTypeInstance->IsClosure())
  14673. {
  14674. BfFieldInstance* fieldInstance = &mCurTypeInstance->mFieldInstances.back();
  14675. BF_ASSERT(fieldInstance->GetFieldDef()->mName == "__dtorThunk");
  14676. auto thisVal = GetThis();
  14677. auto dtorThunkPtr = mBfIRBuilder->CreateInBoundsGEP(thisVal.mValue, 0, fieldInstance->mDataIdx);
  14678. auto dtorThunk = mBfIRBuilder->CreateLoad(dtorThunkPtr);
  14679. auto funcPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapMethod(mCurMethodInstance));
  14680. auto dtorPtr = mBfIRBuilder->CreateBitCast(dtorThunk, funcPtrType);
  14681. SizedArray<BfIRValue, 1> args;
  14682. args.push_back(thisVal.mValue);
  14683. auto result = mBfIRBuilder->CreateCall(dtorPtr, args);
  14684. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_CDecl);
  14685. // Fall through to Object::~this call
  14686. auto dtorFunc = GetMethodByName(mContext->mBfObjectType, "~this");
  14687. if (mIsComptimeModule)
  14688. mCompiler->mCeMachine->QueueMethod(dtorFunc.mMethodInstance, dtorFunc.mFunc);
  14689. auto basePtr = mBfIRBuilder->CreateBitCast(thisVal.mValue, mBfIRBuilder->MapTypeInstPtr(mContext->mBfObjectType));
  14690. SizedArray<BfIRValue, 1> vals = { basePtr };
  14691. result = mBfIRBuilder->CreateCall(dtorFunc.mFunc, vals);
  14692. mBfIRBuilder->SetCallCallingConv(result, GetIRCallingConvention(dtorFunc.mMethodInstance));
  14693. mBfIRBuilder->SetTailCall(result);
  14694. return;
  14695. }
  14696. auto typeDef = mCurTypeInstance->mTypeDef;
  14697. auto methodDef = mCurMethodInstance->mMethodDef;
  14698. auto methodDeclaration = methodDef->GetMethodDeclaration();
  14699. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  14700. CallChainedMethods(mCurMethodInstance, true);
  14701. if (auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody))
  14702. {
  14703. VisitEmbeddedStatement(bodyBlock);
  14704. if (bodyBlock->mCloseBrace != NULL)
  14705. {
  14706. UpdateSrcPos(bodyBlock->mCloseBrace);
  14707. }
  14708. }
  14709. else
  14710. {
  14711. if (methodDeclaration != NULL)
  14712. UpdateSrcPos(methodDeclaration);
  14713. else if ((methodDef->mDeclaringType != NULL) && (methodDef->mDeclaringType->GetRefNode() != NULL))
  14714. UpdateSrcPos(methodDef->mDeclaringType->GetRefNode());
  14715. else if (typeDef->mTypeDeclaration != NULL)
  14716. UpdateSrcPos(typeDef->mTypeDeclaration);
  14717. if ((methodDeclaration != NULL) && (methodDeclaration->mFatArrowToken != NULL))
  14718. {
  14719. Fail("Destructors cannot have expression bodies", methodDeclaration->mFatArrowToken, true);
  14720. }
  14721. }
  14722. if ((!mCompiler->mIsResolveOnly) || (mCompiler->mResolvePassData->mAutoComplete == NULL))
  14723. {
  14724. for (int fieldIdx = (int)mCurTypeInstance->mFieldInstances.size() - 1; fieldIdx >= 0; fieldIdx--)
  14725. {
  14726. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldIdx];
  14727. auto fieldDef = fieldInst->GetFieldDef();
  14728. BfFieldDeclaration* fieldDecl = NULL;
  14729. if (fieldDef != NULL)
  14730. fieldDecl = fieldDef->GetFieldDeclaration();
  14731. if ((fieldDef != NULL) && (fieldDef->mIsStatic == methodDef->mIsStatic) && (fieldInst->IsAppendedObject()))
  14732. {
  14733. auto refNode = fieldDef->GetRefNode();
  14734. UpdateSrcPos(refNode);
  14735. auto objectType = mContext->mBfObjectType;
  14736. BfTypeInstance* checkTypeInst = mCurTypeInstance->ToTypeInstance();
  14737. BfTypedValue val;
  14738. if (fieldDef->mIsStatic)
  14739. val = ReferenceStaticField(fieldInst);
  14740. else
  14741. {
  14742. auto fieldAddr = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, fieldInst->mDataIdx);
  14743. val = BfTypedValue(mBfIRBuilder->CreateBitCast(fieldAddr, mBfIRBuilder->MapType(fieldInst->mResolvedType)), fieldInst->mResolvedType);
  14744. }
  14745. bool allowPrivate = checkTypeInst == mCurTypeInstance;
  14746. bool allowProtected = allowPrivate || TypeIsSubTypeOf(mCurTypeInstance, checkTypeInst);
  14747. while (checkTypeInst != NULL)
  14748. {
  14749. auto dtorMethodDef = checkTypeInst->mTypeDef->GetMethodByName("~this");
  14750. if (dtorMethodDef)
  14751. {
  14752. if (!CheckProtection(dtorMethodDef->mProtection, checkTypeInst->mTypeDef, allowProtected, allowPrivate))
  14753. {
  14754. auto error = Fail(StrFormat("'%s.~this()' is inaccessible due to its protection level", TypeToString(checkTypeInst).c_str()), refNode); // CS0122
  14755. }
  14756. }
  14757. checkTypeInst = checkTypeInst->mBaseType;
  14758. allowPrivate = false;
  14759. }
  14760. // call dtor
  14761. BfExprEvaluator expressionEvaluator(this);
  14762. PopulateType(val.mType);
  14763. PopulateType(objectType, BfPopulateType_DataAndMethods);
  14764. if (objectType->mVirtualMethodTable.size() == 0)
  14765. {
  14766. if (!mCompiler->IsAutocomplete())
  14767. AssertErrorState();
  14768. }
  14769. else if (!IsSkippingExtraResolveChecks())
  14770. {
  14771. BfMethodInstance* methodInstance = objectType->mVirtualMethodTable[mCompiler->GetVTableMethodOffset() + 0].mImplementingMethod;
  14772. BF_ASSERT(methodInstance->mMethodDef->mName == "~this");
  14773. SizedArray<BfIRValue, 4> llvmArgs;
  14774. llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(objectType)));
  14775. expressionEvaluator.CreateCall(refNode, methodInstance, mBfIRBuilder->GetFakeVal(), false, llvmArgs);
  14776. }
  14777. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  14778. {
  14779. auto int8PtrType = CreatePointerType(GetPrimitiveType(BfTypeCode_Int8));
  14780. auto int8PtrVal = mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(int8PtrType));
  14781. mBfIRBuilder->CreateStore(GetConstValue8(BfObjectFlag_Deleted), int8PtrVal);
  14782. }
  14783. }
  14784. if ((fieldDef != NULL) && (fieldDef->mIsStatic == methodDef->mIsStatic) && (fieldDecl != NULL) && (fieldDecl->mFieldDtor != NULL))
  14785. {
  14786. if (fieldDef->mDeclaringType != mCurMethodInstance->mMethodDef->mDeclaringType)
  14787. {
  14788. BF_ASSERT(mCurTypeInstance->mTypeDef->mIsCombinedPartial);
  14789. continue;
  14790. }
  14791. if ((!methodDef->mIsStatic) && (mCurTypeInstance->IsValueType()))
  14792. {
  14793. Fail("Structs cannot have field destructors", fieldDecl->mFieldDtor->mTildeToken, true);
  14794. }
  14795. SetAndRestoreValue<BfFilePosition> prevFilePos(mCurFilePosition);
  14796. auto fieldDtor = fieldDecl->mFieldDtor;
  14797. if ((fieldDef->mIsStatic) != (methodDef->mIsStatic))
  14798. continue;
  14799. UpdateSrcPos(fieldDtor);
  14800. BfScopeData scopeData;
  14801. mCurMethodState->AddScope(&scopeData);
  14802. NewScopeState();
  14803. UpdateSrcPos(fieldDtor);
  14804. bool hasDbgInfo = (!fieldDef->mIsConst);
  14805. if (hasDbgInfo)
  14806. {
  14807. mBfIRBuilder->SaveDebugLocation();
  14808. mBfIRBuilder->ClearDebugLocation();
  14809. }
  14810. BfIRValue value;
  14811. if (fieldDef->mIsStatic)
  14812. {
  14813. value = ReferenceStaticField(fieldInst).mValue;
  14814. }
  14815. else
  14816. {
  14817. PopulateType(fieldInst->mResolvedType);
  14818. if (fieldInst->mResolvedType->IsValuelessType())
  14819. {
  14820. value = mBfIRBuilder->GetFakeVal();
  14821. }
  14822. else if (!mCurTypeInstance->IsValueType())
  14823. {
  14824. auto thisValue = GetThis();
  14825. value = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInst->mDataIdx);
  14826. }
  14827. else
  14828. {
  14829. AssertErrorState();
  14830. value = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(fieldInst->mResolvedType));
  14831. }
  14832. }
  14833. BfIRValue staticVal;
  14834. if (hasDbgInfo)
  14835. {
  14836. BfIRValue dbgShowValue = value;
  14837. BfLocalVariable* localDef = new BfLocalVariable();
  14838. localDef->mName = "_";
  14839. localDef->mResolvedType = fieldInst->mResolvedType;
  14840. localDef->mAddr = value;
  14841. if ((mBfIRBuilder->DbgHasInfo()) && (!IsTargetingBeefBackend()))
  14842. {
  14843. // Create another pointer indirection, a ref to the gep
  14844. auto refFieldType = CreateRefType(fieldInst->mResolvedType);
  14845. auto allocaInst = CreateAlloca(refFieldType);
  14846. auto storeResult = mBfIRBuilder->CreateStore(value, allocaInst);
  14847. localDef->mResolvedType = refFieldType;
  14848. localDef->mAddr = allocaInst;
  14849. }
  14850. mBfIRBuilder->RestoreDebugLocation();
  14851. auto defLocalVar = AddLocalVariableDef(localDef, true);
  14852. // Put back so we actually modify the correct value*/
  14853. defLocalVar->mResolvedType = fieldInst->mResolvedType;
  14854. defLocalVar->mAddr = value;
  14855. }
  14856. while (fieldDtor != NULL)
  14857. {
  14858. if (mCompiler->mResolvePassData != NULL)
  14859. {
  14860. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(fieldDtor))
  14861. {
  14862. sourceClassifier->SetElementType(fieldDtor, BfSourceElementType_Normal);
  14863. sourceClassifier->VisitChild(fieldDtor);
  14864. }
  14865. }
  14866. UpdateSrcPos(fieldDtor);
  14867. VisitEmbeddedStatement(fieldDtor->mBody);
  14868. fieldDtor = fieldDtor->mNextFieldDtor;
  14869. }
  14870. RestoreScopeState();
  14871. }
  14872. }
  14873. if ((!methodDef->mIsStatic) && (mCurMethodInstance->mChainType != BfMethodChainType_ChainMember))
  14874. {
  14875. auto checkBaseType = mCurTypeInstance->mBaseType;
  14876. while (checkBaseType != NULL)
  14877. {
  14878. if (auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody))
  14879. {
  14880. if (bodyBlock->mCloseBrace != NULL)
  14881. UpdateSrcPos(bodyBlock->mCloseBrace);
  14882. }
  14883. else
  14884. {
  14885. UpdateSrcPos(typeDef->mTypeDeclaration->mNameNode);
  14886. }
  14887. BfMethodDef* dtorMethodDef = checkBaseType->mTypeDef->GetMethodByName("~this");
  14888. if (dtorMethodDef != NULL)
  14889. {
  14890. auto dtorMethodInstance = GetMethodInstance(checkBaseType, dtorMethodDef, BfTypeVector());
  14891. if (IsSkippingExtraResolveChecks())
  14892. {
  14893. // Nothing
  14894. }
  14895. else if (dtorMethodInstance.mMethodInstance->GetParamCount() == 0)
  14896. {
  14897. if ((!IsSkippingExtraResolveChecks()) && (!checkBaseType->IsUnspecializedType()))
  14898. {
  14899. auto basePtr = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapTypeInstPtr(checkBaseType));
  14900. SizedArray<BfIRValue, 1> vals = { basePtr };
  14901. auto callInst = mBfIRBuilder->CreateCall(dtorMethodInstance.mFunc, vals);
  14902. if (mIsComptimeModule)
  14903. mCompiler->mCeMachine->QueueMethod(dtorMethodInstance.mMethodInstance, dtorMethodInstance.mFunc);
  14904. mBfIRBuilder->SetCallCallingConv(callInst, GetIRCallingConvention(dtorMethodInstance.mMethodInstance));
  14905. }
  14906. }
  14907. else
  14908. {
  14909. // Invalid base dtor declaration
  14910. AssertErrorState();
  14911. }
  14912. break;
  14913. }
  14914. checkBaseType = checkBaseType->mBaseType;
  14915. }
  14916. }
  14917. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  14918. }
  14919. else
  14920. {
  14921. // The reason we can't just do the 'normal' path for this is that the BfTypeInstance here is NOT the
  14922. // autocomplete type instance, so FieldInstance initializer values contain expressions from the full
  14923. // resolve pass, NOT the autocomplete expression
  14924. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  14925. {
  14926. if (tempTypeDef->mFullName == typeDef->mFullName)
  14927. {
  14928. for (auto fieldDef : tempTypeDef->mFields)
  14929. {
  14930. auto fieldDecl = fieldDef->GetFieldDeclaration();
  14931. if ((fieldDef->mIsStatic == methodDef->mIsStatic) && (fieldDef->mFieldDeclaration != NULL) &&
  14932. (fieldDecl->mFieldDtor != NULL) && (mCompiler->mResolvePassData->mIsClassifying))
  14933. {
  14934. BfType* fieldType = NULL;
  14935. for (int curFieldIdx = 0; curFieldIdx < (int)mCurTypeInstance->mFieldInstances.size(); curFieldIdx++)
  14936. {
  14937. auto curFieldInstance = &mCurTypeInstance->mFieldInstances[curFieldIdx];
  14938. auto curFieldDef = curFieldInstance->GetFieldDef();
  14939. if ((curFieldDef != NULL) && (fieldDef->mName == curFieldDef->mName))
  14940. fieldType = curFieldInstance->GetResolvedType();
  14941. }
  14942. if (fieldType == NULL)
  14943. fieldType = GetPrimitiveType(BfTypeCode_Var);
  14944. auto fieldDtor = fieldDecl->mFieldDtor;
  14945. BfScopeData scopeData;
  14946. mCurMethodState->AddScope(&scopeData);
  14947. NewScopeState();
  14948. // This is just for autocomplete, it doesn't matter that mAddr is incorrect
  14949. if (fieldType != NULL)
  14950. {
  14951. BfLocalVariable* localDef = new BfLocalVariable();
  14952. localDef->mName = "_";
  14953. localDef->mResolvedType = fieldType;
  14954. localDef->mAddr = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(fieldType));
  14955. localDef->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  14956. AddLocalVariableDef(localDef);
  14957. }
  14958. while (fieldDtor != NULL)
  14959. {
  14960. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(fieldDtor))
  14961. {
  14962. sourceClassifier->SetElementType(fieldDtor, BfSourceElementType_Normal);
  14963. sourceClassifier->VisitChild(fieldDtor);
  14964. }
  14965. UpdateSrcPos(fieldDtor);
  14966. VisitEmbeddedStatement(fieldDtor->mBody);
  14967. fieldDtor = fieldDtor->mNextFieldDtor;
  14968. }
  14969. RestoreScopeState();
  14970. }
  14971. }
  14972. }
  14973. }
  14974. }
  14975. }
  14976. BfIRValue BfModule::CreateDllImportGlobalVar(BfMethodInstance* methodInstance, bool define)
  14977. {
  14978. BF_ASSERT(methodInstance->mIsReified);
  14979. auto typeInstance = methodInstance->GetOwner();
  14980. bool foundDllImportAttr = false;
  14981. BfCallingConvention callingConvention = methodInstance->mCallingConvention;
  14982. for (auto customAttr : methodInstance->GetCustomAttributes()->mAttributes)
  14983. {
  14984. if (customAttr.mType->mTypeDef->mFullName.ToString() == "System.ImportAttribute")
  14985. {
  14986. foundDllImportAttr = true;
  14987. }
  14988. }
  14989. if (!foundDllImportAttr)
  14990. {
  14991. AssertErrorState();
  14992. return BfIRValue();
  14993. }
  14994. StringT<512> name = "bf_hs_preserve@";
  14995. BfMangler::Mangle(name, mCompiler->GetMangleKind(), methodInstance);
  14996. name += "__imp";
  14997. BfIRType returnType;
  14998. SizedArray<BfIRType, 8> paramTypes;
  14999. methodInstance->GetIRFunctionInfo(this, returnType, paramTypes);
  15000. BfIRFunctionType externFunctionType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes, methodInstance->IsVarArgs());
  15001. auto ptrType = mBfIRBuilder->GetPointerTo(externFunctionType);
  15002. BfIRValue initVal;
  15003. if (define)
  15004. {
  15005. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  15006. initVal = mBfIRBuilder->CreateConstNull(ptrType);
  15007. }
  15008. auto globalVar = mBfIRBuilder->CreateGlobalVariable(ptrType, false, BfIRLinkageType_External, initVal, name);
  15009. if ((define) && (mBfIRBuilder->DbgHasInfo()))
  15010. {
  15011. auto voidType = GetPrimitiveType(BfTypeCode_None);
  15012. auto ptrType = CreatePointerType(voidType);
  15013. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, name, name, BfIRMDNode(), 0, mBfIRBuilder->DbgGetType(ptrType), false, globalVar);
  15014. }
  15015. return globalVar;
  15016. }
  15017. void BfModule::CreateDllImportMethod()
  15018. {
  15019. if (mBfIRBuilder->mIgnoreWrites)
  15020. return;
  15021. auto globalVar = mFuncReferences[mCurMethodInstance];
  15022. if (!globalVar)
  15023. return;
  15024. bool allowTailCall = true;
  15025. mBfIRBuilder->ClearDebugLocation();
  15026. bool isHotCompile = mCompiler->IsHotCompile();
  15027. // If we are hot swapping, we need to have this stub because we may need to call the LoadSharedLibraries on demand
  15028. if (isHotCompile)
  15029. {
  15030. auto loadSharedLibsFunc = GetBuiltInFunc(BfBuiltInFuncType_LoadSharedLibraries);
  15031. mBfIRBuilder->CreateCall(loadSharedLibsFunc, SizedArray<BfIRValue, 0>());
  15032. }
  15033. auto callingConvention = GetIRCallingConvention(mCurMethodInstance);
  15034. BfIRType returnType;
  15035. SizedArray<BfIRType, 8> paramTypes;
  15036. mCurMethodInstance->GetIRFunctionInfo(this, returnType, paramTypes, mCurMethodInstance->IsVarArgs());
  15037. SizedArray<BfIRValue, 8> args;
  15038. for (int i = 0; i < (int)paramTypes.size(); i++)
  15039. args.push_back(mBfIRBuilder->GetArgument(i));
  15040. BfIRFunctionType externFunctionType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes, mCurMethodInstance->IsVarArgs());
  15041. if (isHotCompile)
  15042. {
  15043. BfIRValue funcVal = mBfIRBuilder->CreateLoad(globalVar);
  15044. auto result = mBfIRBuilder->CreateCall(funcVal, args);
  15045. if (callingConvention == BfIRCallingConv_StdCall)
  15046. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_StdCall);
  15047. else if (callingConvention == BfIRCallingConv_FastCall)
  15048. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_FastCall);
  15049. else
  15050. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_CDecl);
  15051. if (allowTailCall)
  15052. mBfIRBuilder->SetTailCall(result);
  15053. CreateReturn(result);
  15054. mCurMethodState->mHadReturn = true;
  15055. }
  15056. if (HasCompiledOutput())
  15057. {
  15058. BfDllImportEntry dllImportEntry;
  15059. dllImportEntry.mFuncVar = globalVar;
  15060. dllImportEntry.mMethodInstance = mCurMethodInstance;
  15061. mDllImportEntries.push_back(dllImportEntry);
  15062. }
  15063. }
  15064. BfIRCallingConv BfModule::GetIRCallingConvention(BfMethodInstance* methodInstance)
  15065. {
  15066. auto methodDef = methodInstance->mMethodDef;
  15067. BfTypeInstance* owner = NULL;
  15068. if (!methodDef->mIsStatic)
  15069. owner = methodInstance->GetThisType()->ToTypeInstance();
  15070. if (owner == NULL)
  15071. owner = methodInstance->GetOwner();
  15072. if ((mCompiler->mOptions.mMachineType != BfMachineType_x86) || (mCompiler->mOptions.mPlatformType != BfPlatformType_Windows))
  15073. return BfIRCallingConv_CDecl;
  15074. if (methodInstance->mCallingConvention == BfCallingConvention_Stdcall)
  15075. return BfIRCallingConv_StdCall;
  15076. if (methodInstance->mCallingConvention == BfCallingConvention_Fastcall)
  15077. return BfIRCallingConv_FastCall;
  15078. if (!methodDef->mIsStatic)
  15079. {
  15080. if (owner->mIsCRepr)
  15081. return BfIRCallingConv_ThisCall;
  15082. if ((!owner->IsValuelessType()) &&
  15083. ((!owner->IsSplattable()) || (methodDef->HasNoThisSplat())))
  15084. return BfIRCallingConv_ThisCall;
  15085. }
  15086. return BfIRCallingConv_CDecl;
  15087. //return GetIRCallingConvention(owner, methodInstance->mMethodDef);
  15088. }
  15089. void BfModule::SetupIRMethod(BfMethodInstance* methodInstance, BfIRFunction func, bool isInlined)
  15090. {
  15091. BfMethodDef* methodDef = NULL;
  15092. if (methodInstance != NULL)
  15093. methodDef = methodInstance->mMethodDef;
  15094. if (!func)
  15095. return;
  15096. if (mCompiler->mOptions.mNoFramePointerElim)
  15097. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_NoFramePointerElim);
  15098. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_NoUnwind);
  15099. if (mSystem->mPtrSize == 8) // We need unwind info for debugging
  15100. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_UWTable);
  15101. if (methodInstance == NULL)
  15102. return;
  15103. if (methodInstance->mReturnType->IsVar())
  15104. mBfIRBuilder->Func_AddAttribute(func, -1, BfIRAttribute_VarRet);
  15105. if (methodDef->mImportKind == BfImportKind_Export)
  15106. {
  15107. if (methodDef->mDeclaringType->mProject->mTargetType != BfTargetType_BeefLib_StaticLib)
  15108. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_DllExport);
  15109. }
  15110. if (methodDef->mIsNoReturn)
  15111. mBfIRBuilder->Func_AddAttribute(func, -1, BfIRAttribute_NoReturn);
  15112. auto callingConv = GetIRCallingConvention(methodInstance);
  15113. if (callingConv != BfIRCallingConv_CDecl)
  15114. mBfIRBuilder->SetFuncCallingConv(func, callingConv);
  15115. if (isInlined)
  15116. {
  15117. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_AlwaysInline);
  15118. }
  15119. int argIdx = 0;
  15120. int paramIdx = 0;
  15121. if ((methodInstance->HasThis()) && (!methodDef->mHasExplicitThis))
  15122. paramIdx = -1;
  15123. int argCount = methodInstance->GetIRFunctionParamCount(this);
  15124. while (argIdx < argCount)
  15125. {
  15126. if ((!mIsComptimeModule) && (argIdx == methodInstance->GetStructRetIdx()))
  15127. {
  15128. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_NoAlias);
  15129. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_StructRet);
  15130. argIdx++;
  15131. continue;
  15132. }
  15133. bool isThis = (paramIdx == -1) || ((methodDef->mHasExplicitThis) && (paramIdx == 0));
  15134. while ((!isThis) && (methodInstance->IsParamSkipped(paramIdx)))
  15135. paramIdx++;
  15136. BfType* resolvedTypeRef = NULL;
  15137. BfType* resolvedTypeRef2 = NULL;
  15138. String paramName;
  15139. bool isSplattable = false;
  15140. bool tryLowering = !mIsComptimeModule;
  15141. if (isThis)
  15142. {
  15143. paramName = "this";
  15144. if (methodInstance->mIsClosure)
  15145. resolvedTypeRef = mCurMethodState->mClosureState->mClosureType;
  15146. else
  15147. resolvedTypeRef = methodInstance->GetThisType();
  15148. isSplattable = (!mIsComptimeModule) && (resolvedTypeRef->IsSplattable()) && (methodInstance->AllowsSplatting(-1));
  15149. tryLowering = (!mIsComptimeModule) && (methodInstance->AllowsSplatting(-1));
  15150. }
  15151. else
  15152. {
  15153. paramName = methodInstance->GetParamName(paramIdx);
  15154. resolvedTypeRef = methodInstance->GetParamType(paramIdx);
  15155. if (resolvedTypeRef->IsMethodRef())
  15156. isSplattable = true;
  15157. else if ((!mIsComptimeModule) && (resolvedTypeRef->IsSplattable()) && (methodInstance->AllowsSplatting(paramIdx)))
  15158. {
  15159. auto resolvedTypeInst = resolvedTypeRef->ToTypeInstance();
  15160. if ((resolvedTypeInst != NULL) && (resolvedTypeInst->mIsCRepr))
  15161. {
  15162. // crepr splat is always splattable
  15163. isSplattable = true;
  15164. }
  15165. else
  15166. {
  15167. auto resolvedTypeInst = resolvedTypeRef->ToTypeInstance();
  15168. if ((resolvedTypeInst != NULL) && (resolvedTypeInst->mIsCRepr))
  15169. isSplattable = true;
  15170. else if (resolvedTypeRef->GetSplatCount() + argIdx <= mCompiler->mOptions.mMaxSplatRegs)
  15171. isSplattable = true;
  15172. }
  15173. }
  15174. }
  15175. if (tryLowering)
  15176. {
  15177. BfTypeCode loweredTypeCode = BfTypeCode_None;
  15178. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  15179. if (resolvedTypeRef->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2))
  15180. {
  15181. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, paramName + "__1");
  15182. argIdx++;
  15183. if (loweredTypeCode2 != BfTypeCode_None)
  15184. {
  15185. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, paramName + "__2");
  15186. argIdx++;
  15187. }
  15188. paramIdx++;
  15189. continue;
  15190. }
  15191. }
  15192. auto _SetupParam = [&](const StringImpl& paramName, BfType* resolvedTypeRef)
  15193. {
  15194. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, paramName);
  15195. int addDeref = -1;
  15196. if (resolvedTypeRef->IsRef())
  15197. {
  15198. auto refType = (BfRefType*)resolvedTypeRef;
  15199. auto elementType = refType->mElementType;
  15200. PopulateType(elementType, BfPopulateType_Data);
  15201. addDeref = elementType->mSize;
  15202. if ((addDeref <= 0) && (!elementType->IsValuelessType()) && (!elementType->IsOpaque()))
  15203. AssertErrorState();
  15204. }
  15205. if ((resolvedTypeRef->IsComposite()) && (!resolvedTypeRef->IsTypedPrimitive()))
  15206. {
  15207. if (isThis)
  15208. {
  15209. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_NoCapture);
  15210. PopulateType(resolvedTypeRef, BfPopulateType_Data);
  15211. addDeref = resolvedTypeRef->mSize;
  15212. }
  15213. else if (methodInstance->WantsStructsAttribByVal(resolvedTypeRef))
  15214. {
  15215. mBfIRBuilder->PopulateType(resolvedTypeRef, BfIRPopulateType_Full);
  15216. BF_ASSERT(resolvedTypeRef->mAlign > 0);
  15217. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_ByVal, mSystem->mPtrSize);
  15218. }
  15219. }
  15220. else if (resolvedTypeRef->IsPrimitiveType())
  15221. {
  15222. auto primType = (BfPrimitiveType*)resolvedTypeRef;
  15223. if (primType->mTypeDef->mTypeCode == BfTypeCode_Boolean)
  15224. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_ZExt);
  15225. }
  15226. if (addDeref >= 0)
  15227. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_Dereferencable, addDeref);
  15228. argIdx++;
  15229. };
  15230. if (isSplattable)
  15231. {
  15232. std::function<void(BfType*, const StringImpl&)> checkTypeLambda = [&](BfType* checkType, const StringImpl& curName)
  15233. {
  15234. if (checkType->IsStruct())
  15235. {
  15236. auto checkTypeInstance = checkType->ToTypeInstance();
  15237. if (checkTypeInstance->mBaseType != NULL)
  15238. checkTypeLambda(checkTypeInstance->mBaseType, curName);
  15239. if (checkTypeInstance->mIsUnion)
  15240. {
  15241. BfType* unionInnerType = checkTypeInstance->GetUnionInnerType();
  15242. checkTypeLambda(unionInnerType, curName + "_data");
  15243. }
  15244. else
  15245. {
  15246. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  15247. {
  15248. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  15249. auto fieldDef = fieldInstance->GetFieldDef();
  15250. if (fieldInstance->mDataIdx >= 0)
  15251. {
  15252. checkTypeLambda(fieldInstance->GetResolvedType(), curName + "_" + fieldInstance->GetFieldDef()->mName);
  15253. }
  15254. }
  15255. }
  15256. if (checkTypeInstance->IsEnum())
  15257. {
  15258. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, curName + "_dscr");
  15259. argIdx++;
  15260. }
  15261. }
  15262. else if (checkType->IsMethodRef())
  15263. {
  15264. auto methodRefType = (BfMethodRefType*)checkType;
  15265. BfMethodInstance* methodRefMethodInst = methodRefType->mMethodRef;
  15266. for (int dataIdx = 0; dataIdx < (int)methodRefType->GetCaptureDataCount(); dataIdx++)
  15267. {
  15268. int methodRefParamIdx = methodRefType->GetParamIdxFromDataIdx(dataIdx);
  15269. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  15270. {
  15271. checkTypeLambda(methodRefType->GetCaptureType(dataIdx), curName + "_" + methodRefMethodInst->GetParamName(methodRefParamIdx));
  15272. }
  15273. else
  15274. {
  15275. _SetupParam(curName + "_" + methodRefMethodInst->GetParamName(methodRefParamIdx), methodRefType->GetCaptureType(dataIdx));
  15276. }
  15277. }
  15278. }
  15279. else if (!checkType->IsValuelessType())
  15280. {
  15281. _SetupParam(curName, checkType);
  15282. }
  15283. };
  15284. checkTypeLambda(resolvedTypeRef, paramName);
  15285. paramIdx++;
  15286. continue;
  15287. }
  15288. _SetupParam(paramName, resolvedTypeRef);
  15289. if (resolvedTypeRef2 != NULL)
  15290. _SetupParam(paramName, resolvedTypeRef2);
  15291. paramIdx++;
  15292. }
  15293. }
  15294. void BfModule::EmitInitBlocks(const std::function<void(BfAstNode*)>& initBlockCallback)
  15295. {
  15296. auto methodDef = mCurMethodInstance->mMethodDef;
  15297. mCurTypeInstance->mTypeDef->PopulateMemberSets();
  15298. BfMemberSetEntry* entry = NULL;
  15299. BfMethodDef* initMethodDef = NULL;
  15300. mCurTypeInstance->mTypeDef->mMethodSet.TryGetWith(String("__BfInit"), &entry);
  15301. if (entry != NULL)
  15302. initMethodDef = (BfMethodDef*)entry->mMemberDef;
  15303. SizedArray<BfAstNode*, 8> initBodies;
  15304. for (; initMethodDef != NULL; initMethodDef = initMethodDef->mNextWithSameName)
  15305. {
  15306. if (initMethodDef->mDeclaringType->GetDefinition() != methodDef->mDeclaringType->GetDefinition())
  15307. continue;
  15308. if (initMethodDef->mMethodType != BfMethodType_Init)
  15309. continue;
  15310. if (initMethodDef->mIsStatic != methodDef->mIsStatic)
  15311. continue;
  15312. initBodies.Insert(0, initMethodDef->mBody);
  15313. }
  15314. for (auto body : initBodies)
  15315. {
  15316. initBlockCallback(body);
  15317. VisitEmbeddedStatement(body);
  15318. }
  15319. }
  15320. void BfModule::EmitCtorBody(bool& skipBody)
  15321. {
  15322. auto methodInstance = mCurMethodInstance;
  15323. auto methodDef = methodInstance->mMethodDef;
  15324. auto methodDeclaration = methodDef->mMethodDeclaration;
  15325. auto ctorDeclaration = (BfConstructorDeclaration*)methodDef->mMethodDeclaration;
  15326. auto typeDef = mCurTypeInstance->mTypeDef;
  15327. BfCustomAttributes* customAttributes = NULL;
  15328. defer(delete customAttributes);
  15329. BfInvocationExpression* ctorInvocation = NULL;
  15330. BfAttributeState attributeState;
  15331. attributeState.mTarget = BfAttributeTargets_MemberAccess;
  15332. if (ctorDeclaration != NULL)
  15333. {
  15334. ctorInvocation = BfNodeDynCast<BfInvocationExpression>(ctorDeclaration->mInitializer);
  15335. if (auto attributedExpr = BfNodeDynCast<BfAttributedExpression>(ctorDeclaration->mInitializer))
  15336. {
  15337. ctorInvocation = BfNodeDynCast<BfInvocationExpression>(attributedExpr->mExpression);
  15338. attributeState.mCustomAttributes = GetCustomAttributes(attributedExpr->mAttributes, attributeState.mTarget);
  15339. }
  15340. }
  15341. SetAndRestoreValue<BfAttributeState*> prevAttributeState(mAttributeState, &attributeState);
  15342. // Prologue
  15343. mBfIRBuilder->ClearDebugLocation();
  15344. bool hadThisInitializer = false;
  15345. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL))
  15346. {
  15347. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorInvocation->mTarget);
  15348. auto targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  15349. if (targetToken->GetToken() == BfToken_This)
  15350. {
  15351. hadThisInitializer = true;
  15352. // Since we call a 'this', it's that other ctor's responsibility to fully assign the fields
  15353. mCurMethodState->LocalDefined(GetThisVariable());
  15354. }
  15355. }
  15356. // Zero out memory for default ctor
  15357. if ((methodDeclaration == NULL) && (mCurTypeInstance->IsStruct()) && (methodInstance->mChainType != BfMethodChainType_ChainMember))
  15358. {
  15359. if (mCurTypeInstance->IsTypedPrimitive())
  15360. {
  15361. auto thisRef = mCurMethodState->mLocals[0]->mValue;
  15362. mBfIRBuilder->CreateStore(GetDefaultValue(mCurTypeInstance), thisRef);
  15363. }
  15364. else if (mCurTypeInstance->mInstSize > 0)
  15365. {
  15366. BfIRValue fillValue = GetConstValue8(0);
  15367. BfIRValue sizeValue = GetConstValue(mCurTypeInstance->mInstSize);
  15368. auto thisRef = mCurMethodState->mLocals[0]->mValue;
  15369. BfIRValue destBits = mBfIRBuilder->CreateBitCast(thisRef, mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr));
  15370. mBfIRBuilder->CreateMemSet(destBits, fillValue, sizeValue, mCurTypeInstance->mAlign);
  15371. }
  15372. }
  15373. BfAstNode* baseCtorNode = NULL;
  15374. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL) && (ctorInvocation->mTarget != NULL))
  15375. baseCtorNode = ctorInvocation->mTarget;
  15376. else if (methodDef->mBody != NULL)
  15377. baseCtorNode = methodDef->mBody;
  15378. else if (ctorDeclaration != NULL)
  15379. baseCtorNode = ctorDeclaration;
  15380. else if ((methodDef->mDeclaringType != NULL) && (methodDef->mDeclaringType->GetRefNode() != NULL))
  15381. baseCtorNode = methodDef->mDeclaringType->GetRefNode();
  15382. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  15383. baseCtorNode = mCurTypeInstance->mTypeDef->mTypeDeclaration->mNameNode;
  15384. else if ((mCurTypeInstance->mBaseType != NULL) && (mCurTypeInstance->mBaseType->mTypeDef->mTypeDeclaration != NULL))
  15385. baseCtorNode = mCurTypeInstance->mBaseType->mTypeDef->mTypeDeclaration;
  15386. else
  15387. baseCtorNode = mContext->mBfObjectType->mTypeDef->mTypeDeclaration;
  15388. bool calledCtorNoBody = false;
  15389. if ((mCurTypeInstance->IsTypedPrimitive()) && (!mCurTypeInstance->IsValuelessType()))
  15390. {
  15391. // Zero out typed primitives in ctor
  15392. mBfIRBuilder->CreateAlignedStore(GetDefaultValue(mCurTypeInstance->GetUnderlyingType()), mBfIRBuilder->GetArgument(0), mCurTypeInstance->mAlign);
  15393. }
  15394. if ((!mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType == BfMethodType_Ctor) && (!hadThisInitializer))
  15395. {
  15396. // Call the root type's default ctor (with no body) to initialize its fields and call the chained ctors
  15397. if (mCurTypeInstance->mTypeDef->mHasCtorNoBody)
  15398. {
  15399. BfMethodDef* defaultCtor = NULL;
  15400. for (auto methodDef : mCurTypeInstance->mTypeDef->mMethods)
  15401. {
  15402. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) && (methodDef->mDeclaringType->mTypeCode != BfTypeCode_Extension))
  15403. {
  15404. defaultCtor = methodDef;
  15405. }
  15406. }
  15407. if (defaultCtor != NULL)
  15408. {
  15409. UpdateSrcPos(mCurTypeInstance->mTypeDef->GetRefNode());
  15410. SetIllegalSrcPos();
  15411. auto moduleMethodInstance = GetMethodInstance(mCurTypeInstance, defaultCtor, BfTypeVector());
  15412. BfExprEvaluator exprEvaluator(this);
  15413. SizedArray<BfIRValue, 1> irArgs;
  15414. exprEvaluator.PushThis(NULL, GetThis(), moduleMethodInstance.mMethodInstance, irArgs);
  15415. exprEvaluator.CreateCall(NULL, moduleMethodInstance.mMethodInstance, moduleMethodInstance.mFunc, false, irArgs);
  15416. if (mIsComptimeModule)
  15417. mCompiler->mCeMachine->QueueMethod(moduleMethodInstance);
  15418. calledCtorNoBody = true;
  15419. }
  15420. }
  15421. }
  15422. // Initialize fields (if applicable)
  15423. if (mCurTypeInstance->IsBoxed())
  15424. {
  15425. skipBody = true;
  15426. }
  15427. else if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mDeclaringType->mTypeCode == BfTypeCode_Extension))
  15428. {
  15429. // Field initializers occur in CtorNoBody methods for extensions
  15430. }
  15431. else if (!hadThisInitializer)
  15432. {
  15433. // If we had a 'this' initializer, that other ctor will have initialized our fields
  15434. //auto
  15435. if ((!mCompiler->mIsResolveOnly) ||
  15436. (mCompiler->mResolvePassData->mAutoComplete == NULL) ||
  15437. (mCompiler->mResolvePassData->mAutoComplete->mResolveType == BfResolveType_ShowFileSymbolReferences))
  15438. {
  15439. // If we calledCtorNoBody then we did the field initializer code, but we still need to run though it here
  15440. // to properly set the assigned flags
  15441. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mBfIRBuilder->mIgnoreWrites || calledCtorNoBody);
  15442. bool hadInlineInitBlock = false;
  15443. BfScopeData scopeData;
  15444. scopeData.mInInitBlock = true;
  15445. auto _CheckInitBlock = [&](BfAstNode* node)
  15446. {
  15447. if (!hadInlineInitBlock)
  15448. {
  15449. if ((mBfIRBuilder->DbgHasInfo()) && (!mCurTypeInstance->IsUnspecializedType()) && (mHasFullDebugInfo))
  15450. {
  15451. UpdateSrcPos(baseCtorNode);
  15452. if (methodDef->mBody == NULL)
  15453. SetIllegalSrcPos();
  15454. // 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
  15455. EmitEnsureInstructionAt();
  15456. BfType* thisType = mCurTypeInstance;
  15457. if (thisType->IsValueType())
  15458. thisType = CreateRefType(thisType);
  15459. SizedArray<BfIRMDNode, 1> diParamTypes;
  15460. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParamTypes);
  15461. mCurMethodState->AddScope(&scopeData);
  15462. NewScopeState();
  15463. int flags = 0;
  15464. mCurMethodState->mCurScope->mDIInlinedAt = mBfIRBuilder->DbgGetCurrentLocation();
  15465. BF_ASSERT(mCurMethodState->mCurScope->mDIInlinedAt);
  15466. // mCurMethodState->mCurScope->mDIInlinedAt may still be null ifwe don't have an explicit ctor
  15467. String linkageName;
  15468. if ((mIsComptimeModule) && (mCompiler->mCeMachine->mCurBuilder != NULL))
  15469. linkageName = StrFormat("%d", mCompiler->mCeMachine->mCurBuilder->DbgCreateMethodRef(mCurMethodInstance, "$initFields"));
  15470. mCurMethodState->mCurScope->mDIScope = mBfIRBuilder->DbgCreateFunction(mBfIRBuilder->DbgGetTypeInst(mCurTypeInstance), "this$initFields", linkageName, mCurFilePosition.mFileInstance->mDIFile,
  15471. mCurFilePosition.mCurLine + 1, diFuncType, false, true, mCurFilePosition.mCurLine + 1, flags, false, BfIRValue());
  15472. UpdateSrcPos(node);
  15473. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  15474. "this", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(thisType));
  15475. //
  15476. {
  15477. auto loadedThis = GetThis();
  15478. // LLVM can't handle two variables pointing to the same value
  15479. BfIRValue copiedThisPtr;
  15480. copiedThisPtr = CreateAlloca(thisType);
  15481. auto storeInst = mBfIRBuilder->CreateStore(loadedThis.mValue, copiedThisPtr);
  15482. mBfIRBuilder->ClearDebugLocation(storeInst);
  15483. mBfIRBuilder->DbgInsertDeclare(copiedThisPtr, diVariable);
  15484. }
  15485. hadInlineInitBlock = true;
  15486. }
  15487. else
  15488. {
  15489. // Just do a simple one
  15490. mCurMethodState->AddScope(&scopeData);
  15491. NewScopeState();
  15492. hadInlineInitBlock = true;
  15493. }
  15494. }
  15495. UpdateSrcPos(node);
  15496. };
  15497. for (auto fieldDef : typeDef->mFields)
  15498. {
  15499. // For extensions, only handle these fields in the appropriate extension
  15500. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  15501. continue;
  15502. if ((!fieldDef->mIsConst) && (!fieldDef->mIsStatic))
  15503. {
  15504. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  15505. if (!fieldInst->mFieldIncluded)
  15506. continue;
  15507. if (fieldInst->mDataIdx < 0)
  15508. continue;
  15509. auto initializer = fieldDef->GetInitializer();
  15510. if (fieldInst->IsAppendedObject())
  15511. {
  15512. UpdateSrcPos(fieldDef->GetNameNode());
  15513. AppendedObjectInit(fieldInst);
  15514. continue;
  15515. }
  15516. if (initializer == NULL)
  15517. {
  15518. continue;
  15519. // if (fieldDef->mProtection != BfProtection_Hidden)
  15520. // continue;
  15521. // if (mCurTypeInstance->IsObject()) // Already zeroed out
  15522. // continue;
  15523. }
  15524. if (fieldInst->mResolvedType == NULL)
  15525. {
  15526. BF_ASSERT(mHadBuildError);
  15527. continue;
  15528. }
  15529. if (initializer != NULL)
  15530. {
  15531. _CheckInitBlock(initializer);
  15532. }
  15533. BfIRValue fieldAddr;
  15534. if ((!mCurTypeInstance->IsTypedPrimitive()) && (!fieldInst->mResolvedType->IsVar()))
  15535. {
  15536. fieldAddr = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, fieldInst->mDataIdx /*, fieldDef->mName*/);
  15537. }
  15538. else
  15539. {
  15540. // Failed
  15541. }
  15542. auto assignValue = GetFieldInitializerValue(fieldInst);
  15543. if (mCurTypeInstance->IsUnion())
  15544. {
  15545. auto fieldPtrType = CreatePointerType(fieldInst->mResolvedType);
  15546. fieldAddr = mBfIRBuilder->CreateBitCast(fieldAddr, mBfIRBuilder->MapType(fieldPtrType));
  15547. }
  15548. if ((fieldAddr) && (assignValue))
  15549. mBfIRBuilder->CreateAlignedStore(assignValue.mValue, fieldAddr, fieldInst->mResolvedType->mAlign);
  15550. }
  15551. }
  15552. EmitInitBlocks(_CheckInitBlock);
  15553. if (hadInlineInitBlock)
  15554. {
  15555. RestoreScopeState();
  15556. // This gets set to false because of AddScope but we actually are still in the head block
  15557. mCurMethodState->mInHeadScope = true;
  15558. // Make sure we emit a return even if we had a NoReturn call or return inside ourselves
  15559. mCurMethodState->mHadReturn = false;
  15560. mCurMethodState->mLeftBlockUncond = false;
  15561. }
  15562. }
  15563. else // Autocomplete case
  15564. {
  15565. BfScopeData scopeData;
  15566. scopeData.mInInitBlock = true;
  15567. mCurMethodState->AddScope(&scopeData);
  15568. NewScopeState();
  15569. // The reason we can't just do the 'normal' path for this is that the BfTypeInstance here is NOT the
  15570. // autocomplete type instance, so FieldInstance initializer values contain expressions from the full
  15571. // resolve pass, NOT the autocomplete expression
  15572. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  15573. {
  15574. if (tempTypeDef->mFullName == typeDef->mFullName)
  15575. {
  15576. for (auto fieldDef : tempTypeDef->mFields)
  15577. {
  15578. auto initializer = fieldDef->GetInitializer();
  15579. if ((!fieldDef->mIsStatic) && (initializer != NULL) && (mCompiler->mResolvePassData->mIsClassifying))
  15580. {
  15581. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(initializer))
  15582. {
  15583. sourceClassifier->SetElementType(initializer, BfSourceElementType_Normal);
  15584. sourceClassifier->VisitChild(initializer);
  15585. }
  15586. BfType* wantType = NULL;
  15587. if ((!BfNodeIsA<BfVarTypeReference>(fieldDef->mTypeRef)) &&
  15588. (!BfNodeIsA<BfLetTypeReference>(fieldDef->mTypeRef)))
  15589. wantType = ResolveTypeRef(fieldDef->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_AllowInferredSizedArray);
  15590. if ((wantType != NULL) &&
  15591. ((wantType->IsVar()) || (wantType->IsLet()) || (wantType->IsRef())))
  15592. wantType = NULL;
  15593. BfEvalExprFlags exprFlags = BfEvalExprFlags_FieldInitializer;
  15594. if (fieldDef->mIsAppend)
  15595. exprFlags = (BfEvalExprFlags)(exprFlags | BfEvalExprFlags_AppendFieldInitializer);
  15596. CreateValueFromExpression(initializer, wantType, exprFlags);
  15597. }
  15598. }
  15599. tempTypeDef->PopulateMemberSets();
  15600. BfMemberSetEntry* entry = NULL;
  15601. BfMethodDef* initMethodDef = NULL;
  15602. tempTypeDef->mMethodSet.TryGetWith(String("__BfInit"), &entry);
  15603. if (entry != NULL)
  15604. initMethodDef = (BfMethodDef*)entry->mMemberDef;
  15605. SizedArray<BfAstNode*, 8> initBodies;
  15606. for (; initMethodDef != NULL; initMethodDef = initMethodDef->mNextWithSameName)
  15607. {
  15608. if (initMethodDef->mMethodType != BfMethodType_Init)
  15609. continue;
  15610. initBodies.Insert(0, initMethodDef->mBody);
  15611. }
  15612. for (auto body : initBodies)
  15613. VisitEmbeddedStatement(body);
  15614. }
  15615. }
  15616. // Mark fields from full type with initializers as initialized, to give proper initialization errors within ctor
  15617. for (auto fieldDef : typeDef->mFields)
  15618. {
  15619. if ((!fieldDef->mIsConst) && (!fieldDef->mIsStatic) && (fieldDef->GetInitializer() != NULL))
  15620. {
  15621. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  15622. if (fieldDef->GetInitializer() != NULL)
  15623. MarkFieldInitialized(fieldInst);
  15624. }
  15625. }
  15626. RestoreScopeState();
  15627. }
  15628. }
  15629. if (!methodInstance->mIsAutocompleteMethod)
  15630. {
  15631. if (auto autoDecl = BfNodeDynCast<BfAutoConstructorDeclaration>(methodDeclaration))
  15632. {
  15633. BfExprEvaluator exprEvaluator(this);
  15634. for (int paramIdx = 0; paramIdx < methodDef->mParams.mSize; paramIdx++)
  15635. {
  15636. auto paramDef = methodDef->mParams[paramIdx];
  15637. auto& fieldInstance = mCurTypeInstance->mFieldInstances[paramIdx];
  15638. BF_ASSERT(paramDef->mName == fieldInstance.GetFieldDef()->mName);
  15639. if (fieldInstance.mDataIdx < 0)
  15640. continue;
  15641. if (paramDef->mParamKind != BfParamKind_Normal)
  15642. continue;
  15643. auto localVar = mCurMethodState->mLocals[paramIdx + 1];
  15644. BF_ASSERT(localVar->mName == paramDef->mName);
  15645. auto localVal = exprEvaluator.LoadLocal(localVar);
  15646. localVal = LoadOrAggregateValue(localVal);
  15647. if (!localVal.mType->IsVar())
  15648. {
  15649. auto thisVal = GetThis();
  15650. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(thisVal.mValue, 0, fieldInstance.mDataIdx);
  15651. mBfIRBuilder->CreateAlignedStore(localVal.mValue, fieldPtr, localVar->mResolvedType->mAlign);
  15652. }
  15653. MarkFieldInitialized(&fieldInstance);
  15654. }
  15655. }
  15656. }
  15657. // Call base ctor (if applicable)
  15658. BfTypeInstance* targetType = NULL;
  15659. BfAstNode* targetRefNode = NULL;
  15660. if (ctorDeclaration != NULL)
  15661. targetRefNode = ctorDeclaration->mInitializer;
  15662. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(targetRefNode))
  15663. targetRefNode = invocationExpr->mTarget;
  15664. if (baseCtorNode != NULL)
  15665. {
  15666. UpdateSrcPos(baseCtorNode);
  15667. if (methodDef->mBody == NULL)
  15668. SetIllegalSrcPos();
  15669. }
  15670. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL))
  15671. {
  15672. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorInvocation->mTarget);
  15673. targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  15674. }
  15675. else if ((mCurTypeInstance->mBaseType != NULL) && (!mCurTypeInstance->IsUnspecializedType()) && (methodDef->mMethodType != BfMethodType_CtorNoBody))
  15676. {
  15677. auto baseType = mCurTypeInstance->mBaseType;
  15678. if ((!mCurTypeInstance->IsTypedPrimitive()) &&
  15679. ((baseType->mTypeDef != mCompiler->mValueTypeTypeDef) || (!mContext->mCanSkipValueTypeCtor)) &&
  15680. ((baseType->mTypeDef != mCompiler->mBfObjectTypeDef) || (!mContext->mCanSkipObjectCtor)))
  15681. {
  15682. // Try to find a ctor without any params first
  15683. BfMethodDef* matchedMethod = NULL;
  15684. bool hadCtorWithAllDefaults = false;
  15685. bool isHiddenGenerated = (methodDeclaration == NULL) && (methodDef->mProtection == BfProtection_Hidden);
  15686. for (int pass = 0; pass < 2; pass++)
  15687. {
  15688. baseType->mTypeDef->PopulateMemberSets();
  15689. BfMemberSetEntry* entry = NULL;
  15690. BfMethodDef* checkMethodDef = NULL;
  15691. baseType->mTypeDef->mMethodSet.TryGetWith(String("__BfCtor"), &entry);
  15692. if (entry != NULL)
  15693. checkMethodDef = (BfMethodDef*)entry->mMemberDef;
  15694. while (checkMethodDef != NULL)
  15695. {
  15696. bool allowMethod = checkMethodDef->mProtection > BfProtection_Private;
  15697. if (isHiddenGenerated)
  15698. {
  15699. // Allow calling of the default base ctor if it is implicitly defined
  15700. if ((checkMethodDef->mMethodDeclaration == NULL) && (pass == 1) && (!hadCtorWithAllDefaults))
  15701. allowMethod = true;
  15702. }
  15703. if ((checkMethodDef->mMethodType == BfMethodType_Ctor) && (!checkMethodDef->mIsStatic) && (allowMethod))
  15704. {
  15705. if (checkMethodDef->mParams.size() == 0)
  15706. {
  15707. if (matchedMethod != NULL)
  15708. {
  15709. // Has multiple matched methods - can happen from extensions
  15710. matchedMethod = NULL;
  15711. break;
  15712. }
  15713. matchedMethod = checkMethodDef;
  15714. }
  15715. else if (isHiddenGenerated)
  15716. {
  15717. if ((checkMethodDef->mParams[0]->mParamDeclaration != NULL) && (checkMethodDef->mParams[0]->mParamDeclaration->mInitializer != NULL))
  15718. hadCtorWithAllDefaults = true;
  15719. }
  15720. }
  15721. checkMethodDef = checkMethodDef->mNextWithSameName;
  15722. }
  15723. if (matchedMethod != NULL)
  15724. break;
  15725. }
  15726. if ((HasExecutedOutput()) && (matchedMethod != NULL))
  15727. {
  15728. SizedArray<BfIRValue, 1> args;
  15729. auto ctorBodyMethodInstance = GetMethodInstance(mCurTypeInstance->mBaseType, matchedMethod, BfTypeVector());
  15730. if (!mCurTypeInstance->mBaseType->IsValuelessType())
  15731. {
  15732. auto basePtr = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapTypeInstPtr(mCurTypeInstance->mBaseType));
  15733. args.push_back(basePtr);
  15734. }
  15735. AddCallDependency(ctorBodyMethodInstance.mMethodInstance, true);
  15736. auto callInst = mBfIRBuilder->CreateCall(ctorBodyMethodInstance.mFunc, args);
  15737. auto callingConv = GetIRCallingConvention(ctorBodyMethodInstance.mMethodInstance);
  15738. if (callingConv != BfIRCallingConv_CDecl)
  15739. mBfIRBuilder->SetCallCallingConv(callInst, callingConv);
  15740. if (mIsComptimeModule)
  15741. mCompiler->mCeMachine->QueueMethod(ctorBodyMethodInstance);
  15742. }
  15743. if (matchedMethod == NULL)
  15744. {
  15745. targetType = mCurTypeInstance->mBaseType;
  15746. if (ctorDeclaration != NULL)
  15747. targetRefNode = ctorDeclaration->mThisToken;
  15748. else if (typeDef->mTypeDeclaration != NULL)
  15749. targetRefNode = typeDef->mTypeDeclaration->mNameNode;
  15750. }
  15751. }
  15752. }
  15753. if (methodDef->mHasAppend)
  15754. {
  15755. mCurMethodState->mCurAppendAlign = methodInstance->mAppendAllocAlign;
  15756. }
  15757. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL) && (ctorInvocation->mArguments.size() == 1) && (targetType != NULL))
  15758. {
  15759. if (auto tokenNode = BfNodeDynCast<BfUninitializedExpression>(ctorInvocation->mArguments[0]))
  15760. {
  15761. if (targetType == mCurTypeInstance)
  15762. {
  15763. auto thisVariable = GetThisVariable();
  15764. if (thisVariable != NULL)
  15765. {
  15766. thisVariable->mUnassignedFieldFlags = 0;
  15767. thisVariable->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  15768. }
  15769. }
  15770. targetType = NULL;
  15771. }
  15772. }
  15773. if (targetType != NULL)
  15774. {
  15775. BfAstNode* refNode = methodDeclaration;
  15776. if (refNode == NULL)
  15777. refNode = typeDef->mTypeDeclaration;
  15778. BfAutoParentNodeEntry autoParentNodeEntry(this, refNode);
  15779. auto autoComplete = mCompiler->GetAutoComplete();
  15780. auto wasCapturingMethodInfo = (autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo);
  15781. if ((autoComplete != NULL) && (ctorDeclaration != NULL) && (ctorInvocation != NULL))
  15782. {
  15783. auto invocationExpr = ctorInvocation;
  15784. autoComplete->CheckInvocation(invocationExpr, invocationExpr->mOpenParen, invocationExpr->mCloseParen, invocationExpr->mCommas);
  15785. }
  15786. BfType* targetThisType = targetType;
  15787. auto target = Cast(targetRefNode, GetThis(), targetThisType);
  15788. BfExprEvaluator exprEvaluator(this);
  15789. BfResolvedArgs argValues;
  15790. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL))
  15791. {
  15792. argValues.Init(&ctorInvocation->mArguments);
  15793. if (gDebugStuff)
  15794. {
  15795. OutputDebugStrF("Expr: %@ %d\n", argValues.mArguments->mVals, argValues.mArguments->mSize);
  15796. }
  15797. }
  15798. exprEvaluator.ResolveArgValues(argValues, BfResolveArgsFlag_DeferParamEval);
  15799. BfTypedValue appendIdxVal;
  15800. if (methodDef->mHasAppend)
  15801. {
  15802. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  15803. BF_ASSERT(localVar->mName == "appendIdx");
  15804. auto intRefType = localVar->mResolvedType;
  15805. appendIdxVal = BfTypedValue(localVar->mValue, intRefType);
  15806. mCurMethodState->mCurAppendAlign = 1; // Don't make any assumptions about how the base leaves the alignment
  15807. }
  15808. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, methodDef->mHasAppend, &appendIdxVal);
  15809. if (autoComplete != NULL)
  15810. {
  15811. if ((wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo))
  15812. {
  15813. if (autoComplete->mMethodMatchInfo != NULL)
  15814. autoComplete->mIsCapturingMethodMatchInfo = true;
  15815. else
  15816. autoComplete->mIsCapturingMethodMatchInfo = false;
  15817. }
  15818. else
  15819. autoComplete->mIsCapturingMethodMatchInfo = false;
  15820. }
  15821. }
  15822. }
  15823. void BfModule::EmitEnumToStringBody()
  15824. {
  15825. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  15826. auto strVal = CreateAlloca(stringType);
  15827. auto int64StructType = GetPrimitiveStructType(BfTypeCode_Int64);
  15828. BfExprEvaluator exprEvaluator(this);
  15829. auto stringDestAddr = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  15830. BfIRBlock appendBlock = mBfIRBuilder->CreateBlock("append");
  15831. BfIRBlock noMatchBlock = mBfIRBuilder->CreateBlock("noMatch");
  15832. BfIRBlock endBlock = mBfIRBuilder->CreateBlock("end");
  15833. BfType* discriminatorType = NULL;
  15834. BfTypedValue rawPayload;
  15835. BfIRValue enumVal;
  15836. if (mCurTypeInstance->IsPayloadEnum())
  15837. {
  15838. discriminatorType = mCurTypeInstance->GetDiscriminatorType();
  15839. auto enumTypedValue = ExtractValue(GetThis(), NULL, 2);
  15840. enumTypedValue = LoadValue(enumTypedValue);
  15841. enumVal = enumTypedValue.mValue;
  15842. rawPayload = ExtractValue(GetThis(), NULL, 1);
  15843. }
  15844. else
  15845. enumVal = mBfIRBuilder->GetArgument(0);
  15846. Array<BfType*> paramTypes;
  15847. paramTypes.Add(stringType);
  15848. auto appendModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  15849. auto switchVal = mBfIRBuilder->CreateSwitch(enumVal, noMatchBlock, (int)mCurTypeInstance->mFieldInstances.size());
  15850. HashSet<int64> handledCases;
  15851. for (auto& fieldInstance : mCurTypeInstance->mFieldInstances)
  15852. {
  15853. if (fieldInstance.mIsEnumPayloadCase)
  15854. {
  15855. int tagId = -fieldInstance.mDataIdx - 1;
  15856. BfIRBlock caseBlock = mBfIRBuilder->CreateBlock("case");
  15857. mBfIRBuilder->AddBlock(caseBlock);
  15858. mBfIRBuilder->SetInsertPoint(caseBlock);
  15859. BF_ASSERT(discriminatorType->IsPrimitiveType());
  15860. auto constVal = mBfIRBuilder->CreateConst(((BfPrimitiveType*)discriminatorType)->mTypeDef->mTypeCode, tagId);
  15861. mBfIRBuilder->AddSwitchCase(switchVal, constVal, caseBlock);
  15862. auto caseStr = GetStringObjectValue(fieldInstance.GetFieldDef()->mName);
  15863. auto stringDestVal = LoadValue(stringDestAddr);
  15864. SizedArray<BfIRValue, 2> args;
  15865. args.Add(stringDestVal.mValue);
  15866. args.Add(caseStr);
  15867. exprEvaluator.CreateCall(NULL, appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  15868. auto payloadType = fieldInstance.mResolvedType->ToTypeInstance();
  15869. BF_ASSERT(payloadType->IsTuple());
  15870. if (payloadType->mFieldInstances.size() != 0)
  15871. {
  15872. auto payload = rawPayload;
  15873. if (payload.mType != payloadType)
  15874. {
  15875. payload = Cast(NULL, payload, payloadType, BfCastFlags_Force);
  15876. }
  15877. auto toStringMethod = GetMethodByName(payloadType->ToTypeInstance(), "ToString");
  15878. SizedArray<BfIRValue, 2> irArgs;
  15879. exprEvaluator.PushThis(NULL, payload, toStringMethod.mMethodInstance, irArgs);
  15880. stringDestVal = LoadValue(stringDestAddr);
  15881. irArgs.Add(stringDestVal.mValue);
  15882. exprEvaluator.CreateCall(NULL, toStringMethod.mMethodInstance, toStringMethod.mFunc, true, irArgs);
  15883. }
  15884. mBfIRBuilder->CreateBr(endBlock);
  15885. continue;
  15886. }
  15887. if (fieldInstance.mConstIdx == -1)
  15888. continue;
  15889. // Only allow compact 'ValA, ValB' enum declaration fields through
  15890. auto fieldDef = fieldInstance.GetFieldDef();
  15891. auto fieldDecl = fieldDef->mFieldDeclaration;
  15892. if ((fieldDecl == NULL) || (fieldDef->mTypeRef != NULL))
  15893. continue;
  15894. auto constant = mCurTypeInstance->mConstHolder->GetConstantById(fieldInstance.mConstIdx);
  15895. if (!handledCases.TryAdd(constant->mInt64, NULL))
  15896. {
  15897. // Duplicate
  15898. continue;
  15899. }
  15900. BfIRBlock caseBlock = mBfIRBuilder->CreateBlock("case");
  15901. mBfIRBuilder->AddBlock(caseBlock);
  15902. mBfIRBuilder->SetInsertPoint(caseBlock);
  15903. BfIRValue constVal = ConstantToCurrent(constant, mCurTypeInstance->mConstHolder, mCurTypeInstance);
  15904. mBfIRBuilder->AddSwitchCase(switchVal, constVal, caseBlock);
  15905. auto caseStr = GetStringObjectValue(fieldInstance.GetFieldDef()->mName);
  15906. mBfIRBuilder->CreateStore(caseStr, strVal);
  15907. mBfIRBuilder->CreateBr(appendBlock);
  15908. }
  15909. mBfIRBuilder->AddBlock(appendBlock);
  15910. mBfIRBuilder->SetInsertPoint(appendBlock);
  15911. SizedArray<BfIRValue, 2> args;
  15912. auto stringDestVal = LoadValue(stringDestAddr);
  15913. args.Add(stringDestVal.mValue);
  15914. args.Add(mBfIRBuilder->CreateLoad(strVal));
  15915. exprEvaluator.CreateCall(NULL, appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  15916. mBfIRBuilder->CreateBr(endBlock);
  15917. mBfIRBuilder->AddBlock(noMatchBlock);
  15918. mBfIRBuilder->SetInsertPoint(noMatchBlock);
  15919. auto int64Val = mBfIRBuilder->CreateNumericCast(enumVal, false, BfTypeCode_Int64);
  15920. auto toStringModuleMethodInstance = GetMethodByName(int64StructType, "ToString", 1);
  15921. args.clear();
  15922. args.Add(int64Val);
  15923. stringDestVal = LoadValue(stringDestAddr);
  15924. args.Add(stringDestVal.mValue);
  15925. exprEvaluator.CreateCall(NULL, toStringModuleMethodInstance.mMethodInstance, toStringModuleMethodInstance.mFunc, false, args);
  15926. mBfIRBuilder->CreateBr(endBlock);
  15927. mBfIRBuilder->AddBlock(endBlock);
  15928. mBfIRBuilder->SetInsertPoint(endBlock);
  15929. }
  15930. void BfModule::EmitTupleToStringBody()
  15931. {
  15932. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  15933. BfExprEvaluator exprEvaluator(this);
  15934. auto stringDestRef = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  15935. Array<BfType*> paramTypes;
  15936. paramTypes.Add(GetPrimitiveType(BfTypeCode_Char8));
  15937. auto appendCharModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  15938. paramTypes.Clear();
  15939. paramTypes.Add(stringType);
  15940. auto appendModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  15941. auto _AppendChar = [&](char c)
  15942. {
  15943. SizedArray<BfIRValue, 2> args;
  15944. auto stringDestVal = LoadValue(stringDestRef);
  15945. args.Add(stringDestVal.mValue);
  15946. args.Add(mBfIRBuilder->CreateConst(BfTypeCode_Char8, (int)c));
  15947. exprEvaluator.CreateCall(NULL, appendCharModuleMethodInstance.mMethodInstance, appendCharModuleMethodInstance.mFunc, false, args);
  15948. };
  15949. int fieldIdx = 0;
  15950. auto thisValue = GetThis();
  15951. auto toStringModuleMethodInstance = GetMethodByName(mContext->mBfObjectType, "ToString", 1);
  15952. auto toStringSafeModuleMethodInstance = GetMethodByName(mContext->mBfObjectType, "ToString", 2);
  15953. BfIRValue commaStr;
  15954. auto iPrintableType = ResolveTypeDef(mCompiler->mIPrintableTypeDef)->ToTypeInstance();
  15955. auto printModuleMethodInstance = GetMethodByName(iPrintableType, "Print");
  15956. _AppendChar('(');
  15957. for (auto& fieldInstance : mCurTypeInstance->mFieldInstances)
  15958. {
  15959. if (fieldInstance.mDataIdx == -1)
  15960. continue;
  15961. if (fieldIdx > 0)
  15962. {
  15963. if (!commaStr)
  15964. commaStr = GetStringObjectValue(", ");
  15965. SizedArray<BfIRValue, 2> args;
  15966. auto stringDestVal = LoadValue(stringDestRef);
  15967. args.Add(stringDestVal.mValue);
  15968. args.Add(commaStr);
  15969. exprEvaluator.CreateCall(NULL, appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  15970. }
  15971. fieldIdx++;
  15972. if (fieldInstance.mResolvedType->IsValuelessType())
  15973. continue;
  15974. BfTypedValue fieldValue = ExtractValue(thisValue, &fieldInstance, fieldInstance.mDataIdx);
  15975. if (fieldValue.mType->IsPrimitiveType())
  15976. {
  15977. fieldValue.mType = GetPrimitiveStructType(((BfPrimitiveType*)fieldValue.mType)->mTypeDef->mTypeCode);
  15978. }
  15979. auto typeInstance = fieldValue.mType->ToTypeInstance();
  15980. if ((typeInstance != NULL) && (TypeIsSubTypeOf(typeInstance, iPrintableType, false)))
  15981. {
  15982. BfExprEvaluator exprEvaluator(this);
  15983. SizedArray<BfResolvedArg, 0> resolvedArgs;
  15984. BfMethodMatcher methodMatcher(NULL, this, printModuleMethodInstance.mMethodInstance, resolvedArgs, BfMethodGenericArguments());
  15985. methodMatcher.mBestMethodDef = printModuleMethodInstance.mMethodInstance->mMethodDef;
  15986. methodMatcher.mBestMethodTypeInstance = iPrintableType;
  15987. methodMatcher.TryDevirtualizeCall(fieldValue);
  15988. BfTypedValue callVal = Cast(NULL, fieldValue, methodMatcher.mBestMethodTypeInstance);
  15989. BfResolvedArg resolvedArg;
  15990. auto stringDestVal = LoadValue(stringDestRef);
  15991. resolvedArg.mTypedValue = stringDestVal;
  15992. resolvedArg.mResolvedType = stringDestVal.mType;
  15993. resolvedArgs.Add(resolvedArg);
  15994. exprEvaluator.CreateCall(&methodMatcher, callVal);
  15995. continue;
  15996. }
  15997. if (fieldValue.mType->IsObjectOrInterface())
  15998. {
  15999. fieldValue = LoadValue(fieldValue);
  16000. BF_ASSERT(!fieldValue.IsAddr());
  16001. SizedArray<BfIRValue, 2> args;
  16002. args.Add(mBfIRBuilder->CreateBitCast(fieldValue.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType)));
  16003. auto stringDestVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  16004. stringDestVal = LoadValue(stringDestVal);
  16005. args.Add(stringDestVal.mValue);
  16006. exprEvaluator.CreateCall(NULL, toStringSafeModuleMethodInstance.mMethodInstance, toStringSafeModuleMethodInstance.mFunc, false, args);
  16007. continue;
  16008. }
  16009. BfExprEvaluator exprEvaluator(this);
  16010. SizedArray<BfResolvedArg, 0> resolvedArgs;
  16011. BfMethodMatcher methodMatcher(NULL, this, toStringModuleMethodInstance.mMethodInstance, resolvedArgs, BfMethodGenericArguments());
  16012. methodMatcher.mBestMethodDef = toStringModuleMethodInstance.mMethodInstance->mMethodDef;
  16013. methodMatcher.mBestMethodTypeInstance = mContext->mBfObjectType;
  16014. methodMatcher.TryDevirtualizeCall(fieldValue);
  16015. if (methodMatcher.mBestMethodTypeInstance == mContext->mBfObjectType)
  16016. {
  16017. AddCallDependency(appendModuleMethodInstance.mMethodInstance);
  16018. AddDependency(fieldValue.mType, mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  16019. // Just append the type name
  16020. String typeName = TypeToString(fieldInstance.mResolvedType);
  16021. auto strVal = GetStringObjectValue(typeName);
  16022. SizedArray<BfIRValue, 2> args;
  16023. auto stringDestVal = LoadValue(stringDestRef);
  16024. args.Add(stringDestVal.mValue);
  16025. args.Add(strVal);
  16026. exprEvaluator.CreateCall(NULL, appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  16027. continue;
  16028. }
  16029. BfTypedValue callVal = Cast(NULL, fieldValue, methodMatcher.mBestMethodTypeInstance);
  16030. BfResolvedArg resolvedArg;
  16031. auto stringDestVal = LoadValue(stringDestRef);
  16032. resolvedArg.mTypedValue = stringDestVal;
  16033. resolvedArg.mResolvedType = stringDestVal.mType;
  16034. resolvedArgs.Add(resolvedArg);
  16035. exprEvaluator.CreateCall(&methodMatcher, callVal);
  16036. }
  16037. _AppendChar(')');
  16038. }
  16039. void BfModule::EmitIteratorBlock(bool& skipBody)
  16040. {
  16041. auto methodInstance = mCurMethodInstance;
  16042. auto methodDef = methodInstance->mMethodDef;
  16043. auto methodDeclaration = methodDef->GetMethodDeclaration();
  16044. auto typeDef = mCurTypeInstance->mTypeDef;
  16045. BfType* innerRetType = NULL;
  16046. BfTypeInstance* usingInterface = NULL;
  16047. auto retTypeInst = mCurMethodInstance->mReturnType->ToGenericTypeInstance();
  16048. if (retTypeInst != NULL)
  16049. {
  16050. if ((retTypeInst->IsInstanceOf(mCompiler->mGenericIEnumerableTypeDef)) ||
  16051. (retTypeInst->IsInstanceOf(mCompiler->mGenericIEnumeratorTypeDef)))
  16052. {
  16053. innerRetType = retTypeInst->mGenericTypeInfo->mTypeGenericArguments[0];
  16054. }
  16055. }
  16056. if (innerRetType == NULL)
  16057. {
  16058. Fail("Methods with yields must return either System.IEnumerable<T> or System.IEnumerator<T>", methodDeclaration->mReturnType);
  16059. return;
  16060. }
  16061. auto blockBody = BfNodeDynCast<BfBlock>(methodDeclaration->mBody);
  16062. if (blockBody == NULL)
  16063. return;
  16064. }
  16065. void BfModule::EmitGCMarkAppended(BfTypedValue markVal)
  16066. {
  16067. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef, BfPopulateType_DataAndMethods);
  16068. if (gcType == NULL)
  16069. return;
  16070. BfModuleMethodInstance markFromGCThreadMethodInstance = GetMethodByName(gcType->ToTypeInstance(), "MarkAppendedObject", 1);
  16071. if (!markFromGCThreadMethodInstance)
  16072. return;
  16073. SizedArray<BfIRValue, 1> args;
  16074. args.push_back(mBfIRBuilder->CreateBitCast(markVal.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType)));
  16075. BfExprEvaluator exprEvaluator(this);
  16076. exprEvaluator.CreateCall(NULL, markFromGCThreadMethodInstance.mMethodInstance, markFromGCThreadMethodInstance.mFunc, false, args);
  16077. }
  16078. void BfModule::EmitGCMarkValue(BfTypedValue markVal, BfModuleMethodInstance markFromGCThreadMethodInstance)
  16079. {
  16080. auto fieldType = markVal.mType;
  16081. auto fieldTypeInst = fieldType->ToTypeInstance();
  16082. if (fieldType == NULL)
  16083. return;
  16084. if (!markVal.mType->IsComposite())
  16085. markVal = LoadValue(markVal);
  16086. BfExprEvaluator exprEvaluator(this);
  16087. PopulateType(markVal.mType, BfPopulateType_Data);
  16088. if (markVal.mType->IsObjectOrInterface())
  16089. {
  16090. BfIRValue val = markVal.mValue;
  16091. val = mBfIRBuilder->CreateBitCast(val, mBfIRBuilder->MapType(mContext->mBfObjectType));
  16092. SizedArray<BfIRValue, 1> args;
  16093. args.push_back(val);
  16094. exprEvaluator.CreateCall(NULL, markFromGCThreadMethodInstance.mMethodInstance, markFromGCThreadMethodInstance.mFunc, false, args);
  16095. }
  16096. else if (fieldType->IsSizedArray())
  16097. {
  16098. BfSizedArrayType* sizedArrayType = (BfSizedArrayType*)fieldType;
  16099. if (sizedArrayType->mElementType->WantsGCMarking())
  16100. {
  16101. BfTypedValue arrayValue = markVal;
  16102. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  16103. auto itr = CreateAlloca(intPtrType);
  16104. mBfIRBuilder->CreateStore(GetDefaultValue(intPtrType), itr);
  16105. auto loopBB = mBfIRBuilder->CreateBlock("loop", true);
  16106. auto bodyBB = mBfIRBuilder->CreateBlock("body", true);
  16107. auto doneBB = mBfIRBuilder->CreateBlock("done", true);
  16108. mBfIRBuilder->CreateBr(loopBB);
  16109. mBfIRBuilder->SetInsertPoint(loopBB);
  16110. auto loadedItr = mBfIRBuilder->CreateLoad(itr);
  16111. auto cmpRes = mBfIRBuilder->CreateCmpGTE(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)sizedArrayType->mElementCount), true);
  16112. mBfIRBuilder->CreateCondBr(cmpRes, doneBB, bodyBB);
  16113. mBfIRBuilder->SetInsertPoint(bodyBB);
  16114. auto ptrType = CreatePointerType(sizedArrayType->mElementType);
  16115. auto ptrValue = mBfIRBuilder->CreateBitCast(arrayValue.mValue, mBfIRBuilder->MapType(ptrType));
  16116. auto gepResult = mBfIRBuilder->CreateInBoundsGEP(ptrValue, loadedItr);
  16117. auto value = BfTypedValue(gepResult, sizedArrayType->mElementType, BfTypedValueKind_Addr);
  16118. EmitGCMarkValue(value, markFromGCThreadMethodInstance);
  16119. auto incValue = mBfIRBuilder->CreateAdd(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  16120. mBfIRBuilder->CreateStore(incValue, itr);
  16121. mBfIRBuilder->CreateBr(loopBB);
  16122. mBfIRBuilder->SetInsertPoint(doneBB);
  16123. }
  16124. }
  16125. else if ((fieldType->IsComposite()) && (!fieldType->IsTypedPrimitive()) && (fieldTypeInst != NULL))
  16126. {
  16127. auto markMemberMethodInstance = GetMethodByName(fieldTypeInst, BF_METHODNAME_MARKMEMBERS, 0, true);
  16128. if (markMemberMethodInstance)
  16129. {
  16130. SizedArray<BfIRValue, 1> args;
  16131. auto methodOwner = markMemberMethodInstance.mMethodInstance->GetOwner();
  16132. if (markVal.mType != methodOwner)
  16133. markVal = Cast(NULL, markVal, methodOwner);
  16134. exprEvaluator.PushThis(NULL, markVal, markMemberMethodInstance.mMethodInstance, args);
  16135. exprEvaluator.CreateCall(NULL, markMemberMethodInstance.mMethodInstance, markMemberMethodInstance.mFunc, false, args);
  16136. }
  16137. }
  16138. }
  16139. void BfModule::CallChainedMethods(BfMethodInstance* methodInstance, bool reverse)
  16140. {
  16141. Array<BfMethodInstance*> methodInstances;
  16142. for (int methodIdx = 0; methodIdx < (int)mCurTypeInstance->mMethodInstanceGroups.size(); methodIdx++)
  16143. {
  16144. auto& methodInstGroup = mCurTypeInstance->mMethodInstanceGroups[methodIdx];
  16145. auto chainedMethodInst = methodInstGroup.mDefault;
  16146. if ((chainedMethodInst != NULL) && (chainedMethodInst->mChainType == BfMethodChainType_ChainMember))
  16147. {
  16148. if ((chainedMethodInst->mMethodDef->mIsStatic == methodInstance->mMethodDef->mIsStatic) &&
  16149. (CompareMethodSignatures(methodInstance, chainedMethodInst)))
  16150. {
  16151. methodInstances.push_back(chainedMethodInst);
  16152. }
  16153. }
  16154. }
  16155. std::stable_sort(methodInstances.begin(), methodInstances.end(),
  16156. [&](BfMethodInstance* lhs, BfMethodInstance* rhs)
  16157. {
  16158. bool isBetter;
  16159. bool isWorse;
  16160. CompareDeclTypes(lhs->mMethodDef->mDeclaringType, rhs->mMethodDef->mDeclaringType, isBetter, isWorse);
  16161. if (isBetter == isWorse)
  16162. {
  16163. return false;
  16164. }
  16165. return isWorse;
  16166. });
  16167. if (reverse)
  16168. std::reverse(methodInstances.begin(), methodInstances.end());
  16169. for (auto chainedMethodInst : methodInstances)
  16170. {
  16171. auto declModule = this;
  16172. BfGetMethodInstanceFlags flags = BfGetMethodInstanceFlag_None;
  16173. auto moduleMethodInst = declModule->GetMethodInstance(mCurTypeInstance, chainedMethodInst->mMethodDef, BfTypeVector(), flags);
  16174. BfExprEvaluator exprEvaluator(this);
  16175. SizedArray<BfIRValue, 1> args;
  16176. exprEvaluator.PushThis(chainedMethodInst->mMethodDef->GetRefNode(), GetThis(), chainedMethodInst, args);
  16177. exprEvaluator.CreateCall(NULL, moduleMethodInst.mMethodInstance, moduleMethodInst.mFunc, true, args);
  16178. }
  16179. }
  16180. void BfModule::AddHotDataReferences(BfHotDataReferenceBuilder* builder)
  16181. {
  16182. BF_ASSERT(mCurMethodInstance->mIsReified);
  16183. if (mCurTypeInstance->mHotTypeData == NULL)
  16184. {
  16185. mCurTypeInstance->mHotTypeData = new BfHotTypeData();
  16186. BfLogSysM("Created HotTypeData %p created for type %p in AddHotDataReferences\n", mCurTypeInstance->mHotTypeData, mCurTypeInstance);
  16187. }
  16188. auto hotMethod = mCurMethodInstance->mHotMethod;
  16189. for (auto depData : hotMethod->mReferences)
  16190. {
  16191. // Only virtual decls are allowed to already be there
  16192. BF_ASSERT((depData->mDataKind == BfHotDepDataKind_VirtualDecl) || (depData->mDataKind == BfHotDepDataKind_DupMethod));
  16193. }
  16194. BF_ASSERT(hotMethod->mSrcTypeVersion != NULL);
  16195. int prevSize = (int)hotMethod->mReferences.size();
  16196. int refCount = (int)(prevSize + builder->mUsedData.size() + builder->mCalledMethods.size() + builder->mDevirtualizedCalledMethods.size());
  16197. if (!mCurMethodInstance->mMethodDef->mIsStatic)
  16198. refCount++;
  16199. hotMethod->mReferences.Reserve(refCount);
  16200. if (!mCurMethodInstance->mMethodDef->mIsStatic)
  16201. {
  16202. auto hotThis = mCompiler->mHotData->GetThisType(mCurMethodInstance->GetOwner()->mHotTypeData->GetLatestVersion());
  16203. hotThis->mRefCount++;
  16204. hotMethod->mReferences.Insert(0, hotThis);
  16205. prevSize++;
  16206. }
  16207. for (auto val : builder->mAllocatedData)
  16208. {
  16209. auto hotAllocation = mCompiler->mHotData->GetAllocation(val);
  16210. hotMethod->mReferences.Add(hotAllocation);
  16211. }
  16212. for (auto val : builder->mUsedData)
  16213. hotMethod->mReferences.Add(val);
  16214. for (auto val : builder->mCalledMethods)
  16215. hotMethod->mReferences.Add(val);
  16216. for (auto val : builder->mDevirtualizedCalledMethods)
  16217. {
  16218. auto devirtualizedMethod = mCompiler->mHotData->GetDevirtualizedMethod(val);
  16219. hotMethod->mReferences.Add(devirtualizedMethod);
  16220. }
  16221. for (auto val : builder->mFunctionPtrs)
  16222. {
  16223. auto funcRef = mCompiler->mHotData->GetFunctionReference(val);
  16224. hotMethod->mReferences.Add(funcRef);
  16225. }
  16226. for (auto val : builder->mInnerMethods)
  16227. {
  16228. auto innerMethod = mCompiler->mHotData->GetInnerMethod(val);
  16229. hotMethod->mReferences.Add(innerMethod);
  16230. }
  16231. for (int refIdx = prevSize; refIdx < (int)hotMethod->mReferences.size(); refIdx++)
  16232. {
  16233. auto depData = hotMethod->mReferences[refIdx];
  16234. BF_ASSERT(depData != NULL);
  16235. depData->mRefCount++;
  16236. }
  16237. }
  16238. void BfModule::ProcessMethod_SetupParams(BfMethodInstance* methodInstance, BfType* thisType, bool wantsDIData, SizedArrayImpl<BfIRMDNode>* diParams)
  16239. {
  16240. auto methodDef = methodInstance->mMethodDef;
  16241. auto methodDeclaration = methodDef->mMethodDeclaration;
  16242. bool isThisStruct = false;
  16243. if (thisType != NULL)
  16244. isThisStruct = thisType->IsStruct() && !thisType->IsTypedPrimitive();
  16245. int argIdx = 0;
  16246. if ((!mIsComptimeModule) && (argIdx == methodInstance->GetStructRetIdx()))
  16247. argIdx++;
  16248. auto rootMethodState = mCurMethodState->GetRootMethodState();
  16249. if (!methodDef->mIsStatic)
  16250. {
  16251. BfTypeCode loweredTypeCode = BfTypeCode_None;
  16252. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  16253. BfLocalVariable* paramVar = rootMethodState->mBumpAlloc.Alloc<BfLocalVariable>();
  16254. paramVar->mIsBumpAlloc = true;
  16255. paramVar->mResolvedType = thisType;
  16256. paramVar->mName.Reference("this");
  16257. if (!thisType->IsValuelessType())
  16258. paramVar->mValue = mBfIRBuilder->GetArgument(argIdx);
  16259. else
  16260. paramVar->mValue = mBfIRBuilder->GetFakeVal();
  16261. if ((!mIsComptimeModule) && (thisType->IsSplattable()) && (methodInstance->AllowsSplatting(-1)))
  16262. {
  16263. if (!thisType->IsTypedPrimitive())
  16264. paramVar->mIsSplat = true;
  16265. }
  16266. else if ((!mIsComptimeModule) && (!methodDef->mIsMutating) && (methodInstance->mCallingConvention == BfCallingConvention_Unspecified))
  16267. paramVar->mIsLowered = thisType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2) != BfTypeCode_None;
  16268. auto thisTypeInst = thisType->ToTypeInstance();
  16269. paramVar->mIsStruct = isThisStruct;
  16270. paramVar->mAddr = BfIRValue();
  16271. paramVar->mIsThis = true;
  16272. paramVar->mParamIdx = -1;
  16273. if ((methodDef->mMethodType == BfMethodType_Ctor) && (mCurTypeInstance->IsStruct()))
  16274. {
  16275. paramVar->mAssignedKind = BfLocalVarAssignKind_None;
  16276. }
  16277. else
  16278. {
  16279. paramVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  16280. }
  16281. paramVar->mReadFromId = -1;
  16282. paramVar->Init();
  16283. if (methodDeclaration == NULL)
  16284. UseDefaultSrcPos();
  16285. AddLocalVariableDef(paramVar);
  16286. if (!thisType->IsValuelessType())
  16287. {
  16288. if (wantsDIData)
  16289. {
  16290. BfType* thisPtrType = thisType;
  16291. auto diType = mBfIRBuilder->DbgGetType(thisPtrType);
  16292. if (!thisType->IsValueType())
  16293. diType = mBfIRBuilder->DbgCreateArtificialType(diType);
  16294. else if (!paramVar->mIsSplat)
  16295. diType = mBfIRBuilder->DbgCreatePointerType(diType);
  16296. diParams->push_back(diType);
  16297. }
  16298. if (paramVar->mIsSplat)
  16299. {
  16300. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  16301. }
  16302. else
  16303. {
  16304. argIdx++;
  16305. if (loweredTypeCode2 != BfTypeCode_None)
  16306. argIdx++;
  16307. }
  16308. }
  16309. }
  16310. if ((!mIsComptimeModule) && (argIdx == methodInstance->GetStructRetIdx()))
  16311. argIdx++;
  16312. bool hadParams = false;
  16313. bool hasDefault = false;
  16314. int compositeVariableIdx = -1;
  16315. int paramIdx = 0;
  16316. for (paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  16317. {
  16318. // We already issues a type error for this param if we had one in declaration processing
  16319. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  16320. BfLocalVariable* paramVar = rootMethodState->mBumpAlloc.Alloc<BfLocalVariable>();
  16321. paramVar->mIsBumpAlloc = true;
  16322. BfTypeCode loweredTypeCode = BfTypeCode_None;
  16323. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  16324. bool isParamSkipped = methodInstance->IsParamSkipped(paramIdx);
  16325. auto resolvedType = methodInstance->GetParamType(paramIdx);
  16326. if (resolvedType == NULL)
  16327. {
  16328. AssertErrorState();
  16329. paramVar->mParamFailed = true;
  16330. }
  16331. prevIgnoreErrors.Restore();
  16332. PopulateType(resolvedType, BfPopulateType_Declaration);
  16333. paramVar->mResolvedType = resolvedType;
  16334. int namePrefixCount = 0;
  16335. methodInstance->GetParamName(paramIdx, paramVar->mName, namePrefixCount);
  16336. paramVar->mNamePrefixCount = (uint8)namePrefixCount;
  16337. paramVar->mNameNode = methodInstance->GetParamNameNode(paramIdx);
  16338. if (!isParamSkipped)
  16339. {
  16340. paramVar->mValue = mBfIRBuilder->GetArgument(argIdx);
  16341. if (resolvedType->IsMethodRef())
  16342. {
  16343. paramVar->mIsSplat = true;
  16344. }
  16345. else if ((!mIsComptimeModule) && (resolvedType->IsComposite()) && (resolvedType->IsSplattable()))
  16346. {
  16347. if (methodInstance->AllowsSplatting(paramIdx))
  16348. {
  16349. auto resolveTypeInst = resolvedType->ToTypeInstance();
  16350. if ((resolveTypeInst != NULL) && (resolveTypeInst->mIsCRepr))
  16351. paramVar->mIsSplat = true;
  16352. else
  16353. {
  16354. int splatCount = resolvedType->GetSplatCount();
  16355. if (argIdx + splatCount <= mCompiler->mOptions.mMaxSplatRegs)
  16356. paramVar->mIsSplat = true;
  16357. }
  16358. }
  16359. }
  16360. }
  16361. else
  16362. {
  16363. paramVar->mIsSplat = true; // Treat skipped (valueless) as a splat
  16364. paramVar->mValue = mBfIRBuilder->GetFakeVal();
  16365. }
  16366. paramVar->mIsLowered = (!mIsComptimeModule) && resolvedType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2) != BfTypeCode_None;
  16367. paramVar->mIsStruct = resolvedType->IsComposite() && !resolvedType->IsTypedPrimitive();
  16368. paramVar->mParamIdx = paramIdx;
  16369. paramVar->mIsImplicitParam = methodInstance->IsImplicitCapture(paramIdx);
  16370. paramVar->mReadFromId = 0;
  16371. if (resolvedType->IsRef())
  16372. {
  16373. auto refType = (BfRefType*)resolvedType;
  16374. paramVar->mAssignedKind = (refType->mRefKind != BfRefType::RefKind_Out) ? BfLocalVarAssignKind_Unconditional : BfLocalVarAssignKind_None;
  16375. if (refType->mRefKind == BfRefType::RefKind_In)
  16376. {
  16377. paramVar->mIsReadOnly = true;
  16378. }
  16379. }
  16380. else
  16381. {
  16382. paramVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  16383. if (methodDef->mMethodType != BfMethodType_Mixin)
  16384. paramVar->mIsReadOnly = true;
  16385. }
  16386. if (paramVar->mResolvedType->IsGenericParam())
  16387. {
  16388. auto genericParamInst = GetGenericParamInstance((BfGenericParamType*)paramVar->mResolvedType);
  16389. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  16390. {
  16391. auto typedVal = GetDefaultTypedValue(genericParamInst->mTypeConstraint, false, BfDefaultValueKind_Undef);
  16392. paramVar->mResolvedType = typedVal.mType;
  16393. paramVar->mConstValue = typedVal.mValue;
  16394. }
  16395. }
  16396. if (paramVar->mResolvedType->IsConstExprValue())
  16397. {
  16398. BfConstExprValueType* constExprValueType = (BfConstExprValueType*)paramVar->mResolvedType;
  16399. auto unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance);
  16400. auto unspecParamType = unspecializedMethodInstance->GetParamType(paramIdx);
  16401. BF_ASSERT(unspecParamType->IsGenericParam());
  16402. if (unspecParamType->IsGenericParam())
  16403. {
  16404. BfGenericParamType* genericParamType = (BfGenericParamType*)unspecParamType;
  16405. if (genericParamType->mGenericParamKind == BfGenericParamKind_Method)
  16406. {
  16407. auto genericParamInst = unspecializedMethodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  16408. if (genericParamInst->mTypeConstraint != NULL)
  16409. {
  16410. BfExprEvaluator exprEvaluator(this);
  16411. exprEvaluator.mExpectingType = genericParamInst->mTypeConstraint;
  16412. exprEvaluator.GetLiteral(NULL, constExprValueType->mValue);
  16413. auto checkType = genericParamInst->mTypeConstraint;
  16414. if (checkType->IsTypedPrimitive())
  16415. checkType = checkType->GetUnderlyingType();
  16416. auto typedVal = exprEvaluator.mResult;
  16417. if ((typedVal) && (typedVal.mType != checkType))
  16418. typedVal = Cast(NULL, typedVal, checkType, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_SilentFail));
  16419. if ((typedVal.mType == checkType) && (typedVal.mValue.IsConst()))
  16420. {
  16421. paramVar->mResolvedType = genericParamInst->mTypeConstraint;
  16422. paramVar->mConstValue = typedVal.mValue;
  16423. BF_ASSERT(paramVar->mConstValue.IsConst());
  16424. paramVar->mIsConst = true;
  16425. }
  16426. else
  16427. {
  16428. AssertErrorState();
  16429. paramVar->mResolvedType = genericParamInst->mTypeConstraint;
  16430. paramVar->mConstValue = GetDefaultValue(genericParamInst->mTypeConstraint);
  16431. paramVar->mIsConst = true;
  16432. }
  16433. if (paramVar->mResolvedType->IsObject())
  16434. {
  16435. BfTypedValue typedVal(paramVar->mConstValue, paramVar->mResolvedType);
  16436. FixValueActualization(typedVal);
  16437. if (typedVal.mValue.IsConst())
  16438. paramVar->mConstValue = typedVal.mValue;
  16439. }
  16440. }
  16441. }
  16442. }
  16443. //BF_ASSERT(!paramVar->mResolvedType->IsConstExprValue());
  16444. if (paramVar->mResolvedType->IsConstExprValue())
  16445. {
  16446. Fail("Invalid use of constant expression", methodInstance->GetParamTypeRef(paramIdx));
  16447. //AssertErrorState();
  16448. paramVar->mResolvedType = GetPrimitiveType(BfTypeCode_IntPtr);
  16449. paramVar->mConstValue = GetDefaultValue(paramVar->mResolvedType);
  16450. paramVar->mIsConst = true;
  16451. }
  16452. }
  16453. if (methodInstance->GetParamKind(paramIdx) == BfParamKind_DelegateParam)
  16454. {
  16455. if (compositeVariableIdx == -1)
  16456. {
  16457. compositeVariableIdx = (int)mCurMethodState->mLocals.size();
  16458. BfLocalVariable* localVar = new BfLocalVariable();
  16459. auto paramInst = &methodInstance->mParams[paramIdx];
  16460. auto paramDef = methodDef->mParams[paramInst->mParamDefIdx];
  16461. localVar->mName = paramDef->mName;
  16462. localVar->mNamePrefixCount = paramDef->mNamePrefixCount;
  16463. localVar->mResolvedType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_NoResolveGenericParam);
  16464. localVar->mCompositeCount = 0;
  16465. DoAddLocalVariable(localVar);
  16466. }
  16467. mCurMethodState->mLocals[compositeVariableIdx]->mCompositeCount++;
  16468. paramVar->mIsImplicitParam = true;
  16469. }
  16470. if (!mCurTypeInstance->IsDelegateOrFunction())
  16471. CheckVariableDef(paramVar);
  16472. paramVar->Init();
  16473. AddLocalVariableDef(paramVar);
  16474. if (!isParamSkipped)
  16475. {
  16476. if (wantsDIData)
  16477. diParams->push_back(mBfIRBuilder->DbgGetType(resolvedType));
  16478. if (paramVar->mIsSplat)
  16479. {
  16480. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  16481. }
  16482. else
  16483. {
  16484. argIdx++;
  16485. }
  16486. if (loweredTypeCode2 != BfTypeCode_None)
  16487. argIdx++;
  16488. }
  16489. }
  16490. // Try to find an ending delegate params composite
  16491. if ((compositeVariableIdx == -1) && (methodDef->mParams.size() > 0))
  16492. {
  16493. auto paramDef = methodDef->mParams.back();
  16494. if (paramDef->mParamKind == BfParamKind_Params)
  16495. {
  16496. auto paramsType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_NoResolveGenericParam);
  16497. if (paramsType == NULL)
  16498. {
  16499. // Had error or 'var'
  16500. }
  16501. else if (paramsType->IsGenericParam())
  16502. {
  16503. auto genericParamInstance = GetGenericParamInstance((BfGenericParamType*)paramsType);
  16504. if (genericParamInstance->mTypeConstraint != NULL)
  16505. {
  16506. auto typeInstConstraint = genericParamInstance->mTypeConstraint->ToTypeInstance();
  16507. if ((genericParamInstance->mTypeConstraint->IsDelegate()) || (genericParamInstance->mTypeConstraint->IsFunction()) ||
  16508. ((typeInstConstraint != NULL) &&
  16509. ((typeInstConstraint->IsInstanceOf(mCompiler->mDelegateTypeDef)) || (typeInstConstraint->IsInstanceOf(mCompiler->mFunctionTypeDef)))))
  16510. {
  16511. BfLocalVariable* localVar = new BfLocalVariable();
  16512. localVar->mName = paramDef->mName;
  16513. localVar->mResolvedType = paramsType;
  16514. localVar->mCompositeCount = 0;
  16515. DoAddLocalVariable(localVar);
  16516. }
  16517. }
  16518. }
  16519. else if (paramsType->IsDelegate())
  16520. {
  16521. BfMethodInstance* invokeMethodInstance = GetRawMethodInstanceAtIdx(paramsType->ToTypeInstance(), 0, "Invoke");
  16522. if (invokeMethodInstance != NULL)
  16523. {
  16524. // This is only for the case where the delegate didn't actually have any params so the composite is zero-sized
  16525. // and wasn't cleared by the preceding loop
  16526. BF_ASSERT(invokeMethodInstance->GetParamCount() == 0);
  16527. BfLocalVariable* localVar = new BfLocalVariable();
  16528. localVar->mName = paramDef->mName;
  16529. localVar->mResolvedType = paramsType;
  16530. localVar->mCompositeCount = 0;
  16531. DoAddLocalVariable(localVar);
  16532. }
  16533. }
  16534. }
  16535. }
  16536. }
  16537. void BfModule::ProcessMethod_ProcessDeferredLocals(int startIdx)
  16538. {
  16539. // if (mCurMethodState->mPrevMethodState != NULL) // Re-entry
  16540. // return;
  16541. auto startMethodState = mCurMethodState;
  16542. auto _ClearState = [&]()
  16543. {
  16544. mCurMethodState->mLocalMethods.Clear();
  16545. for (auto& local : mCurMethodState->mLocals)
  16546. {
  16547. if (local->mIsBumpAlloc)
  16548. local->~BfLocalVariable();
  16549. else
  16550. delete local;
  16551. }
  16552. mCurMethodState->mLocals.Clear();
  16553. mCurMethodState->mLocalVarSet.Clear();
  16554. };
  16555. while (true)
  16556. {
  16557. bool didWork = false;
  16558. // 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
  16559. // we show errors in the capture phase. If we somehow pass the capture phase without error then this method WILL show any errors here,
  16560. // however (compiler bug), so this is the safest way
  16561. if (!mCurMethodState->mDeferredLocalMethods.IsEmpty())
  16562. {
  16563. for (int deferredLocalMethodIdx = 0; deferredLocalMethodIdx < (int)mCurMethodState->mDeferredLocalMethods.size(); deferredLocalMethodIdx++)
  16564. {
  16565. auto deferredLocalMethod = mCurMethodState->mDeferredLocalMethods[deferredLocalMethodIdx];
  16566. BfLogSysM("Processing deferred local method %p\n", deferredLocalMethod);
  16567. if (!mHadBuildError)
  16568. {
  16569. // Process as a closure - that allows us to look back and see the const locals and stuff
  16570. BfClosureState closureState;
  16571. mCurMethodState->mClosureState = &closureState;
  16572. closureState.mConstLocals = deferredLocalMethod->mConstLocals;
  16573. closureState.mReturnType = deferredLocalMethod->mMethodInstance->mReturnType;
  16574. closureState.mActiveDeferredLocalMethod = deferredLocalMethod;
  16575. closureState.mLocalMethod = deferredLocalMethod->mLocalMethod;
  16576. if (deferredLocalMethod->mMethodInstance->mMethodInfoEx != NULL)
  16577. closureState.mClosureInstanceInfo = deferredLocalMethod->mMethodInstance->mMethodInfoEx->mClosureInstanceInfo;
  16578. mCurMethodState->mMixinState = deferredLocalMethod->mLocalMethod->mDeclMixinState;
  16579. _ClearState();
  16580. for (auto& constLocal : deferredLocalMethod->mConstLocals)
  16581. {
  16582. auto localVar = new BfLocalVariable();
  16583. *localVar = constLocal;
  16584. DoAddLocalVariable(localVar);
  16585. }
  16586. mCurMethodState->mLocalMethods = deferredLocalMethod->mLocalMethods;
  16587. bool doProcess = !mCompiler->mCanceling;
  16588. if (doProcess)
  16589. {
  16590. BP_ZONE_F("ProcessMethod local %s", deferredLocalMethod->mMethodInstance->mMethodDef->mName.c_str());
  16591. ProcessMethod(deferredLocalMethod->mMethodInstance);
  16592. }
  16593. }
  16594. delete deferredLocalMethod;
  16595. mContext->CheckLockYield();
  16596. didWork = true;
  16597. }
  16598. mCurMethodState->mDeferredLocalMethods.Clear();
  16599. }
  16600. for (auto& kv : mCurMethodState->mLocalMethodCache)
  16601. {
  16602. BF_ASSERT((kv.mValue->mMethodDef == NULL) || (kv.mKey == kv.mValue->mMethodDef->mName));
  16603. }
  16604. if ((!mCurMethodState->mDeferredLambdaInstances.IsEmpty()) && (!mHadBuildError))
  16605. {
  16606. for (int deferredLambdaIdx = 0; deferredLambdaIdx < (int)mCurMethodState->mDeferredLambdaInstances.size(); deferredLambdaIdx++)
  16607. {
  16608. auto lambdaInstance = mCurMethodState->mDeferredLambdaInstances[deferredLambdaIdx];
  16609. BfLogSysM("Processing deferred lambdaInstance %p\n", lambdaInstance);
  16610. BfClosureState closureState;
  16611. mCurMethodState->mClosureState = &closureState;
  16612. //closureState.mConstLocals = deferredLocalMethod->mConstLocals;
  16613. closureState.mReturnType = lambdaInstance->mMethodInstance->mReturnType;
  16614. if (lambdaInstance->mClosureTypeInstance != NULL)
  16615. closureState.mClosureType = lambdaInstance->mClosureTypeInstance;
  16616. else
  16617. closureState.mClosureType = lambdaInstance->mDelegateTypeInstance;
  16618. closureState.mClosureInstanceInfo = lambdaInstance->mMethodInstance->mMethodInfoEx->mClosureInstanceInfo;
  16619. closureState.mDeclaringMethodIsMutating = lambdaInstance->mDeclaringMethodIsMutating;
  16620. mCurMethodState->mMixinState = lambdaInstance->mDeclMixinState;
  16621. _ClearState();
  16622. for (auto& constLocal : lambdaInstance->mConstLocals)
  16623. {
  16624. //if (constLocal.mIsThis)
  16625. {
  16626. // Valueless 'this'
  16627. closureState.mConstLocals.Add(constLocal);
  16628. }
  16629. /*else
  16630. {
  16631. auto localVar = new BfLocalVariable();
  16632. *localVar = constLocal;
  16633. DoAddLocalVariable(localVar);
  16634. }*/
  16635. }
  16636. BfMethodInstanceGroup methodInstanceGroup;
  16637. methodInstanceGroup.mOwner = mCurTypeInstance;
  16638. methodInstanceGroup.mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  16639. bool doProcess = !mCompiler->mCanceling;
  16640. if (doProcess)
  16641. {
  16642. BP_ZONE_F("ProcessMethod lambdaInstance %s", lambdaInstance->mMethodInstance->mMethodDef->mName.c_str());
  16643. lambdaInstance->mMethodInstance->mMethodInstanceGroup = &methodInstanceGroup;
  16644. ProcessMethod(lambdaInstance->mMethodInstance);
  16645. lambdaInstance->mMethodInstance->mMethodInstanceGroup = NULL;
  16646. if (lambdaInstance->mDtorMethodInstance != NULL)
  16647. {
  16648. lambdaInstance->mDtorMethodInstance->mMethodInstanceGroup = &methodInstanceGroup;
  16649. auto startMethodState2 = mCurMethodState;
  16650. ProcessMethod(lambdaInstance->mDtorMethodInstance);
  16651. lambdaInstance->mDtorMethodInstance->mMethodInstanceGroup = NULL;
  16652. }
  16653. }
  16654. didWork = true;
  16655. }
  16656. mContext->CheckLockYield();
  16657. mCurMethodState->mDeferredLambdaInstances.Clear();
  16658. }
  16659. if (!didWork)
  16660. break;
  16661. }
  16662. }
  16663. void BfModule::EmitGCMarkValue(BfTypedValue& thisValue, BfType* checkType, int memberDepth, int curOffset, HashSet<int>& objectOffsets, BfModuleMethodInstance markFromGCThreadMethodInstance, bool isAppendObject)
  16664. {
  16665. if (checkType->IsComposite())
  16666. PopulateType(checkType, BfPopulateType_Data);
  16667. if (!checkType->WantsGCMarking())
  16668. return;
  16669. auto typeInstance = checkType->ToTypeInstance();
  16670. bool callMarkMethod = false;
  16671. // Call the actual marking method
  16672. if (memberDepth == 0)
  16673. {
  16674. // Don't call marking method on self
  16675. }
  16676. else if (checkType->IsObjectOrInterface())
  16677. {
  16678. if (!objectOffsets.Add(curOffset))
  16679. {
  16680. return;
  16681. }
  16682. callMarkMethod = true;
  16683. }
  16684. else if (checkType->IsSizedArray())
  16685. {
  16686. BfSizedArrayType* sizedArrayType = (BfSizedArrayType*)checkType;
  16687. if (sizedArrayType->mElementType->WantsGCMarking())
  16688. {
  16689. BfTypedValue arrayValue = thisValue;
  16690. if (thisValue.mType != checkType)
  16691. {
  16692. BfIRValue srcValue = thisValue.mValue;
  16693. if (curOffset != 0)
  16694. {
  16695. if (!thisValue.mType->IsPointer())
  16696. {
  16697. auto int8Type = GetPrimitiveType(BfTypeCode_UInt8);
  16698. auto int8PtrType = CreatePointerType(int8Type);
  16699. srcValue = mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(int8PtrType));
  16700. }
  16701. srcValue = mBfIRBuilder->CreateInBoundsGEP(srcValue, curOffset);
  16702. }
  16703. arrayValue = BfTypedValue(mBfIRBuilder->CreateBitCast(srcValue, mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(checkType))), checkType, BfTypedValueKind_Addr);
  16704. }
  16705. if (sizedArrayType->mElementCount > 6)
  16706. {
  16707. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  16708. auto itr = CreateAlloca(intPtrType);
  16709. mBfIRBuilder->CreateStore(GetDefaultValue(intPtrType), itr);
  16710. auto loopBB = mBfIRBuilder->CreateBlock("loop", true);
  16711. auto bodyBB = mBfIRBuilder->CreateBlock("body", true);
  16712. auto doneBB = mBfIRBuilder->CreateBlock("done", true);
  16713. mBfIRBuilder->CreateBr(loopBB);
  16714. mBfIRBuilder->SetInsertPoint(loopBB);
  16715. auto loadedItr = mBfIRBuilder->CreateLoad(itr);
  16716. auto cmpRes = mBfIRBuilder->CreateCmpGTE(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)sizedArrayType->mElementCount), true);
  16717. mBfIRBuilder->CreateCondBr(cmpRes, doneBB, bodyBB);
  16718. mBfIRBuilder->SetInsertPoint(bodyBB);
  16719. auto ptrType = CreatePointerType(sizedArrayType->mElementType);
  16720. auto ptrValue = mBfIRBuilder->CreateBitCast(arrayValue.mValue, mBfIRBuilder->MapType(ptrType));
  16721. auto gepResult = mBfIRBuilder->CreateInBoundsGEP(ptrValue, loadedItr);
  16722. auto value = BfTypedValue(gepResult, sizedArrayType->mElementType, BfTypedValueKind_Addr);
  16723. EmitGCMarkValue(value, markFromGCThreadMethodInstance);
  16724. auto incValue = mBfIRBuilder->CreateAdd(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  16725. mBfIRBuilder->CreateStore(incValue, itr);
  16726. mBfIRBuilder->CreateBr(loopBB);
  16727. mBfIRBuilder->SetInsertPoint(doneBB);
  16728. }
  16729. else
  16730. {
  16731. for (int dataIdx = 0; dataIdx < sizedArrayType->mElementCount; dataIdx++)
  16732. {
  16733. auto ptrType = CreatePointerType(sizedArrayType->mElementType);
  16734. auto ptrValue = mBfIRBuilder->CreateBitCast(arrayValue.mValue, mBfIRBuilder->MapType(ptrType));
  16735. auto gepResult = mBfIRBuilder->CreateInBoundsGEP(ptrValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, dataIdx));
  16736. auto value = BfTypedValue(gepResult, sizedArrayType->mElementType, BfTypedValueKind_Addr);
  16737. HashSet<int> objectOffsets;
  16738. EmitGCMarkValue(value, markFromGCThreadMethodInstance);
  16739. }
  16740. }
  16741. }
  16742. }
  16743. else if (typeInstance != NULL)
  16744. {
  16745. typeInstance->mTypeDef->PopulateMemberSets();
  16746. BfMemberSetEntry* entry = NULL;
  16747. BfMethodDef* methodDef = NULL;
  16748. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(String(BF_METHODNAME_MARKMEMBERS), &entry))
  16749. {
  16750. methodDef = (BfMethodDef*)entry->mMemberDef;
  16751. if (methodDef->HasBody())
  16752. {
  16753. callMarkMethod = true;
  16754. }
  16755. }
  16756. }
  16757. if (callMarkMethod)
  16758. {
  16759. BfTypedValue markValue;
  16760. auto memberType = checkType;
  16761. if (memberType->IsObjectOrInterface())
  16762. memberType = mContext->mBfObjectType; // Just to avoid that extra cast for the call itself
  16763. auto memberPtrType = CreatePointerType(memberType);
  16764. if (curOffset == 0)
  16765. {
  16766. markValue = BfTypedValue(mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(memberPtrType)), memberType, true);
  16767. }
  16768. else
  16769. {
  16770. if (!thisValue.mType->IsPointer())
  16771. {
  16772. auto int8Type = GetPrimitiveType(BfTypeCode_UInt8);
  16773. auto int8PtrType = CreatePointerType(int8Type);
  16774. thisValue = BfTypedValue(mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(int8PtrType)), int8PtrType);
  16775. }
  16776. auto offsetValue = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, curOffset);
  16777. markValue = BfTypedValue(mBfIRBuilder->CreateBitCast(offsetValue, mBfIRBuilder->MapType(memberPtrType)), memberType, true);
  16778. }
  16779. if (isAppendObject)
  16780. EmitGCMarkAppended(markValue);
  16781. else
  16782. EmitGCMarkValue(markValue, markFromGCThreadMethodInstance);
  16783. return;
  16784. }
  16785. auto methodDef = mCurMethodInstance->mMethodDef;
  16786. if (checkType->IsPayloadEnum())
  16787. {
  16788. for (auto& fieldInst : typeInstance->mFieldInstances)
  16789. {
  16790. if (!fieldInst.mIsEnumPayloadCase)
  16791. continue;
  16792. auto fieldDef = fieldInst.GetFieldDef();
  16793. EmitGCMarkValue(thisValue, fieldInst.mResolvedType, memberDepth + 1, curOffset, objectOffsets, markFromGCThreadMethodInstance);
  16794. }
  16795. return;
  16796. }
  16797. if (typeInstance == NULL)
  16798. return;
  16799. for (auto& fieldInst : typeInstance->mFieldInstances)
  16800. {
  16801. auto fieldDef = fieldInst.GetFieldDef();
  16802. if (fieldDef == NULL)
  16803. continue;
  16804. if (fieldDef->mIsStatic)
  16805. continue;
  16806. if (typeInstance == mCurTypeInstance)
  16807. {
  16808. // Note: we don't do method chaining when we are marking members of members. Theoretically this means
  16809. // we may be marking member values that can never contain a value anyway, but this is benign
  16810. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  16811. continue;
  16812. }
  16813. EmitGCMarkValue(thisValue, fieldInst.mResolvedType, memberDepth + 1, curOffset + fieldInst.mDataOffset, objectOffsets, markFromGCThreadMethodInstance, fieldInst.IsAppendedObject());
  16814. }
  16815. if ((typeInstance->mBaseType != NULL) && (typeInstance->mBaseType != mContext->mBfObjectType))
  16816. {
  16817. EmitGCMarkValue(thisValue, typeInstance->mBaseType, memberDepth, curOffset, objectOffsets, markFromGCThreadMethodInstance);
  16818. }
  16819. }
  16820. void BfModule::EmitGCMarkMembers()
  16821. {
  16822. auto methodDef = mCurMethodInstance->mMethodDef;
  16823. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef, BfPopulateType_DataAndMethods);
  16824. BfModuleMethodInstance markFromGCThreadMethodInstance;
  16825. if (gcType != NULL)
  16826. markFromGCThreadMethodInstance = GetMethodByName(gcType->ToTypeInstance(), "Mark", 1);
  16827. if ((markFromGCThreadMethodInstance.mMethodInstance != NULL) && (!mCurMethodInstance->mIsUnspecialized))
  16828. {
  16829. if (mCurTypeInstance->IsBoxed())
  16830. {
  16831. // This already gets filled in by the normal boxed forwarding
  16832. }
  16833. else
  16834. {
  16835. auto thisValue = GetThis();
  16836. if (thisValue.IsSplat())
  16837. {
  16838. BfIRFunction func = mCurMethodInstance->mIRFunction;
  16839. int argIdx = 0;
  16840. std::function<void(BfType*)> checkTypeLambda = [&](BfType* checkType)
  16841. {
  16842. if (checkType->IsStruct())
  16843. {
  16844. auto checkTypeInstance = checkType->ToTypeInstance();
  16845. if (checkTypeInstance->mBaseType != NULL)
  16846. checkTypeLambda(checkTypeInstance->mBaseType);
  16847. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  16848. {
  16849. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  16850. if (fieldInstance->mDataIdx >= 0)
  16851. checkTypeLambda(fieldInstance->GetResolvedType());
  16852. }
  16853. }
  16854. else if (checkType->IsMethodRef())
  16855. {
  16856. BFMODULE_FATAL(this, "Not handled");
  16857. }
  16858. else if (checkType->WantsGCMarking())
  16859. {
  16860. BfTypedValue markValue(mBfIRBuilder->GetArgument(argIdx), checkType);
  16861. EmitGCMarkValue(markValue, markFromGCThreadMethodInstance);
  16862. argIdx++;
  16863. }
  16864. };
  16865. checkTypeLambda(thisValue.mType);
  16866. }
  16867. else if (!methodDef->mIsStatic)
  16868. {
  16869. if ((mCurTypeInstance->mBaseType != NULL) && (!mCurTypeInstance->IsTypedPrimitive()) && (mCurTypeInstance->mBaseType->WantsGCMarking()))
  16870. {
  16871. BfModuleMethodInstance moduleMethodInst = GetMethodByName(mCurTypeInstance->mBaseType, BF_METHODNAME_MARKMEMBERS, 0, true);
  16872. if (moduleMethodInst)
  16873. {
  16874. auto methodBaseType = moduleMethodInst.mMethodInstance->GetOwner();
  16875. bool wantsBaseMarking = true;
  16876. if (methodBaseType == mContext->mBfObjectType)
  16877. {
  16878. wantsBaseMarking = false;
  16879. PopulateType(methodBaseType);
  16880. for (auto& fieldInstance : mContext->mBfObjectType->mFieldInstances)
  16881. {
  16882. if ((fieldInstance.GetFieldDef()->mDeclaringType->IsExtension()) &&
  16883. (fieldInstance.mResolvedType->WantsGCMarking()))
  16884. wantsBaseMarking = true;
  16885. }
  16886. }
  16887. if (wantsBaseMarking)
  16888. {
  16889. auto thisValue = GetThis();
  16890. auto baseValue = Cast(NULL, thisValue, methodBaseType, BfCastFlags_Explicit);
  16891. SizedArray<BfIRValue, 1> args;
  16892. if ((!mIsComptimeModule) && (moduleMethodInst.mMethodInstance->GetParamIsSplat(-1)))
  16893. {
  16894. BfExprEvaluator exprEvaluator(this);
  16895. exprEvaluator.SplatArgs(baseValue, args);
  16896. }
  16897. else
  16898. {
  16899. args.push_back(baseValue.mValue);
  16900. }
  16901. mBfIRBuilder->CreateCall(moduleMethodInst.mFunc, args);
  16902. }
  16903. }
  16904. }
  16905. }
  16906. if (!methodDef->mIsStatic)
  16907. {
  16908. HashSet<int> objectOffsets;
  16909. EmitGCMarkValue(thisValue, mCurTypeInstance, 0, 0, objectOffsets, markFromGCThreadMethodInstance);
  16910. }
  16911. else
  16912. {
  16913. for (auto& fieldInst : mCurTypeInstance->mFieldInstances)
  16914. {
  16915. if (thisValue.IsSplat())
  16916. break;
  16917. auto fieldDef = fieldInst.GetFieldDef();
  16918. if (fieldDef == NULL)
  16919. continue;
  16920. if (fieldInst.mIsThreadLocal)
  16921. continue;
  16922. if (fieldDef->mIsStatic == methodDef->mIsStatic)
  16923. {
  16924. // For extensions, only handle these fields in the appropriate extension
  16925. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  16926. continue;
  16927. if (!fieldInst.mFieldIncluded)
  16928. continue;
  16929. auto fieldType = fieldInst.mResolvedType;
  16930. auto fieldDef = fieldInst.GetFieldDef();
  16931. BfTypedValue markVal;
  16932. if (fieldDef->mIsConst)
  16933. continue;
  16934. if ((!fieldType->IsObjectOrInterface()) && (!fieldType->IsComposite()))
  16935. continue;
  16936. mBfIRBuilder->PopulateType(fieldType);
  16937. if (fieldType->IsValuelessType())
  16938. continue;
  16939. if ((fieldDef->mIsStatic) && (!fieldDef->mIsConst))
  16940. {
  16941. StringT<512> staticVarName;
  16942. BfMangler::Mangle(staticVarName, mCompiler->GetMangleKind(), &fieldInst);
  16943. if (staticVarName.StartsWith('#'))
  16944. continue;
  16945. markVal = ReferenceStaticField(&fieldInst);
  16946. }
  16947. else if (!fieldDef->mIsStatic)
  16948. {
  16949. if (fieldInst.IsAppendedObject())
  16950. {
  16951. auto fieldAddr = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, fieldInst.mDataIdx);
  16952. auto val = mBfIRBuilder->CreateBitCast(fieldAddr, mBfIRBuilder->MapType(mContext->mBfObjectType));
  16953. markVal = BfTypedValue(mBfIRBuilder->CreateBitCast(fieldAddr, mBfIRBuilder->MapType(fieldInst.mResolvedType)), fieldInst.mResolvedType);
  16954. }
  16955. else
  16956. {
  16957. markVal = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInst.mDataIdx/*, fieldDef->mName*/), fieldInst.mResolvedType, true);
  16958. }
  16959. }
  16960. if (markVal)
  16961. {
  16962. if (fieldInst.IsAppendedObject())
  16963. EmitGCMarkAppended(markVal);
  16964. else
  16965. EmitGCMarkValue(markVal, markFromGCThreadMethodInstance);
  16966. }
  16967. }
  16968. }
  16969. }
  16970. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  16971. CallChainedMethods(mCurMethodInstance, false);
  16972. }
  16973. }
  16974. }
  16975. void BfModule::EmitGCFindTLSMembers()
  16976. {
  16977. auto methodDef = mCurMethodInstance->mMethodDef;
  16978. auto gcTypeInst = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  16979. auto reportTLSMark = GetMethodByName(gcTypeInst, "ReportTLSMember", 2);
  16980. BF_ASSERT(reportTLSMark);
  16981. for (auto& fieldInst : mCurTypeInstance->mFieldInstances)
  16982. {
  16983. auto fieldDef = fieldInst.GetFieldDef();
  16984. if (fieldDef == NULL)
  16985. continue;
  16986. if (!fieldInst.mIsThreadLocal)
  16987. continue;
  16988. // For extensions, only handle these fields in the appropriate extension
  16989. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  16990. continue;
  16991. if (!fieldInst.mFieldIncluded)
  16992. continue;
  16993. if (fieldDef->mIsConst)
  16994. continue;
  16995. auto fieldType = fieldInst.mResolvedType;
  16996. if ((!fieldType->IsObjectOrInterface()) && (!fieldType->IsComposite()))
  16997. continue;
  16998. if (fieldType->IsValuelessType())
  16999. continue;
  17000. BfTypedValue markVal = ReferenceStaticField(&fieldInst);
  17001. if (markVal)
  17002. {
  17003. BfIRValue fieldRefPtr = mBfIRBuilder->CreateBitCast(markVal.mValue, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  17004. BfIRValue markFuncPtr = GetMarkFuncPtr(fieldType);
  17005. SizedArray<BfIRValue, 2> llvmArgs;
  17006. llvmArgs.push_back(fieldRefPtr);
  17007. llvmArgs.push_back(markFuncPtr);
  17008. mBfIRBuilder->CreateCall(reportTLSMark.mFunc, llvmArgs);
  17009. }
  17010. }
  17011. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  17012. CallChainedMethods(mCurMethodInstance, false);
  17013. }
  17014. void BfModule::ProcessMethod(BfMethodInstance* methodInstance, bool isInlineDup, bool forceIRWrites)
  17015. {
  17016. BP_ZONE_F("BfModule::ProcessMethod %s", BP_DYN_STR(methodInstance->mMethodDef->mName.c_str()));
  17017. if (mIsComptimeModule)
  17018. {
  17019. BF_ASSERT(!mCompiler->IsAutocomplete());
  17020. }
  17021. if (mAwaitingInitFinish)
  17022. FinishInit();
  17023. if (!methodInstance->mIsReified)
  17024. BF_ASSERT(!mIsReified);
  17025. BF_ASSERT((!methodInstance->GetOwner()->IsUnspecializedTypeVariation()) || (mIsComptimeModule));
  17026. if (methodInstance->mMethodInfoEx != NULL)
  17027. {
  17028. for (auto methodGenericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  17029. {
  17030. if (methodGenericArg->IsMethodRef())
  17031. {
  17032. auto methodRefType = (BfMethodRefType*)methodGenericArg;
  17033. BF_ASSERT(methodRefType->mOwnerRevision == methodRefType->mOwner->mRevision);
  17034. }
  17035. }
  17036. }
  17037. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, (mWantsIRIgnoreWrites || methodInstance->mIsUnspecialized) && (!forceIRWrites));
  17038. if ((HasCompiledOutput()) && (!mBfIRBuilder->mIgnoreWrites))
  17039. {
  17040. BF_ASSERT(!methodInstance->mIRFunction.IsFake() || (methodInstance->GetImportCallKind() != BfImportCallKind_None));
  17041. }
  17042. SetAndRestoreValue<bool> prevIsClassifying;
  17043. if (((methodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend) || (methodInstance->mIsForeignMethodDef) || (methodInstance->IsSpecializedGenericMethod())) &&
  17044. (mCompiler->mResolvePassData != NULL))
  17045. {
  17046. // Don't classify on the CtorCalcAppend, just on the actual Ctor
  17047. prevIsClassifying.Init(mCompiler->mResolvePassData->mIsClassifying, false);
  17048. }
  17049. if (methodInstance->mHasBeenProcessed)
  17050. {
  17051. BfLogSysM("ProcessMethod %p HasBeenProcessed\n", methodInstance);
  17052. return;
  17053. }
  17054. if (methodInstance->mFailedConstraints)
  17055. {
  17056. // The only way this should be able to happen is if we fail our generic param check
  17057. BF_ASSERT(methodInstance->IsSpecializedGenericMethod());
  17058. BfLogSysM("Method instance marked as 'failed' at start of ProcessMethod %p\n", methodInstance);
  17059. methodInstance->mHasBeenProcessed = true;
  17060. return;
  17061. }
  17062. if (HasExecutedOutput())
  17063. {
  17064. BF_ASSERT(mIsModuleMutable);
  17065. }
  17066. BfMethodInstance* defaultMethodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  17067. if (!mIsComptimeModule)
  17068. {
  17069. BF_ASSERT(methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_NotSet);
  17070. if ((methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_AlwaysInclude) &&
  17071. (methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_Referenced))
  17072. {
  17073. auto owningModule = methodInstance->GetOwner()->mModule;
  17074. if (owningModule->mIsScratchModule)
  17075. {
  17076. BF_ASSERT(owningModule->mOnDemandMethodCount == 0);
  17077. }
  17078. else
  17079. {
  17080. BF_ASSERT((owningModule->mOnDemandMethodCount > 0) || (!HasCompiledOutput()) || (owningModule->mExtensionCount > 0));
  17081. if (owningModule->mOnDemandMethodCount > 0)
  17082. owningModule->mOnDemandMethodCount--;
  17083. }
  17084. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Referenced;
  17085. VerifyOnDemandMethods();
  17086. }
  17087. }
  17088. // We set mHasBeenProcessed to true immediately -- this helps avoid stack overflow during recursion for things like
  17089. // self-referencing append allocations in ctor@calcAppend
  17090. methodInstance->mHasBeenProcessed = true;
  17091. mIncompleteMethodCount--;
  17092. BF_ASSERT((mIsSpecialModule) || (mIncompleteMethodCount >= 0));
  17093. auto typeDef = methodInstance->mMethodInstanceGroup->mOwner->mTypeDef;
  17094. auto methodDef = methodInstance->mMethodDef;
  17095. auto methodDeclaration = methodDef->GetMethodDeclaration();
  17096. if ((methodDef->mHasComptime) && (!mIsComptimeModule))
  17097. mBfIRBuilder->mIgnoreWrites = true;
  17098. if ((methodInstance->mIsReified) && (methodInstance->mVirtualTableIdx != -1))
  17099. {
  17100. // If we reify a virtual method in a HotCompile then we need to make sure the type data gets written out
  17101. // so we get the new vdata for it
  17102. methodInstance->GetOwner()->mDirty = true;
  17103. }
  17104. int dependentGenericStartIdx = 0;
  17105. if ((methodDef->mIsLocalMethod) && (mCurMethodState != NULL)) // See DoMethodDeclaration for an explaination of dependentGenericStartIdx
  17106. dependentGenericStartIdx = (int)mCurMethodState->GetRootMethodState()->mMethodInstance->GetNumGenericArguments();
  17107. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  17108. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, methodInstance->mMethodInstanceGroup->mOwner);
  17109. SetAndRestoreValue<BfFilePosition> prevFilePos(mCurFilePosition);
  17110. SetAndRestoreValue<bool> prevHadBuildError(mHadBuildError, false);
  17111. SetAndRestoreValue<bool> prevHadWarning(mHadBuildWarning, false);
  17112. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors);
  17113. SetAndRestoreValue<bool> prevIgnoreWarnings(mIgnoreWarnings, mIsComptimeModule);
  17114. if ((!mIsComptimeModule) && (methodInstance->mIsReified) &&
  17115. ((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorNoBody)))
  17116. {
  17117. mCurTypeInstance->mHasBeenInstantiated = true;
  17118. }
  17119. // Warnings are shown in the capture phase
  17120. if ((methodDef->mIsLocalMethod) || (mCurTypeInstance->IsClosure()))
  17121. mIgnoreWarnings = true;
  17122. if ((methodDeclaration == NULL) && (mCurMethodState == NULL))
  17123. UseDefaultSrcPos();
  17124. if ((mIsComptimeModule) && (methodDef->mIsStatic))
  17125. {
  17126. PopulateType(mCurTypeInstance, BfPopulateType_AllowStaticMethods);
  17127. }
  17128. else
  17129. {
  17130. // We may not actually be populated in relatively rare autocompelte cases
  17131. PopulateType(mCurTypeInstance, BfPopulateType_DataAndMethods);
  17132. mBfIRBuilder->PopulateType(mCurTypeInstance, BfIRPopulateType_Full);
  17133. }
  17134. BfAstNode* nameNode = NULL;
  17135. if (methodDeclaration != NULL)
  17136. {
  17137. nameNode = methodDeclaration->mNameNode;
  17138. if (nameNode == NULL)
  17139. {
  17140. if (auto ctorDeclaration = BfNodeDynCast<BfConstructorDeclaration>(methodDeclaration))
  17141. nameNode = ctorDeclaration->mThisToken;
  17142. }
  17143. }
  17144. if ((mCompiler->mResolvePassData != NULL) && (methodDeclaration != NULL) && (nameNode != NULL) &&
  17145. (mCompiler->mResolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Method) &&
  17146. (methodDef->mIdx >= 0) && (!methodInstance->mIsForeignMethodDef))
  17147. {
  17148. if (methodInstance->GetExplicitInterface() == NULL)
  17149. mCompiler->mResolvePassData->HandleMethodReference(nameNode, typeDef, methodDef);
  17150. else
  17151. {
  17152. for (auto& ifaceEntry : mCurTypeInstance->mInterfaces)
  17153. {
  17154. auto ifaceInst = ifaceEntry.mInterfaceType;
  17155. int startIdx = ifaceEntry.mStartInterfaceTableIdx;
  17156. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  17157. if (methodInstance->GetExplicitInterface() != ifaceInst)
  17158. continue;
  17159. ifaceInst->mTypeDef->PopulateMemberSets();
  17160. BfMethodDef* nextMethod = NULL;
  17161. BfMemberSetEntry* entry = NULL;
  17162. if (ifaceInst->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  17163. nextMethod = (BfMethodDef*)entry->mMemberDef;
  17164. while (nextMethod != NULL)
  17165. {
  17166. auto checkMethod = nextMethod;
  17167. nextMethod = nextMethod->mNextWithSameName;
  17168. BfMethodInstance* implMethodInst = mCurTypeInstance->mInterfaceMethodTable[startIdx + checkMethod->mIdx].mMethodRef;
  17169. if (implMethodInst == methodInstance)
  17170. {
  17171. auto ifaceMethodDef = ifaceInst->mTypeDef->mMethods[checkMethod->mIdx];
  17172. mCompiler->mResolvePassData->HandleMethodReference(nameNode, ifaceInst->mTypeDef, ifaceMethodDef);
  17173. }
  17174. }
  17175. }
  17176. }
  17177. if (methodDef->mIsOverride)
  17178. {
  17179. for (int virtIdx = 0; virtIdx < (int)mCurTypeInstance->mVirtualMethodTable.size(); virtIdx++)
  17180. {
  17181. auto& ventry = mCurTypeInstance->mVirtualMethodTable[virtIdx];
  17182. if (ventry.mDeclaringMethod.mMethodNum == -1)
  17183. continue;
  17184. BfMethodInstance* virtMethod = ventry.mImplementingMethod;
  17185. if (virtMethod != NULL)
  17186. {
  17187. if (virtMethod == methodInstance)
  17188. {
  17189. // Is matching method
  17190. if (virtIdx < (int)mCurTypeInstance->mBaseType->mVirtualMethodTable.size())
  17191. {
  17192. auto baseType = mCurTypeInstance->mBaseType;
  17193. if (baseType != NULL)
  17194. {
  17195. while ((baseType->mBaseType != NULL) && (virtIdx < baseType->mBaseType->mVirtualMethodTableSize))
  17196. baseType = baseType->mBaseType;
  17197. BfMethodInstance* baseVirtMethod = baseType->mVirtualMethodTable[virtIdx].mImplementingMethod;
  17198. mCompiler->mResolvePassData->HandleMethodReference(nameNode, baseType->mTypeDef, baseVirtMethod->mMethodDef);
  17199. }
  17200. }
  17201. break;
  17202. }
  17203. }
  17204. }
  17205. }
  17206. }
  17207. BfLogSysM("ProcessMethod %p Unspecialized: %d Module: %p IRFunction: %d Reified: %d Incomplete:%d\n", methodInstance, mCurTypeInstance->IsUnspecializedType(), this, methodInstance->mIRFunction.mId, methodInstance->mIsReified, mIncompleteMethodCount);
  17208. int importStrNum = -1;
  17209. auto importKind = methodInstance->GetImportKind();
  17210. if ((!mCompiler->mIsResolveOnly) &&
  17211. ((importKind == BfImportKind_Import_Static) || (importKind == BfImportKind_Import_Dynamic)))
  17212. {
  17213. if (auto customAttr = methodInstance->GetCustomAttributes()->Get(mCompiler->mImportAttributeTypeDef))
  17214. {
  17215. if (customAttr->mCtorArgs.size() == 1)
  17216. {
  17217. auto fileNameArg = customAttr->mCtorArgs[0];
  17218. auto constant = mCurTypeInstance->mConstHolder->GetConstant(fileNameArg);
  17219. if (constant != NULL)
  17220. {
  17221. if (!constant->IsNull())
  17222. importStrNum = constant->mInt32;
  17223. }
  17224. else
  17225. {
  17226. importStrNum = GetStringPoolIdx(fileNameArg, mCurTypeInstance->mConstHolder);
  17227. }
  17228. if (importStrNum != -1)
  17229. {
  17230. if (!mStringPoolRefs.Contains(importStrNum))
  17231. mStringPoolRefs.Add(importStrNum);
  17232. }
  17233. }
  17234. }
  17235. }
  17236. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  17237. {
  17238. if (mBfIRBuilder->mIgnoreWrites)
  17239. return;
  17240. BfLogSysM("DllImportGlobalVar processing %p\n", methodInstance);
  17241. if (!methodInstance->mIRFunction)
  17242. {
  17243. BfIRValue dllImportGlobalVar = CreateDllImportGlobalVar(methodInstance, true);
  17244. methodInstance->mIRFunction = mBfIRBuilder->GetFakeVal();
  17245. BF_ASSERT(dllImportGlobalVar || methodInstance->mHasFailed);
  17246. mFuncReferences[mCurMethodInstance] = dllImportGlobalVar;
  17247. }
  17248. if (HasCompiledOutput())
  17249. {
  17250. BfDllImportEntry dllImportEntry;
  17251. dllImportEntry.mFuncVar = methodInstance->mIRFunction;
  17252. dllImportEntry.mMethodInstance = mCurMethodInstance;
  17253. mDllImportEntries.push_back(dllImportEntry);
  17254. }
  17255. return;
  17256. }
  17257. StringT<512> mangledName;
  17258. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  17259. if (!methodInstance->mIRFunction)
  17260. {
  17261. bool isIntrinsic = false;
  17262. SetupIRFunction(methodInstance, mangledName, false, &isIntrinsic);
  17263. }
  17264. if (methodInstance->mIsIntrinsic)
  17265. return;
  17266. if (mCurTypeInstance->IsFunction())
  17267. return;
  17268. auto prevActiveFunction = mBfIRBuilder->GetActiveFunction();
  17269. mBfIRBuilder->SetActiveFunction(mCurMethodInstance->mIRFunction);
  17270. if (methodDef->mBody != NULL)
  17271. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  17272. else if (methodDeclaration != NULL)
  17273. UpdateSrcPos(methodDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  17274. else if ((methodDef->mDeclaringType != NULL) && (methodDef->mDeclaringType->GetRefNode() != NULL))
  17275. UpdateSrcPos(methodDef->mDeclaringType->GetRefNode(), BfSrcPosFlag_NoSetDebugLoc);
  17276. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  17277. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  17278. if ((mCurMethodState == NULL) && (!IsInSpecializedSection())) // Only do initial classify for the 'outer' method state, not any local methods or lambdas
  17279. {
  17280. if ((mCompiler->mIsResolveOnly) && (!mIsComptimeModule) && (methodDef->mBody != NULL) && (!mCurTypeInstance->IsBoxed()))
  17281. {
  17282. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(methodDef->mBody))
  17283. sourceClassifier->VisitChildNoRef(methodDef->mBody);
  17284. }
  17285. }
  17286. BfHotDataReferenceBuilder hotDataReferenceBuilder;
  17287. BfMethodState methodState;
  17288. if (mCurMethodState != NULL)
  17289. methodState.mClosureState = mCurMethodState->mClosureState;
  17290. if ((mCompiler->mOptions.mAllowHotSwapping) && (methodInstance->mIsReified) && (!methodInstance->mIsUnspecialized) && (!isInlineDup))
  17291. {
  17292. //BF_ASSERT(methodInstance->mHotMethod != NULL);
  17293. if (methodInstance->mHotMethod == NULL)
  17294. CheckHotMethod(methodInstance, mangledName);
  17295. methodState.mHotDataReferenceBuilder = &hotDataReferenceBuilder;
  17296. }
  17297. methodState.mPrevMethodState = mCurMethodState;
  17298. methodState.mMethodInstance = methodInstance;
  17299. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  17300. if (methodInstance->GetCustomAttributes() != NULL)
  17301. {
  17302. int typeOptionsIdx = GenerateTypeOptions(methodInstance->GetCustomAttributes(), mCurTypeInstance, false);
  17303. if (typeOptionsIdx != -1)
  17304. methodState.mMethodTypeOptions = mSystem->GetTypeOptions(typeOptionsIdx);
  17305. }
  17306. BfTypeState typeState(mCurTypeInstance);
  17307. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  17308. bool isGenericVariation = (methodInstance->mIsUnspecializedVariation) || (mCurTypeInstance->IsUnspecializedTypeVariation());
  17309. BfMethodInstance* unspecializedMethodInstance = NULL;
  17310. if ((prevMethodState.mPrevVal != NULL) &&
  17311. ((methodState.mClosureState == NULL) || (methodState.mClosureState->mActiveDeferredLocalMethod == NULL)))
  17312. {
  17313. // This is 'inner' (probably a closure) - use binding from outer function
  17314. methodState.mGenericTypeBindings = prevMethodState.mPrevVal->mGenericTypeBindings;
  17315. }
  17316. else if ((methodInstance->mIsUnspecialized) ||
  17317. ((mCurTypeInstance->IsUnspecializedType()) && (!isGenericVariation)))
  17318. {
  17319. methodState.mGenericTypeBindings = &methodInstance->GetMethodInfoEx()->mGenericTypeBindings;
  17320. }
  17321. else if ((((methodInstance->mMethodInfoEx != NULL) && ((int)methodInstance->mMethodInfoEx->mMethodGenericArguments.size() > dependentGenericStartIdx)) ||
  17322. ((mCurTypeInstance->IsGenericTypeInstance()) && (!isGenericVariation || mIsComptimeModule) && (!methodInstance->mMethodDef->mIsLocalMethod) && (!methodInstance->mMethodDef->mDeclaringType->IsEmitted()))))
  17323. {
  17324. unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance, !methodInstance->mMethodDef->mIsLocalMethod);
  17325. if ((mIsComptimeModule) && (!unspecializedMethodInstance->mHasBeenProcessed))
  17326. {
  17327. // This will have already been populated by CeMachine
  17328. methodState.mGenericTypeBindings = &methodInstance->GetMethodInfoEx()->mGenericTypeBindings;
  17329. }
  17330. else
  17331. {
  17332. BF_ASSERT(unspecializedMethodInstance != methodInstance);
  17333. if (!unspecializedMethodInstance->mHasBeenProcessed)
  17334. {
  17335. // Make sure the unspecialized method is processed so we can take its bindings
  17336. // Clear mCurMethodState so we don't think we're in a local method
  17337. SetAndRestoreValue<BfMethodState*> prevMethodState_Unspec(mCurMethodState, prevMethodState.mPrevVal);
  17338. if (unspecializedMethodInstance->mMethodProcessRequest == NULL)
  17339. unspecializedMethodInstance->mDeclModule->mIncompleteMethodCount++;
  17340. mContext->ProcessMethod(unspecializedMethodInstance);
  17341. }
  17342. methodState.mGenericTypeBindings = &unspecializedMethodInstance->GetMethodInfoEx()->mGenericTypeBindings;
  17343. }
  17344. }
  17345. if (methodDef->mMethodType == BfMethodType_Operator)
  17346. {
  17347. auto operatorDef = (BfOperatorDef*) methodDef;
  17348. BfAstNode* refNode = operatorDef->mOperatorDeclaration->mOperatorToken;
  17349. auto paramErrorRefNode = refNode;
  17350. if (operatorDef->mOperatorDeclaration->mOpenParen != NULL)
  17351. paramErrorRefNode = operatorDef->mOperatorDeclaration->mOpenParen;
  17352. if ((mCurMethodInstance->GetParamCount() > 0) && (mCurMethodInstance->GetParamTypeRef(0) != NULL))
  17353. paramErrorRefNode = mCurMethodInstance->GetParamTypeRef(0);
  17354. if (operatorDef->mOperatorDeclaration->mBinOp != BfBinaryOp_None)
  17355. {
  17356. if (methodDef->mParams.size() != 2)
  17357. {
  17358. Fail("Binary operators must declare two parameters", paramErrorRefNode);
  17359. }
  17360. else
  17361. {
  17362. auto checkParam0 = mCurMethodInstance->GetParamType(0);
  17363. if ((checkParam0->IsRef()) && (!checkParam0->IsOut()))
  17364. checkParam0 = checkParam0->GetUnderlyingType();
  17365. auto checkParam1 = mCurMethodInstance->GetParamType(1);
  17366. if ((checkParam1->IsRef()) && (!checkParam1->IsOut()))
  17367. checkParam1 = checkParam1->GetUnderlyingType();
  17368. if ((checkParam0 != mCurTypeInstance) && (!checkParam0->IsSelf()) &&
  17369. (checkParam1 != mCurTypeInstance) && (!checkParam1->IsSelf()))
  17370. {
  17371. Fail("At least one of the parameters of a binary operator must be the containing type", paramErrorRefNode);
  17372. }
  17373. }
  17374. BfType* wantType = NULL;
  17375. if (operatorDef->mOperatorDeclaration->mBinOp == BfBinaryOp_Compare)
  17376. {
  17377. wantType = GetPrimitiveType(BfTypeCode_IntPtr);
  17378. }
  17379. if ((wantType != NULL) && (methodInstance->mReturnType != wantType))
  17380. Fail(StrFormat("The return type for the '%s' operator must be '%s'", BfGetOpName(operatorDef->mOperatorDeclaration->mBinOp),
  17381. TypeToString(wantType).c_str()), operatorDef->mOperatorDeclaration->mReturnType);
  17382. }
  17383. else if (operatorDef->mOperatorDeclaration->mUnaryOp != BfUnaryOp_None)
  17384. {
  17385. if (methodDef->mIsStatic)
  17386. {
  17387. if (methodDef->mParams.size() != 1)
  17388. {
  17389. Fail("Unary operators must declare one parameter", paramErrorRefNode);
  17390. }
  17391. else
  17392. {
  17393. auto checkParam0 = mCurMethodInstance->GetParamType(0);
  17394. if ((checkParam0->IsRef()) && (!checkParam0->IsOut()))
  17395. checkParam0 = checkParam0->GetUnderlyingType();
  17396. if ((checkParam0 != mCurTypeInstance) && (!checkParam0->IsSelf()))
  17397. {
  17398. Fail("The parameter of a unary operator must be the containing type", paramErrorRefNode);
  17399. }
  17400. }
  17401. if (((operatorDef->mOperatorDeclaration->mUnaryOp == BfUnaryOp_Increment) ||
  17402. (operatorDef->mOperatorDeclaration->mUnaryOp == BfUnaryOp_Decrement)) &&
  17403. (!TypeIsSubTypeOf(mCurMethodInstance->mReturnType->ToTypeInstance(), mCurTypeInstance)))
  17404. {
  17405. Fail("The return type for the '++' or '--' operator must match the parameter type or be derived from the parameter type", operatorDef->mOperatorDeclaration->mReturnType);
  17406. }
  17407. }
  17408. else
  17409. {
  17410. if (methodDef->mParams.size() != 0)
  17411. {
  17412. Fail("Non-static unary operators not declare any parameters", paramErrorRefNode);
  17413. }
  17414. if (!mCurMethodInstance->mReturnType->IsVoid())
  17415. {
  17416. Fail("The return type for non-static operator must be 'void'", operatorDef->mOperatorDeclaration->mReturnType);
  17417. }
  17418. }
  17419. }
  17420. else if (operatorDef->mOperatorDeclaration->mAssignOp != BfAssignmentOp_None)
  17421. {
  17422. if (methodDef->mParams.size() != 1)
  17423. {
  17424. Fail("Assignment operators must declare one parameter", paramErrorRefNode);
  17425. }
  17426. if (!mCurMethodInstance->mReturnType->IsVoid())
  17427. {
  17428. Fail("The return type for assignment operator must be 'void'", operatorDef->mOperatorDeclaration->mReturnType);
  17429. }
  17430. }
  17431. else // Conversion
  17432. {
  17433. if (!operatorDef->mOperatorDeclaration->mIsConvOperator)
  17434. {
  17435. if (operatorDef->mOperatorDeclaration->mReturnType != NULL)
  17436. Fail("Conversion operators must declare their target type after the 'operator' token, not before", operatorDef->mOperatorDeclaration->mReturnType);
  17437. }
  17438. if (methodDef->mParams.size() != 1)
  17439. {
  17440. auto refNode = paramErrorRefNode;
  17441. if (!operatorDef->mOperatorDeclaration->mCommas.empty())
  17442. refNode = operatorDef->mOperatorDeclaration->mCommas[0];
  17443. Fail("Conversion operators must declare one parameter", refNode);
  17444. }
  17445. else if ((methodInstance->mMethodInfoEx == NULL) ||
  17446. (methodInstance->mMethodInfoEx->mMethodGenericArguments.IsEmpty()) ||
  17447. ((methodInstance->mIsUnspecialized) && (!methodInstance->mIsUnspecializedVariation)))
  17448. {
  17449. auto checkParam0 = mCurMethodInstance->GetParamType(0);
  17450. if ((checkParam0->IsRef()) && (!checkParam0->IsOut()))
  17451. checkParam0 = checkParam0->GetUnderlyingType();
  17452. if ((checkParam0 != mCurTypeInstance) && (!checkParam0->IsSelf()) &&
  17453. (mCurMethodInstance->mReturnType != mCurTypeInstance) && (!mCurMethodInstance->mReturnType->IsSelf()))
  17454. Fail("User-defined conversion must convert to or from the enclosing type", paramErrorRefNode);
  17455. if (checkParam0 == mCurMethodInstance->mReturnType)
  17456. Fail("User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type", operatorDef->mOperatorDeclaration->mReturnType);
  17457. // On type lookup error we default to 'object', so don't do the 'base class' error if that may have
  17458. // happened here
  17459. if ((!mHadBuildError) || ((mCurMethodInstance->mReturnType != mContext->mBfObjectType) && (checkParam0 != mContext->mBfObjectType)))
  17460. {
  17461. auto isToBase = TypeIsSubTypeOf(mCurTypeInstance->mBaseType, mCurMethodInstance->mReturnType->ToTypeInstance());
  17462. bool isFromBase = TypeIsSubTypeOf(mCurTypeInstance->mBaseType, checkParam0->ToTypeInstance());
  17463. if ((mCurTypeInstance->IsObject()) && (isToBase || isFromBase))
  17464. Fail("User-defined conversions to or from a base class are not allowed", paramErrorRefNode);
  17465. else if ((mCurTypeInstance->IsStruct()) && (isToBase))
  17466. Fail("User-defined conversions to a base struct are not allowed", paramErrorRefNode);
  17467. }
  17468. }
  17469. }
  17470. }
  17471. bool wantsDIData = (mBfIRBuilder->DbgHasInfo()) && (!methodDef->IsEmptyPartial()) && (!mBfIRBuilder->mIgnoreWrites) && (mHasFullDebugInfo);
  17472. if (methodDef->mMethodType == BfMethodType_Mixin)
  17473. wantsDIData = false;
  17474. if (mCurTypeInstance->IsUnspecializedType())
  17475. wantsDIData = false;
  17476. if ((mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType != BfMethodType_Ctor))
  17477. wantsDIData = false;
  17478. bool wantsDIVariables = wantsDIData;
  17479. if (methodDef->mIsExtern)
  17480. wantsDIVariables = false;
  17481. SizedArray<BfIRMDNode, 8> diParams;
  17482. diParams.push_back(mBfIRBuilder->DbgGetType(methodInstance->mReturnType));
  17483. bool isThisStruct = mCurTypeInstance->IsStruct() && !mCurTypeInstance->IsTypedPrimitive();
  17484. BfType* thisType = NULL;
  17485. if (!methodDef->mIsStatic)
  17486. {
  17487. if ((methodState.mClosureState != NULL) && (methodState.mClosureState->mClosureType != NULL))
  17488. thisType = methodState.mClosureState->mClosureType;
  17489. else
  17490. thisType = mCurTypeInstance;
  17491. }
  17492. PopulateType(methodInstance->mReturnType, BfPopulateType_Data);
  17493. ProcessMethod_SetupParams(methodInstance, thisType, wantsDIData, &diParams);
  17494. //////////////////////////////////////////////////////////////////////////
  17495. //
  17496. {
  17497. if (methodDeclaration != NULL)
  17498. UpdateSrcPos(methodDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  17499. else if (methodDef->mBody != NULL)
  17500. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  17501. else if ((methodDef->mDeclaringType != NULL) && (methodDef->mDeclaringType->GetRefNode() != NULL))
  17502. UpdateSrcPos(methodDef->mDeclaringType->GetRefNode(), BfSrcPosFlag_NoSetDebugLoc);
  17503. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  17504. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  17505. }
  17506. BfIRMDNode diFunction;
  17507. if (wantsDIData)
  17508. {
  17509. BP_ZONE("BfModule::DoMethodDeclaration.DISetup");
  17510. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParams);
  17511. int defLine = mCurFilePosition.mCurLine;
  17512. if (mDICompileUnit)
  17513. {
  17514. int flags = 0;
  17515. BfIRMDNode funcScope = mBfIRBuilder->DbgGetTypeInst(mCurTypeInstance);
  17516. if (methodDef->mProtection == BfProtection_Public)
  17517. flags = llvm::DINode::FlagPublic;
  17518. else if (methodDef->mProtection == BfProtection_Protected)
  17519. flags = llvm::DINode::FlagProtected;
  17520. else
  17521. flags = llvm::DINode::FlagPrivate;
  17522. if (methodDef->mIsOverride)
  17523. {
  17524. //flags |= llvm::DINode::FlagVirtual;
  17525. }
  17526. else if (methodDef->mIsVirtual)
  17527. flags |= llvm::DINode::FlagIntroducedVirtual;
  17528. if ((methodDef->mIsStatic) || (methodDef->mMethodType == BfMethodType_Mixin))
  17529. flags |= llvm::DINode::FlagStaticMember;
  17530. else
  17531. {
  17532. if ((mCurTypeInstance->IsValuelessType()) ||
  17533. ((!mIsComptimeModule) && (mCurTypeInstance->IsSplattable())))
  17534. flags |= llvm::DINode::FlagStaticMember;
  17535. }
  17536. flags |= llvm::DINode::FlagPrototyped;
  17537. if (methodDef->mMethodType == BfMethodType_Ctor)
  17538. {
  17539. flags |= llvm::DINode::FlagArtificial;
  17540. }
  17541. auto llvmFunction = methodInstance->mIRFunction;
  17542. SizedArray<BfIRMDNode, 1> genericArgs;
  17543. SizedArray<BfIRValue, 1> genericConstValueArgs;
  17544. String methodName;
  17545. if (methodInstance->GetForeignType() != NULL)
  17546. {
  17547. methodName += TypeToString(methodInstance->GetForeignType());
  17548. methodName += ".";
  17549. }
  17550. if (methodInstance->GetExplicitInterface() != NULL)
  17551. {
  17552. methodName += TypeToString(methodInstance->GetExplicitInterface());
  17553. methodName += ".";
  17554. }
  17555. methodName += methodDef->mName;
  17556. if (methodInstance->GetNumGenericArguments() != 0)
  17557. {
  17558. for (auto genericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  17559. {
  17560. if (genericArg->IsConstExprValue())
  17561. {
  17562. BfConstExprValueType* constExprValueType = (BfConstExprValueType*)genericArg;
  17563. while (genericConstValueArgs.size() < genericArgs.size())
  17564. genericConstValueArgs.push_back(BfIRValue());
  17565. genericConstValueArgs.push_back(mBfIRBuilder->CreateConst(BfTypeCode_UInt64, constExprValueType->mValue.mUInt64));
  17566. genericArgs.push_back(mBfIRBuilder->DbgGetType(GetPrimitiveType(BfTypeCode_Int64)));
  17567. }
  17568. else
  17569. genericArgs.push_back(mBfIRBuilder->DbgGetType(genericArg));
  17570. }
  17571. methodName += "<";
  17572. for (int i = 0; i < (int)methodInstance->mMethodInfoEx->mMethodGenericArguments.size(); i++)
  17573. {
  17574. if (i > 0)
  17575. methodName += ", ";
  17576. BfType* type = methodInstance->mMethodInfoEx->mMethodGenericArguments[i];
  17577. methodName += TypeToString(type);
  17578. }
  17579. methodName += ">";
  17580. }
  17581. if ((methodName.empty()) && (methodDeclaration != NULL))
  17582. {
  17583. if (auto operatorDecl = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  17584. {
  17585. methodName += "operator";
  17586. if (operatorDecl->mIsConvOperator)
  17587. {
  17588. methodName += " ";
  17589. methodName += TypeToString(methodInstance->mReturnType);
  17590. }
  17591. else if (operatorDecl->mOpTypeToken != NULL)
  17592. methodName += operatorDecl->mOpTypeToken->ToString();
  17593. }
  17594. }
  17595. if (methodDef->mCheckedKind == BfCheckedKind_Checked)
  17596. methodName += "$CHK";
  17597. else if (methodDef->mCheckedKind == BfCheckedKind_Unchecked)
  17598. methodName += "$UCHK";
  17599. methodState.mDIFile = mCurFilePosition.mFileInstance->mDIFile;
  17600. // diFunction = mBfIRBuilder->DbgCreateMethod(funcScope, methodName, mangledName, methodState.mDIFile,
  17601. // defLine + 1, diFuncType, false, true,
  17602. // (methodInstance->mVirtualTableIdx != -1) ? llvm::dwarf::DW_VIRTUALITY_virtual : llvm::dwarf::DW_VIRTUALITY_none,
  17603. // (methodInstance->mVirtualTableIdx != -1) ? methodInstance->DbgGetVirtualMethodNum() : 0,
  17604. // nullptr, flags, IsOptimized(), llvmFunction, genericArgs, genericConstValueArgs);
  17605. diFunction = mBfIRBuilder->DbgCreateMethod(funcScope, methodName, mangledName, methodState.mDIFile,
  17606. defLine + 1, diFuncType, false, true,
  17607. llvm::dwarf::DW_VIRTUALITY_none,
  17608. 0,
  17609. BfIRMDNode(), flags, IsOptimized(), llvmFunction, genericArgs, genericConstValueArgs);
  17610. }
  17611. else
  17612. {
  17613. methodState.mDIFile = mCurFilePosition.mFileInstance->mDIFile;
  17614. }
  17615. }
  17616. //////////////////////////////////////////////////////////////////////////
  17617. // Head and Init get rolled into Entry afterwards.
  17618. methodState.mIRFunction = methodInstance->mIRFunction;
  17619. methodState.mIRHeadBlock = mBfIRBuilder->CreateBlock("head", true);
  17620. methodState.mIRInitBlock = mBfIRBuilder->CreateBlock("init", true);
  17621. methodState.mIREntryBlock = mBfIRBuilder->CreateBlock("entry", true);
  17622. methodState.mCurScope->mDIScope = diFunction;
  17623. auto llvmEntryBlock = methodState.mIREntryBlock;
  17624. mBfIRBuilder->SetInsertPoint(llvmEntryBlock);
  17625. if (methodDef->mName == "__MALFORMED")
  17626. {
  17627. auto newBlock = mBfIRBuilder->CreateBlock("malformed", true);
  17628. mBfIRBuilder->SetInsertPoint(newBlock);
  17629. }
  17630. if (methodDef->mBody != NULL)
  17631. {
  17632. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  17633. }
  17634. else if ((mHasFullDebugInfo) && (diFunction) && (typeDef->mTypeDeclaration != NULL))
  17635. {
  17636. // We want to be able to step into delegate invokes -- we actually step over them
  17637. if (methodDef->mName != "Invoke")
  17638. {
  17639. UpdateSrcPos(methodDef->mDeclaringType->GetRefNode());
  17640. mBfIRBuilder->DbgCreateAnnotation(diFunction, "StepOver", GetConstValue32(1));
  17641. }
  17642. }
  17643. // Clear out DebugLoc - to mark the ".addr" code as part of prologue
  17644. mBfIRBuilder->ClearDebugLocation();
  17645. bool isTypedPrimitiveFunc = mCurTypeInstance->IsTypedPrimitive() && (methodDef->mMethodType != BfMethodType_Ctor);
  17646. int irParamCount = methodInstance->GetIRFunctionParamCount(this);
  17647. if (methodInstance->GetImportKind() != BfImportKind_Import_Dynamic)
  17648. {
  17649. int localIdx = 0;
  17650. int argIdx = 0;
  17651. Array<BfIRValue> splatAddrValues;
  17652. for ( ; argIdx < irParamCount; localIdx++)
  17653. {
  17654. bool isThis = ((localIdx == 0) && (!mCurMethodInstance->mMethodDef->mIsStatic));
  17655. if ((isThis) && (thisType->IsValuelessType()))
  17656. isThis = false;
  17657. if ((!mIsComptimeModule) && (methodInstance->GetStructRetIdx() == argIdx))
  17658. {
  17659. argIdx++;
  17660. if (argIdx == irParamCount)
  17661. break;
  17662. }
  17663. BfLocalVariable* paramVar = NULL;
  17664. while (true)
  17665. {
  17666. BF_ASSERT(localIdx < methodState.mLocals.size());
  17667. paramVar = methodState.mLocals[localIdx];
  17668. if ((paramVar->mCompositeCount == -1) &&
  17669. (!paramVar->mIsConst) &&
  17670. ((!paramVar->mResolvedType->IsValuelessType()) || (paramVar->mResolvedType->IsMethodRef())))
  17671. break;
  17672. localIdx++;
  17673. }
  17674. if ((isThis) && (mCurTypeInstance->IsValueType()) && (methodDef->mMethodType != BfMethodType_Ctor) && (!methodDef->HasNoThisSplat()))
  17675. {
  17676. paramVar->mIsReadOnly = true;
  17677. }
  17678. bool wantsAddr = (wantsDIVariables) || (!paramVar->mIsReadOnly) ||
  17679. ((!mIsComptimeModule) && (paramVar->mResolvedType->GetLoweredType(BfTypeUsage_Parameter)));
  17680. if (paramVar->mResolvedType->IsMethodRef())
  17681. wantsAddr = false;
  17682. // if ((methodDef->mHasAppend) && (argIdx == 1))
  17683. // {
  17684. // BF_ASSERT(paramVar->mName == "appendIdx");
  17685. // wantsAddr = true;
  17686. // }
  17687. if (paramVar->mIsSplat)
  17688. {
  17689. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  17690. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  17691. BfTypeUtils::SplatIterate([&](BfType* checkType)
  17692. {
  17693. BfIRType splatIRType;
  17694. if (checkType->IsComposite())
  17695. splatIRType = mBfIRBuilder->MapType(CreatePointerType(checkType));
  17696. else
  17697. splatIRType = mBfIRBuilder->MapType(checkType);
  17698. auto allocaInst = mBfIRBuilder->CreateAlloca(splatIRType);
  17699. mBfIRBuilder->SetAllocaAlignment(allocaInst, checkType->mAlign);
  17700. if (!paramVar->mAddr)
  17701. paramVar->mAddr = allocaInst;
  17702. if (WantsLifetimes())
  17703. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  17704. splatAddrValues.push_back(allocaInst);
  17705. }, paramVar->mResolvedType);
  17706. mBfIRBuilder->SetInsertPoint(prevInsert);
  17707. }
  17708. else if (isThis)
  17709. {
  17710. if (wantsAddr)
  17711. {
  17712. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  17713. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  17714. BfIRType thisAddrType = mBfIRBuilder->MapType(thisType);
  17715. if (paramVar->mIsSplat)
  17716. {
  17717. //
  17718. }
  17719. else
  17720. {
  17721. bool wantPtr = (thisType->IsComposite()) && (!paramVar->mIsLowered);
  17722. if ((thisType->IsTypedPrimitive()) && (methodDef->HasNoThisSplat()))
  17723. wantPtr = true;
  17724. if (wantPtr)
  17725. {
  17726. thisAddrType = mBfIRBuilder->MapTypeInstPtr(thisType->ToTypeInstance());
  17727. }
  17728. auto allocaInst = mBfIRBuilder->CreateAlloca(thisAddrType);
  17729. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  17730. mBfIRBuilder->SetAllocaAlignment(allocaInst, mSystem->mPtrSize);
  17731. paramVar->mAddr = allocaInst;
  17732. if (WantsLifetimes())
  17733. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  17734. }
  17735. mBfIRBuilder->SetInsertPoint(prevInsert);
  17736. }
  17737. }
  17738. else if ((!isThis) && ((paramVar->mIsStruct) || (paramVar->mResolvedType->IsRef())))
  17739. {
  17740. // Address doesn't change so we don't have to alloca it
  17741. BfIRType allocType;
  17742. int alignSize = mSystem->mPtrSize;
  17743. if (paramVar->mResolvedType->IsRef())
  17744. {
  17745. allocType = mBfIRBuilder->MapType(paramVar->mResolvedType);
  17746. }
  17747. else if ((paramVar->mIsSplat) || (paramVar->mIsLowered))
  17748. {
  17749. allocType = mBfIRBuilder->MapType(paramVar->mResolvedType);
  17750. alignSize = paramVar->mResolvedType->mAlign;
  17751. }
  17752. else
  17753. {
  17754. paramVar->mHasLocalStructBacking = true;
  17755. auto typeInst = paramVar->mResolvedType->ToTypeInstance();
  17756. if (typeInst != NULL)
  17757. allocType = mBfIRBuilder->MapTypeInstPtr(paramVar->mResolvedType->ToTypeInstance());
  17758. else
  17759. allocType = mBfIRBuilder->MapType(CreatePointerType(paramVar->mResolvedType));
  17760. }
  17761. if (wantsAddr)
  17762. {
  17763. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  17764. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  17765. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  17766. auto allocaInst = mBfIRBuilder->CreateAlloca(allocType);
  17767. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  17768. mBfIRBuilder->SetAllocaAlignment(allocaInst, alignSize);
  17769. paramVar->mAddr = allocaInst;
  17770. mBfIRBuilder->SetInsertPoint(prevInsert);
  17771. if (WantsLifetimes())
  17772. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  17773. }
  17774. }
  17775. else if (wantsAddr)
  17776. {
  17777. auto allocaInst = CreateAlloca(paramVar->mResolvedType);
  17778. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  17779. paramVar->mAddr = allocaInst;
  17780. }
  17781. if (paramVar->mIsSplat)
  17782. {
  17783. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  17784. }
  17785. else if (paramVar->mIsLowered)
  17786. {
  17787. BfTypeCode loweredTypeCode = BfTypeCode_None;
  17788. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  17789. paramVar->mResolvedType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2);
  17790. argIdx++;
  17791. if (loweredTypeCode2 != BfTypeCode_None)
  17792. argIdx++;
  17793. }
  17794. else
  17795. {
  17796. argIdx++;
  17797. }
  17798. }
  17799. if (methodDef->mBody != NULL)
  17800. UpdateSrcPos(methodDef->mBody);
  17801. else if ((methodDef->mDeclaringType != NULL) && (methodDef->mDeclaringType->GetRefNode() != NULL))
  17802. UpdateSrcPos(methodDef->mDeclaringType->GetRefNode());
  17803. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  17804. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration);
  17805. localIdx = 0;
  17806. argIdx = 0;
  17807. int splatAddrIdx = 0;
  17808. while (localIdx < (int)methodState.mLocals.size())
  17809. {
  17810. if ((!mIsComptimeModule) && (argIdx == methodInstance->GetStructRetIdx()))
  17811. argIdx++;
  17812. int curLocalIdx = localIdx++;
  17813. BfLocalVariable* paramVar = methodState.mLocals[curLocalIdx];
  17814. if (paramVar->mIsConst)
  17815. continue;
  17816. if (!paramVar->IsParam())
  17817. continue;
  17818. if (paramVar->mCompositeCount != -1)
  17819. continue;
  17820. bool isThis = ((curLocalIdx == 0) && (!mCurMethodInstance->mMethodDef->mIsStatic));
  17821. if ((isThis) && (thisType->IsValuelessType()))
  17822. isThis = false;
  17823. if (paramVar->mValue.IsArg())
  17824. BF_ASSERT(paramVar->mValue.mId == argIdx);
  17825. BfIRMDNode diVariable;
  17826. if (wantsDIData)
  17827. {
  17828. String paramName = paramVar->mName;
  17829. BfIRMDNode diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  17830. if (isThis)
  17831. {
  17832. if ((mCurMethodState->mClosureState != NULL) && (mCurMethodState->mClosureState->mClosureType != NULL))
  17833. paramName = "__closure";
  17834. if ((paramVar->mResolvedType->IsValueType()) && (!paramVar->mIsSplat) && (!paramVar->mIsLowered))
  17835. {
  17836. diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  17837. bool wantRef = paramVar->mResolvedType->IsComposite();
  17838. if ((paramVar->mResolvedType->IsTypedPrimitive()) && (methodDef->HasNoThisSplat()))
  17839. wantRef = true;
  17840. if (wantRef)
  17841. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  17842. }
  17843. else if (!paramVar->mResolvedType->IsValueType())
  17844. {
  17845. diType = mBfIRBuilder->DbgCreateArtificialType(diType);
  17846. }
  17847. }
  17848. else
  17849. {
  17850. if ((paramVar->mResolvedType->IsComposite()) && (!paramVar->mIsSplat) && (!paramVar->mIsLowered))
  17851. {
  17852. diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  17853. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  17854. diType = mBfIRBuilder->DbgCreateConstType(diType);
  17855. }
  17856. }
  17857. if (!paramVar->mIsSplat)
  17858. {
  17859. if ((paramVar->mParamIdx >= 0) && (paramVar->mParamIdx < methodInstance->mDefaultValues.mSize))
  17860. {
  17861. auto defaultValue = methodInstance->mDefaultValues[paramVar->mParamIdx];
  17862. auto constant = mCurTypeInstance->mConstHolder->GetConstant(defaultValue.mValue);
  17863. if ((constant != NULL) &&
  17864. ((BfIRConstHolder::IsIntable(constant->mTypeCode)) || (BfIRConstHolder::IsFloat(constant->mTypeCode))))
  17865. {
  17866. int64 writeVal = constant->mInt64;
  17867. if (constant->mTypeCode == BfTypeCode_Float)
  17868. {
  17869. // We need to do this because Singles are stored in mDouble, so we need to reduce here
  17870. float floatVal = (float)constant->mDouble;
  17871. writeVal = *(uint32*)&floatVal;
  17872. }
  17873. if (writeVal < 0)
  17874. paramName += StrFormat("$_%llu", -writeVal);
  17875. else
  17876. paramName += StrFormat("$%llu", writeVal);
  17877. }
  17878. }
  17879. if (paramVar->mResolvedType->IsValuelessType())
  17880. {
  17881. diVariable = mBfIRBuilder->DbgCreateAutoVariable(diFunction,
  17882. paramName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  17883. }
  17884. else if (paramVar->mIsImplicitParam)
  17885. {
  17886. // Annotate this specially?
  17887. diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  17888. paramName, argIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, true, 0);
  17889. }
  17890. else
  17891. {
  17892. diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  17893. paramName, argIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, true, 0);
  17894. }
  17895. paramVar->mDbgVarInst = diVariable;
  17896. }
  17897. else if ((paramVar->mIsSplat) && (paramVar->mResolvedType->GetSplatCount() == 0))
  17898. {
  17899. // if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables))
  17900. // {
  17901. // // Only add this placeholder if we don't have any values
  17902. // auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  17903. // paramName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  17904. // mBfIRBuilder->DbgInsertValueIntrinsic(GetConstValue(0), diVariable);
  17905. // }
  17906. }
  17907. }
  17908. bool isTypedPrimCtor = mCurTypeInstance->IsTypedPrimitive() && (methodDef->mMethodType == BfMethodType_Ctor);
  17909. if ((!paramVar->mParamFailed) && (paramVar->mAddr))
  17910. {
  17911. // Write our argument value into the .addr
  17912. mBfIRBuilder->ClearDebugLocation();
  17913. if (paramVar->mIsSplat)
  17914. {
  17915. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  17916. //
  17917. }
  17918. else
  17919. {
  17920. bool handled = false;
  17921. if (paramVar->mIsLowered)
  17922. {
  17923. BfTypeCode loweredTypeCode = BfTypeCode_None;
  17924. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  17925. if (paramVar->mResolvedType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2))
  17926. {
  17927. BfIRValue targetAddr = paramVar->mAddr;
  17928. bool isTempTarget = false;
  17929. int loweredSize = mBfIRBuilder->GetSize(loweredTypeCode) + mBfIRBuilder->GetSize(loweredTypeCode2);
  17930. if (paramVar->mResolvedType->mSize < loweredSize)
  17931. {
  17932. isTempTarget = true;
  17933. targetAddr = CreateAlloca(GetPrimitiveType(BfTypeCode_Int8), true, NULL, GetConstValue(loweredSize));
  17934. mBfIRBuilder->SetAllocaAlignment(targetAddr,
  17935. BF_MAX(paramVar->mResolvedType->mAlign,
  17936. BF_MAX(mBfIRBuilder->GetSize(loweredTypeCode), mBfIRBuilder->GetSize(loweredTypeCode2))));
  17937. }
  17938. // We have a lowered type coming in, so we have to cast the .addr before storing
  17939. auto primType = mBfIRBuilder->GetPrimitiveType(loweredTypeCode);
  17940. auto primPtrType = mBfIRBuilder->GetPointerTo(primType);
  17941. auto primPtrVal = mBfIRBuilder->CreateBitCast(targetAddr, primPtrType);
  17942. mBfIRBuilder->CreateAlignedStore(paramVar->mValue, primPtrVal, mCurTypeInstance->mAlign);
  17943. if (loweredTypeCode2 != BfTypeCode_None)
  17944. {
  17945. auto primType2 = mBfIRBuilder->GetPrimitiveType(loweredTypeCode2);
  17946. auto primPtrType2 = mBfIRBuilder->GetPointerTo(primType2);
  17947. BfIRValue primPtrVal2;
  17948. if (mBfIRBuilder->GetSize(loweredTypeCode) < mBfIRBuilder->GetSize(loweredTypeCode2))
  17949. primPtrVal2 = mBfIRBuilder->CreateInBoundsGEP(mBfIRBuilder->CreateBitCast(primPtrVal, primPtrType2), 1);
  17950. else
  17951. primPtrVal2 = mBfIRBuilder->CreateBitCast(mBfIRBuilder->CreateInBoundsGEP(primPtrVal, 1), primPtrType2);
  17952. mBfIRBuilder->CreateStore(mBfIRBuilder->GetArgument(argIdx + 1), primPtrVal2);
  17953. }
  17954. if (isTempTarget)
  17955. {
  17956. auto castedTempPtr = mBfIRBuilder->CreateBitCast(targetAddr, mBfIRBuilder->MapType(CreatePointerType(paramVar->mResolvedType)));
  17957. auto tempVal = mBfIRBuilder->CreateAlignedLoad(castedTempPtr, paramVar->mResolvedType->mAlign);
  17958. mBfIRBuilder->CreateAlignedStore(tempVal, paramVar->mAddr, paramVar->mResolvedType->mAlign);
  17959. }
  17960. // We don't want to allow directly using value
  17961. paramVar->mValue = BfIRValue();
  17962. handled = true;
  17963. }
  17964. else
  17965. {
  17966. BF_ASSERT("Expected lowered");
  17967. }
  17968. }
  17969. if (!handled)
  17970. mBfIRBuilder->CreateAlignedStore(paramVar->mValue, paramVar->mAddr, paramVar->mResolvedType->mAlign);
  17971. }
  17972. }
  17973. if (methodDef->mBody != NULL)
  17974. UpdateSrcPos(methodDef->mBody);
  17975. else if (methodDef->mDeclaringType->mTypeDeclaration != NULL)
  17976. UpdateSrcPos(methodDef->mDeclaringType->mTypeDeclaration);
  17977. else if (methodDeclaration == NULL)
  17978. UseDefaultSrcPos();
  17979. // Write our argument value into the .addr
  17980. if (paramVar->mIsSplat)
  17981. {
  17982. int splatComponentIdx = 0;
  17983. auto curArgIdx = argIdx;
  17984. auto _FinishSplats = [&] (BfType* checkType, const StringImpl& name)
  17985. {
  17986. BfIRValue splatAddrValue = splatAddrValues[splatAddrIdx++];
  17987. methodState.mSplatDecompAddrs.push_back(splatAddrValue);
  17988. auto storeInst = mBfIRBuilder->CreateAlignedStore(mBfIRBuilder->GetArgument(curArgIdx), splatAddrValue, checkType->mAlign);
  17989. mBfIRBuilder->ClearDebugLocation(storeInst);
  17990. if (wantsDIData)
  17991. {
  17992. BfIRMDNode diType;
  17993. if (checkType->IsComposite())
  17994. diType = mBfIRBuilder->DbgGetType(CreateRefType(checkType));
  17995. else
  17996. diType = mBfIRBuilder->DbgGetType(checkType);
  17997. auto diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  17998. name, curArgIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  17999. if (wantsDIVariables)
  18000. {
  18001. mBfIRBuilder->DbgInsertDeclare(splatAddrValue, diVariable);
  18002. }
  18003. }
  18004. curArgIdx++;
  18005. splatComponentIdx++;
  18006. };
  18007. std::function<void(BfType*, const StringImpl&)> _FinishSplatsIterate = [&](BfType* checkType, const StringImpl& name)
  18008. {
  18009. if (checkType->IsStruct())
  18010. {
  18011. auto checkTypeInstance = checkType->ToTypeInstance();
  18012. if (checkTypeInstance->mBaseType != NULL)
  18013. {
  18014. _FinishSplatsIterate(checkTypeInstance->mBaseType, name + "$b");
  18015. }
  18016. if (checkTypeInstance->mIsUnion)
  18017. {
  18018. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  18019. if (!unionInnerType->IsValuelessType())
  18020. {
  18021. _FinishSplatsIterate(unionInnerType, name + "$u");
  18022. }
  18023. if (checkTypeInstance->IsEnum())
  18024. {
  18025. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  18026. _FinishSplatsIterate(dscrType, name + "$d");
  18027. }
  18028. }
  18029. else
  18030. {
  18031. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  18032. {
  18033. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  18034. auto fieldDef = fieldInstance->GetFieldDef();
  18035. if (fieldInstance->mDataIdx >= 0)
  18036. {
  18037. _FinishSplatsIterate(fieldInstance->GetResolvedType(), name + "$m$" + fieldDef->mName);
  18038. }
  18039. }
  18040. }
  18041. }
  18042. else if (checkType->IsMethodRef())
  18043. {
  18044. auto methodRefType = (BfMethodRefType*)checkType;
  18045. BfMethodInstance* methodInstance = methodRefType->mMethodRef;
  18046. // int implicitParamCount = methodInstance->GetImplicitParamCount();
  18047. // for (int implicitParamIdx = methodInstance->HasThis() ? -1 : 0; implicitParamIdx < implicitParamCount; implicitParamIdx++)
  18048. // {
  18049. // auto paramType = methodInstance->GetParamType(implicitParamIdx);
  18050. // if (!paramType->IsValuelessType())
  18051. // _FinishSplats(paramType, name + "$m$" + methodInstance->GetParamName(implicitParamIdx));
  18052. // }
  18053. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  18054. {
  18055. int paramIdx = methodRefType->GetParamIdxFromDataIdx(dataIdx);
  18056. String paramName = methodInstance->GetParamName(paramIdx);
  18057. if (paramName == "this")
  18058. paramName = "__this";
  18059. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  18060. {
  18061. _FinishSplatsIterate(methodRefType->GetCaptureType(dataIdx), name + "$m$" + paramName);
  18062. }
  18063. else
  18064. {
  18065. _FinishSplats(methodRefType->GetCaptureType(dataIdx), name + "$m$" + paramName);
  18066. }
  18067. }
  18068. }
  18069. else if (!checkType->IsValuelessType())
  18070. {
  18071. _FinishSplats(checkType, name);
  18072. }
  18073. };
  18074. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  18075. if (!paramVar->mConstValue)
  18076. _FinishSplatsIterate(paramVar->mResolvedType, "$" + paramVar->mName);
  18077. }
  18078. BfIRValue declareCall;
  18079. if (diVariable)
  18080. {
  18081. if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables))
  18082. {
  18083. if (!paramVar->mAddr)
  18084. {
  18085. if ((!paramVar->mValue) || (paramVar->mValue.IsFake()))
  18086. {
  18087. if ((!paramVar->mIsThis) && (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU)) // DWARF chokes on this:
  18088. {
  18089. // We don't need to set the location for this
  18090. mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  18091. }
  18092. }
  18093. else
  18094. declareCall = mBfIRBuilder->DbgInsertDeclare(paramVar->mValue, diVariable);
  18095. }
  18096. else
  18097. {
  18098. declareCall = mBfIRBuilder->DbgInsertDeclare(paramVar->mAddr, diVariable);
  18099. }
  18100. }
  18101. }
  18102. if ((isThis) && (!paramVar->mIsSplat) && (paramVar->mAddr))
  18103. {
  18104. // We don't allow actually assignment to "this", so we just do a single load
  18105. // Keep in mind we don't use the ACTUAL mValue value because that's a register, but
  18106. // we need to store it in the stack frame for debugging purposes
  18107. auto loadedThis = mBfIRBuilder->CreateAlignedLoad(paramVar->mAddr/*, "this"*/, paramVar->mResolvedType->mAlign);
  18108. mBfIRBuilder->ClearDebugLocation(loadedThis);
  18109. paramVar->mValue = loadedThis;
  18110. }
  18111. if ((wantsDIData) && (declareCall))
  18112. mBfIRBuilder->UpdateDebugLocation(declareCall);
  18113. if (paramVar->mIsSplat)
  18114. {
  18115. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  18116. }
  18117. else if (paramVar->mIsLowered)
  18118. {
  18119. argIdx++;
  18120. BfTypeCode loweredTypeCode = BfTypeCode_None;
  18121. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  18122. paramVar->mResolvedType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2);
  18123. if (loweredTypeCode2 != BfTypeCode_None)
  18124. argIdx++;
  18125. }
  18126. else if (!paramVar->mResolvedType->IsValuelessType())
  18127. {
  18128. argIdx++;
  18129. }
  18130. }
  18131. if (wantsDIData)
  18132. {
  18133. BF_ASSERT(splatAddrIdx == (int)splatAddrValues.size());
  18134. }
  18135. }
  18136. for (int varIdx = 0; varIdx < (int)mCurMethodState->mLocals.size(); varIdx++)
  18137. {
  18138. auto paramVar = mCurMethodState->mLocals[varIdx];
  18139. // 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
  18140. // splat member. If the "splat" is valueless then we do create a placeholder, but further up in this method
  18141. // if (paramVar->mIsSplat)
  18142. // {
  18143. // if (wantsDIVariables)
  18144. // {
  18145. // auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(diFunction, paramVar->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(paramVar->mResolvedType));
  18146. // mBfIRBuilder->DbgInsertValueIntrinsic(mBfIRBuilder->CreateConst(BfTypeCode_Int64, 0), diVariable);
  18147. // }
  18148. // }
  18149. if (paramVar->mResolvedType->IsValuelessType())
  18150. {
  18151. if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables) && (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU)) // DWARF chokes on this:
  18152. {
  18153. // Only add this placeholder if we don't have any values
  18154. auto diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  18155. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  18156. paramVar->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  18157. mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  18158. }
  18159. }
  18160. }
  18161. if (IsTargetingBeefBackend())
  18162. mCurMethodState->mCurScope->mValueScopeStart = mBfIRBuilder->CreateValueScopeStart();
  18163. if (methodState.mClosureState != NULL)
  18164. {
  18165. for (auto& constLocal : methodState.mClosureState->mConstLocals)
  18166. {
  18167. BfLocalVariable* localVar = new BfLocalVariable();
  18168. *localVar = constLocal;
  18169. localVar->mIsBumpAlloc = false;
  18170. AddLocalVariableDef(localVar, true);
  18171. }
  18172. }
  18173. bool wantsRemoveBody = false;
  18174. bool skipBody = false;
  18175. bool skipUpdateSrcPos = false;
  18176. bool skipEndChecks = false;
  18177. bool hasExternSpecifier = (methodDeclaration != NULL) && (methodDeclaration->mExternSpecifier != NULL) && (methodInstance->GetImportKind() != BfImportKind_Import_Dynamic);
  18178. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  18179. if ((methodDef != NULL) && (propertyDeclaration != NULL) && (propertyDeclaration->mExternSpecifier != NULL))
  18180. hasExternSpecifier = true;
  18181. // Allocate, clear, set classVData
  18182. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mIsStatic))
  18183. {
  18184. CreateStaticCtor();
  18185. }
  18186. else if ((mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType != BfMethodType_Ctor) && (methodDef->mName != BF_METHODNAME_DYNAMICCAST) && (methodDef->mName != BF_METHODNAME_DYNAMICCAST_INTERFACE))
  18187. {
  18188. skipBody = true;
  18189. skipEndChecks = true;
  18190. if (HasExecutedOutput())
  18191. {
  18192. // Clear out DebugLoc - to mark the ".addr" code as part of prologue
  18193. mBfIRBuilder->ClearDebugLocation();
  18194. BfBoxedType* boxedType = (BfBoxedType*) mCurTypeInstance;
  18195. BfTypeInstance* innerType = boxedType->mElementType->ToTypeInstance();
  18196. PopulateType(innerType, BfPopulateType_DataAndMethods);
  18197. mBfIRBuilder->PopulateType(mCurTypeInstance);
  18198. BfGetMethodInstanceFlags flags = BfGetMethodInstanceFlag_None;
  18199. if (methodInstance->mIsForeignMethodDef)
  18200. {
  18201. flags = BfGetMethodInstanceFlag_ForeignMethodDef;
  18202. }
  18203. BfTypeVector methodGenericArguments;
  18204. if (methodInstance->mMethodInfoEx != NULL)
  18205. methodGenericArguments = methodInstance->mMethodInfoEx->mMethodGenericArguments;
  18206. auto innerMethodInstance = GetMethodInstance(innerType, methodDef, methodGenericArguments, flags, methodInstance->GetForeignType());
  18207. if (innerMethodInstance.mMethodInstance->IsSkipCall())
  18208. {
  18209. if (!methodInstance->mReturnType->IsValuelessType())
  18210. {
  18211. auto retVal = GetDefaultValue(methodInstance->mReturnType);
  18212. CreateReturn(retVal);
  18213. }
  18214. else
  18215. mBfIRBuilder->CreateRetVoid();
  18216. }
  18217. else
  18218. {
  18219. auto innerMethodDef = innerMethodInstance.mMethodInstance->mMethodDef;
  18220. BF_ASSERT(innerMethodDef == methodDef);
  18221. SizedArray<BfIRValue, 8> innerParams;
  18222. BfExprEvaluator exprEvaluator(this);
  18223. if (!innerType->IsValuelessType())
  18224. {
  18225. BfIRValue thisValue = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, 1);
  18226. BfTypedValue innerVal(thisValue, innerType, true);
  18227. if (boxedType->IsBoxedStructPtr())
  18228. {
  18229. innerVal = LoadValue(innerVal);
  18230. innerVal = BfTypedValue(innerVal.mValue, innerType, true);
  18231. }
  18232. exprEvaluator.PushThis(NULL, innerVal, innerMethodInstance.mMethodInstance, innerParams);
  18233. }
  18234. for (int i = 1; i < (int)mCurMethodState->mLocals.size(); i++)
  18235. {
  18236. BfLocalVariable* localVar = mCurMethodState->mLocals[i];
  18237. BfTypedValue localVal = exprEvaluator.LoadLocal(localVar, true);
  18238. exprEvaluator.PushArg(localVal, innerParams);
  18239. }
  18240. if (!innerMethodInstance.mFunc)
  18241. {
  18242. BF_ASSERT(innerType->IsUnspecializedType());
  18243. }
  18244. else if ((!mIsComptimeModule) && (methodInstance->GetStructRetIdx() != -1))
  18245. {
  18246. mBfIRBuilder->PopulateType(methodInstance->mReturnType);
  18247. auto returnType = BfTypedValue(mBfIRBuilder->GetArgument(methodInstance->GetStructRetIdx()), methodInstance->mReturnType, true);
  18248. exprEvaluator.mReceivingValue = &returnType;
  18249. auto retVal = exprEvaluator.CreateCall(NULL, innerMethodInstance.mMethodInstance, innerMethodInstance.mFunc, true, innerParams, NULL, BfCreateCallFlags_TailCall);
  18250. BF_ASSERT(exprEvaluator.mReceivingValue == NULL); // Ensure it was actually used
  18251. mBfIRBuilder->CreateRetVoid();
  18252. }
  18253. else
  18254. {
  18255. mBfIRBuilder->PopulateType(methodInstance->mReturnType);
  18256. auto retVal = exprEvaluator.CreateCall(NULL, innerMethodInstance.mMethodInstance, innerMethodInstance.mFunc, true, innerParams, NULL, BfCreateCallFlags_TailCall);
  18257. if (mCurMethodInstance->mReturnType->IsValueType())
  18258. retVal = LoadValue(retVal);
  18259. CreateReturn(retVal.mValue);
  18260. }
  18261. }
  18262. }
  18263. mCurMethodState->SetHadReturn(true);
  18264. mCurMethodState->mLeftBlockUncond = true;
  18265. }
  18266. else if (methodDef->mMethodType == BfMethodType_CtorClear)
  18267. {
  18268. SetIllegalSrcPos();
  18269. mBfIRBuilder->ClearDebugLocation();
  18270. PopulateType(mCurTypeInstance, BfPopulateType_Data);
  18271. auto thisVal = GetThis();
  18272. int prevSize = 0;
  18273. if (mContext->mBfObjectType != NULL)
  18274. {
  18275. prevSize = mContext->mBfObjectType->mInstSize;
  18276. PopulateType(mContext->mBfObjectType);
  18277. // If we have object extensions, clear out starting at the extension
  18278. for (auto& fieldInstance : mContext->mBfObjectType->mFieldInstances)
  18279. {
  18280. if (fieldInstance.GetFieldDef()->mDeclaringType->IsExtension())
  18281. {
  18282. prevSize = fieldInstance.mDataOffset;
  18283. break;
  18284. }
  18285. }
  18286. }
  18287. auto int8PtrType = CreatePointerType(GetPrimitiveType(BfTypeCode_Int8));
  18288. int curSize = mCurTypeInstance->mInstSize;
  18289. if (curSize > prevSize)
  18290. {
  18291. auto int8PtrVal = mBfIRBuilder->CreateBitCast(thisVal.mValue, mBfIRBuilder->MapType(int8PtrType));
  18292. int8PtrVal = mBfIRBuilder->CreateInBoundsGEP(int8PtrVal, GetConstValue(prevSize));
  18293. mBfIRBuilder->CreateMemSet(int8PtrVal, GetConstValue8(0), GetConstValue(curSize - prevSize), GetConstValue(mCurTypeInstance->mInstAlign));
  18294. }
  18295. if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mIsComptimeModule))
  18296. {
  18297. auto useThis = mCurMethodState->mLocals[0]->mValue;
  18298. auto useThisType = mCurTypeInstance;
  18299. auto checkTypeInst = mCurTypeInstance;
  18300. while (checkTypeInst != NULL)
  18301. {
  18302. for (auto& fieldInstance : checkTypeInst->mFieldInstances)
  18303. {
  18304. auto fieldDef = fieldInstance.GetFieldDef();
  18305. if ((fieldDef == NULL) || (fieldDef->mIsStatic))
  18306. continue;
  18307. if (fieldInstance.IsAppendedObject())
  18308. {
  18309. if (checkTypeInst != useThisType)
  18310. {
  18311. useThis = mBfIRBuilder->CreateBitCast(useThis, mBfIRBuilder->MapType(checkTypeInst));
  18312. useThisType = checkTypeInst;
  18313. }
  18314. BfIRValue fieldAddr = mBfIRBuilder->CreateInBoundsGEP(useThis, 0, fieldInstance.mDataIdx);
  18315. auto int8PtrVal = mBfIRBuilder->CreateBitCast(fieldAddr, mBfIRBuilder->MapType(int8PtrType));
  18316. mBfIRBuilder->CreateStore(GetConstValue8(BfObjectFlag_Deleted), int8PtrVal);
  18317. }
  18318. }
  18319. checkTypeInst = checkTypeInst->mBaseType;
  18320. }
  18321. }
  18322. skipUpdateSrcPos = true;
  18323. }
  18324. else if (((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorNoBody)) && (!hasExternSpecifier))
  18325. {
  18326. EmitCtorBody(skipBody);
  18327. }
  18328. else if ((methodDef->mMethodType == BfMethodType_Dtor) && (!hasExternSpecifier))
  18329. {
  18330. EmitDtorBody();
  18331. skipBody = true;
  18332. }
  18333. if ((!mCurTypeInstance->IsBoxed()) && (methodDeclaration != NULL) && (methodDeclaration->mHadYield) && (methodDef->mBody != NULL))
  18334. {
  18335. EmitIteratorBlock(skipBody);
  18336. }
  18337. if (methodDef->mName == BF_METHODNAME_MARKMEMBERS)
  18338. {
  18339. // We need to be able to mark deleted objects
  18340. mCurMethodState->mIgnoreObjectAccessCheck = true;
  18341. }
  18342. auto customAttributes = methodInstance->GetCustomAttributes();
  18343. if (customAttributes != NULL)
  18344. {
  18345. if (customAttributes->Contains(mCompiler->mDisableObjectAccessChecksAttributeTypeDef))
  18346. mCurMethodState->mIgnoreObjectAccessCheck = true;
  18347. if (customAttributes->Contains(mCompiler->mDisableChecksAttributeTypeDef))
  18348. mCurMethodState->mDisableChecks = true;
  18349. }
  18350. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) && (!methodDef->mIsStatic) &&
  18351. ((methodInstance->mChainType == BfMethodChainType_ChainHead) || (methodInstance->mChainType == BfMethodChainType_None)))
  18352. {
  18353. // We chain even non-default ctors to the default ctors
  18354. auto defaultCtor = methodInstance;
  18355. if (defaultCtor->mChainType == BfMethodChainType_ChainHead)
  18356. CallChainedMethods(defaultCtor, false);
  18357. }
  18358. auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody);
  18359. if (!mCompiler->mHasRequiredTypes)
  18360. {
  18361. // Skip processing to avoid errors
  18362. }
  18363. else if (methodDef->mBody == NULL)
  18364. {
  18365. if (methodDeclaration != NULL)
  18366. {
  18367. if (auto operatorDeclaration = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  18368. {
  18369. if (operatorDeclaration->mIsConvOperator)
  18370. wantsRemoveBody = true;
  18371. }
  18372. }
  18373. bool isDllImport = false;
  18374. if ((importKind == BfImportKind_Import_Static) || (importKind == BfImportKind_Import_Dynamic))
  18375. {
  18376. if (importStrNum != -1)
  18377. {
  18378. if (importKind == BfImportKind_Import_Static)
  18379. {
  18380. if (!mImportFileNames.Contains(importStrNum))
  18381. {
  18382. mImportFileNames.Add(importStrNum);
  18383. }
  18384. }
  18385. }
  18386. }
  18387. else if (methodInstance->GetImportKind() == BfImportKind_Import_Dynamic)
  18388. {
  18389. CreateDllImportMethod();
  18390. }
  18391. else if (((mCurTypeInstance->mTypeDef->mIsDelegate) || (mCurTypeInstance->mTypeDef->mIsFunction)) &&
  18392. (methodDef->mName == "Invoke") && (methodDef->mMethodType == BfMethodType_Normal))
  18393. {
  18394. if (mCurTypeInstance->mTypeDef->mIsFunction)
  18395. {
  18396. // Emit nothing
  18397. }
  18398. else
  18399. {
  18400. CreateDelegateInvokeMethod();
  18401. mCurMethodState->SetHadReturn(true);
  18402. mCurMethodState->mLeftBlockUncond = true;
  18403. }
  18404. }
  18405. else if ((methodDef->mName == BF_METHODNAME_DYNAMICCAST) || (methodDef->mName == BF_METHODNAME_DYNAMICCAST_INTERFACE))
  18406. {
  18407. if (mCurTypeInstance->IsObject())
  18408. {
  18409. CreateDynamicCastMethod();
  18410. }
  18411. else
  18412. {
  18413. mBfIRBuilder->CreateRet(GetDefaultValue(methodInstance->mReturnType));
  18414. mCurMethodState->mHadReturn = true;
  18415. }
  18416. }
  18417. else if ((methodDef->mName == BF_METHODNAME_ENUM_HASFLAG) && (mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()))
  18418. {
  18419. BfIRValue ret;
  18420. if (mCurMethodState->mLocals[1]->mResolvedType != mCurTypeInstance)
  18421. {
  18422. // This can happen if we provide an invalid name
  18423. AssertErrorState();
  18424. ret = mBfIRBuilder->CreateRet(GetDefaultValue(GetPrimitiveType(BfTypeCode_Boolean)));
  18425. }
  18426. else
  18427. {
  18428. // Unfortunate DebugLoc shenanigans-
  18429. // 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,
  18430. // so we only set the loc on the CreateRet which gets inlined out
  18431. mBfIRBuilder->SaveDebugLocation();
  18432. mBfIRBuilder->ClearDebugLocation();
  18433. BfIRValue fromBool;
  18434. if (!mCurTypeInstance->IsTypedPrimitive())
  18435. {
  18436. fromBool = GetDefaultValue(methodInstance->mReturnType);
  18437. }
  18438. else
  18439. {
  18440. auto andResult = mBfIRBuilder->CreateAnd(mCurMethodState->mLocals[0]->mValue, mCurMethodState->mLocals[1]->mValue);
  18441. auto toBool = mBfIRBuilder->CreateCmpNE(andResult, GetDefaultValue(mCurMethodState->mLocals[0]->mResolvedType));
  18442. fromBool = mBfIRBuilder->CreateNumericCast(toBool, false, BfTypeCode_Boolean);
  18443. }
  18444. mBfIRBuilder->RestoreDebugLocation();
  18445. ret = mBfIRBuilder->CreateRet(fromBool);
  18446. //ExtendLocalLifetimes(0);
  18447. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  18448. }
  18449. mCurMethodState->SetHadReturn(true);
  18450. mCurMethodState->mLeftBlockUncond = true;
  18451. }
  18452. else if (((methodDef->mName == BF_METHODNAME_ENUM_GETUNDERLYINGREF) || (methodDef->mName == BF_METHODNAME_ENUM_GETUNDERLYING)) &&
  18453. (mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()))
  18454. {
  18455. BfIRValue ret;
  18456. // Unfortunate DebugLoc shenanigans-
  18457. // 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,
  18458. // so we only set the loc on the CreateRet which gets inlined out
  18459. mBfIRBuilder->SaveDebugLocation();
  18460. mBfIRBuilder->ClearDebugLocation();
  18461. BfIRValue fromBool;
  18462. mBfIRBuilder->RestoreDebugLocation();
  18463. ret = mBfIRBuilder->CreateRet(GetThis().mValue);
  18464. //ExtendLocalLifetimes(0);
  18465. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  18466. mCurMethodState->SetHadReturn(true);
  18467. mCurMethodState->mLeftBlockUncond = true;
  18468. }
  18469. else if ((mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()) && (methodDef->mName == BF_METHODNAME_TO_STRING))
  18470. {
  18471. auto enumType = ResolveTypeDef(mCompiler->mEnumTypeDef);
  18472. if (HasExecutedOutput())
  18473. {
  18474. EmitEnumToStringBody();
  18475. }
  18476. mBfIRBuilder->CreateRetVoid();
  18477. mCurMethodState->SetHadReturn(true);
  18478. mCurMethodState->mLeftBlockUncond = true;
  18479. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  18480. }
  18481. else if ((mCurTypeInstance->IsTuple()) && (!mCurTypeInstance->IsBoxed()) && (methodDef->mName == BF_METHODNAME_TO_STRING))
  18482. {
  18483. auto enumType = ResolveTypeDef(mCompiler->mEnumTypeDef);
  18484. if (HasExecutedOutput())
  18485. {
  18486. EmitTupleToStringBody();
  18487. }
  18488. mBfIRBuilder->CreateRetVoid();
  18489. mCurMethodState->SetHadReturn(true);
  18490. mCurMethodState->mLeftBlockUncond = true;
  18491. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  18492. }
  18493. else if (methodDef->mName == BF_METHODNAME_DEFAULT_EQUALS)
  18494. {
  18495. CreateValueTypeEqualsMethod(false);
  18496. skipBody = true;
  18497. skipEndChecks = true;
  18498. }
  18499. else if (methodDef->mName == BF_METHODNAME_DEFAULT_STRICT_EQUALS)
  18500. {
  18501. CreateValueTypeEqualsMethod(true);
  18502. skipBody = true;
  18503. skipEndChecks = true;
  18504. }
  18505. else if ((methodDef->mName == BF_METHODNAME_EQUALS) && (typeDef->GetDefinition() == mCompiler->mValueTypeTypeDef))
  18506. {
  18507. CreateValueTypeEqualsMethod(false);
  18508. skipBody = true;
  18509. skipEndChecks = true;
  18510. }
  18511. else if ((methodDef->mName == BF_METHODNAME_EQUALS) && (mCurTypeInstance->IsDelegate()))
  18512. {
  18513. CreateDelegateEqualsMethod();
  18514. skipBody = true;
  18515. skipEndChecks = true;
  18516. }
  18517. else
  18518. {
  18519. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  18520. if ((propertyDeclaration != NULL) && (!typeDef->HasAutoProperty(propertyDeclaration)))
  18521. {
  18522. if ((!mCurTypeInstance->IsInterface()) && (!hasExternSpecifier))
  18523. Fail("Body expected", methodDef->mBody);
  18524. }
  18525. else if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  18526. {
  18527. if ((methodInstance->mReturnType->IsRef()) && (!methodDef->mIsMutating) && (mCurTypeInstance->IsValueType()))
  18528. Fail("Auto-implemented ref property getters must declare 'mut'", methodInstance->mMethodDef->GetRefNode());
  18529. if (methodInstance->mReturnType->IsValuelessType())
  18530. {
  18531. mBfIRBuilder->CreateRetVoid();
  18532. }
  18533. else if (HasExecutedOutput())
  18534. {
  18535. String autoPropName = typeDef->GetAutoPropertyName(propertyDeclaration);
  18536. BfFieldInstance* fieldInstance = GetFieldByName(mCurTypeInstance, autoPropName);
  18537. BfFieldDef* fieldDef = NULL;
  18538. if (fieldInstance != NULL)
  18539. fieldDef = fieldInstance->GetFieldDef();
  18540. BfType* retType = methodInstance->mReturnType;
  18541. if (retType->IsRef())
  18542. retType = retType->GetUnderlyingType();
  18543. if ((fieldInstance != NULL) && (fieldInstance->GetResolvedType() == retType) &&
  18544. ((fieldInstance->mDataIdx >= 0) || (fieldDef->IsNonConstStatic())))
  18545. {
  18546. BfTypedValue lookupValue;
  18547. if (fieldDef->IsNonConstStatic())
  18548. lookupValue = ReferenceStaticField(fieldInstance);
  18549. else if (mCurTypeInstance->IsObject())
  18550. lookupValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(GetThis().mValue, 0, fieldInstance->mDataIdx), fieldInstance->mResolvedType, true);
  18551. else
  18552. lookupValue = ExtractValue(GetThis(), fieldInstance, fieldInstance->mDataIdx);
  18553. if (methodInstance->mReturnType->IsRef())
  18554. {
  18555. if ((!lookupValue.IsAddr()) && (!lookupValue.mType->IsValuelessType()))
  18556. lookupValue = MakeAddressable(lookupValue);
  18557. }
  18558. else
  18559. lookupValue = LoadOrAggregateValue(lookupValue);
  18560. CreateReturn(lookupValue.mValue);
  18561. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  18562. }
  18563. else
  18564. {
  18565. // This can happen if we have two properties with the same name but different types
  18566. CreateReturn(GetDefaultValue(mCurMethodInstance->mReturnType));
  18567. EmitDefaultReturn();
  18568. }
  18569. }
  18570. else
  18571. {
  18572. CreateReturn(GetDefaultValue(mCurMethodInstance->mReturnType));
  18573. EmitDefaultReturn();
  18574. }
  18575. mCurMethodState->SetHadReturn(true);
  18576. }
  18577. else if (methodDef->mMethodType == BfMethodType_PropertySetter)
  18578. {
  18579. if ((!methodDef->mIsMutating) && (!methodDef->mIsStatic) && (mCurTypeInstance->IsValueType()))
  18580. {
  18581. Fail("Auto-setter must be marked as 'mut'", methodDef->GetRefNode(), true);
  18582. }
  18583. else if (!mCompiler->IsAutocomplete())
  18584. {
  18585. String autoPropName = typeDef->GetAutoPropertyName(propertyDeclaration);
  18586. BfFieldInstance* fieldInstance = GetFieldByName(mCurTypeInstance, autoPropName);
  18587. auto fieldDef = fieldInstance->GetFieldDef();
  18588. auto& lastParam = mCurMethodState->mLocals.back();
  18589. if ((fieldInstance != NULL) && (fieldInstance->GetResolvedType() == lastParam->mResolvedType) &&
  18590. ((fieldInstance->mDataIdx >= 0) || (fieldDef->IsNonConstStatic())))
  18591. {
  18592. BfIRValue lookupAddr;
  18593. if (fieldDef->IsNonConstStatic())
  18594. lookupAddr = ReferenceStaticField(fieldInstance).mValue;
  18595. else
  18596. {
  18597. auto thisValue = GetThis();
  18598. if (thisValue.IsSplat())
  18599. {
  18600. BFMODULE_FATAL(this, "Should not happen");
  18601. }
  18602. if (mCurTypeInstance->IsObject())
  18603. thisValue = LoadValue(thisValue);
  18604. lookupAddr = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInstance->mDataIdx);
  18605. }
  18606. BfExprEvaluator exprEvaluator(this);
  18607. auto localVal = exprEvaluator.LoadLocal(lastParam);
  18608. localVal = LoadOrAggregateValue(localVal);
  18609. if (!localVal.mType->IsValuelessType())
  18610. mBfIRBuilder->CreateAlignedStore(localVal.mValue, lookupAddr, localVal.mType->mAlign);
  18611. }
  18612. else if (!fieldInstance->mResolvedType->IsValuelessType())
  18613. {
  18614. // This can happen if we have two properties with the same name but different types
  18615. AssertErrorState();
  18616. }
  18617. }
  18618. }
  18619. else if ((methodDef->mName == BF_METHODNAME_MARKMEMBERS) || (methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC))
  18620. {
  18621. if (mCompiler->mOptions.mEnableRealtimeLeakCheck)
  18622. {
  18623. if (HasCompiledOutput())
  18624. EmitGCMarkMembers();
  18625. }
  18626. else if (!mCurTypeInstance->IsObject())
  18627. {
  18628. }
  18629. }
  18630. else if (methodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS)
  18631. {
  18632. if (mCompiler->mOptions.mEnableRealtimeLeakCheck)
  18633. {
  18634. if (HasCompiledOutput())
  18635. EmitGCFindTLSMembers();
  18636. }
  18637. }
  18638. }
  18639. }
  18640. else if (!skipBody)
  18641. {
  18642. bool isEmptyBodied = BfNodeDynCast<BfTokenNode>(methodDef->mBody) != NULL;
  18643. bool wantsRetVal = true;
  18644. if ((mIsComptimeModule) && (methodDef->mMethodType != BfMethodType_CtorCalcAppend))
  18645. wantsRetVal = false;
  18646. else if (mCurMethodInstance->mReturnType->IsVar())
  18647. wantsRetVal = false;
  18648. if ((!mCurMethodInstance->mReturnType->IsValuelessType()) && (!isEmptyBodied))
  18649. {
  18650. mBfIRBuilder->PopulateType(mCurMethodInstance->mReturnType);
  18651. if ((!mIsComptimeModule) && (mCurMethodInstance->GetStructRetIdx() != -1))
  18652. {
  18653. auto ptrType = CreatePointerType(mCurMethodInstance->mReturnType);
  18654. auto allocaInst = AllocLocalVariable(ptrType, "__return.addr", false);
  18655. auto storeInst = mBfIRBuilder->CreateAlignedStore(mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()), allocaInst, mCurMethodInstance->mReturnType->mAlign);
  18656. mBfIRBuilder->ClearDebugLocation(storeInst);
  18657. mCurMethodState->mRetValAddr = allocaInst;
  18658. }
  18659. else if (wantsRetVal)
  18660. {
  18661. auto allocaInst = AllocLocalVariable(mCurMethodInstance->mReturnType, "__return", false);
  18662. mCurMethodState->mRetVal = BfTypedValue(allocaInst, mCurMethodInstance->mReturnType, true);
  18663. }
  18664. }
  18665. if (methodDef->mMethodType == BfMethodType_CtorCalcAppend)
  18666. {
  18667. mBfIRBuilder->CreateAlignedStore(GetConstValue(0), mCurMethodState->mRetVal.mValue, mCurMethodState->mRetVal.mType->mAlign);
  18668. BfGetSymbolReferenceKind prevSymbolKind;
  18669. BfAutoComplete* prevAutoComplete;
  18670. if (mCompiler->mResolvePassData != NULL)
  18671. {
  18672. prevSymbolKind = mCompiler->mResolvePassData->mGetSymbolReferenceKind;
  18673. prevAutoComplete = mCompiler->mResolvePassData->mAutoComplete;
  18674. mCompiler->mResolvePassData->mGetSymbolReferenceKind = BfGetSymbolReferenceKind_None;
  18675. }
  18676. EmitCtorCalcAppend();
  18677. if (mCompiler->mResolvePassData != NULL)
  18678. {
  18679. mCompiler->mResolvePassData->mGetSymbolReferenceKind = prevSymbolKind;
  18680. mCompiler->mResolvePassData->mAutoComplete = prevAutoComplete;
  18681. }
  18682. }
  18683. else if (!isEmptyBodied)
  18684. {
  18685. if (!mCurMethodState->mIRExitBlock)
  18686. mCurMethodState->mIRExitBlock = mBfIRBuilder->CreateBlock("exit", true);
  18687. bool isExpressionBody = false;
  18688. if (methodDeclaration != NULL)
  18689. {
  18690. if (methodDeclaration->mFatArrowToken != NULL)
  18691. isExpressionBody = true;
  18692. }
  18693. else if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  18694. {
  18695. auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration();
  18696. if ((propertyMethodDeclaration != NULL) && (propertyMethodDeclaration->mFatArrowToken != NULL))
  18697. isExpressionBody = true;
  18698. if (auto propBodyExpr = BfNodeDynCast<BfPropertyBodyExpression>(propertyDeclaration->mDefinitionBlock))
  18699. {
  18700. isExpressionBody = true;
  18701. }
  18702. }
  18703. else
  18704. {
  18705. if (auto block = BfNodeDynCast<BfBlock>(methodDef->mBody))
  18706. {
  18707. if (!block->mChildArr.IsEmpty())
  18708. {
  18709. if (auto exprStmt = BfNodeDynCast<BfExpressionStatement>(block->mChildArr.GetLast()))
  18710. {
  18711. if (exprStmt->mTrailingSemicolon == NULL)
  18712. isExpressionBody = true;
  18713. }
  18714. }
  18715. }
  18716. else
  18717. isExpressionBody = true;
  18718. }
  18719. DoCEEmit(methodInstance);
  18720. if (methodInstance->mCeCancelled)
  18721. mIgnoreErrors = true;
  18722. if (auto fieldDtorBody = BfNodeDynCast<BfFieldDtorDeclaration>(methodDef->mBody))
  18723. {
  18724. while (fieldDtorBody != NULL)
  18725. {
  18726. VisitEmbeddedStatement(fieldDtorBody->mBody);
  18727. fieldDtorBody = fieldDtorBody->mNextFieldDtor;
  18728. }
  18729. }
  18730. else if (!isExpressionBody)
  18731. {
  18732. auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody);
  18733. mCurMethodState->mHeadScope.mAstBlock = bodyBlock;
  18734. mCurMethodState->mHeadScope.mCloseNode = bodyBlock->mCloseBrace;
  18735. VisitCodeBlock(bodyBlock);
  18736. }
  18737. else if (auto expressionBody = BfNodeDynCast<BfExpression>(methodDef->mBody))
  18738. {
  18739. // if ((methodDef->mMethodType != BfMethodType_Normal) && (propertyDeclaration == NULL))
  18740. // {
  18741. // BF_ASSERT(methodDeclaration->mFatArrowToken != NULL);
  18742. // Fail("Only normal methods can have expression bodies", methodDeclaration->mFatArrowToken);
  18743. // }
  18744. auto expectingType = mCurMethodInstance->mReturnType;
  18745. // What was this error for?
  18746. // if ((expectingType->IsVoid()) && (IsInSpecializedSection()))
  18747. // {
  18748. // Warn(0, "Using a 'void' return with an expression-bodied method isn't needed. Consider removing '=>' token", methodDeclaration->mFatArrowToken);
  18749. // }
  18750. BfEvalExprFlags exprEvalFlags = (BfEvalExprFlags)(BfEvalExprFlags_AllowRefExpr | BfEvalExprFlags_IsExpressionBody);
  18751. if (expectingType->IsVoid())
  18752. {
  18753. exprEvalFlags = (BfEvalExprFlags)(exprEvalFlags | BfEvalExprFlags_NoCast);
  18754. bool wasReturnGenericParam = false;
  18755. if ((mCurMethodState->mClosureState != NULL) && (mCurMethodState->mClosureState->mReturnType != NULL))
  18756. {
  18757. wasReturnGenericParam = mCurMethodState->mClosureState->mReturnType->IsGenericParam();
  18758. }
  18759. else
  18760. {
  18761. auto unspecializedMethodInstance = GetUnspecializedMethodInstance(mCurMethodInstance);
  18762. if ((unspecializedMethodInstance != NULL) && (unspecializedMethodInstance->mReturnType->IsGenericParam()))
  18763. wasReturnGenericParam = true;
  18764. }
  18765. // If we the void return was from a generic specialization, allow us to return a void result,
  18766. // otherwise treat expression as though it must be a statement
  18767. bool isStatement = expressionBody->VerifyIsStatement(mCompiler->mPassInstance, wasReturnGenericParam);
  18768. if (isStatement)
  18769. expectingType = NULL;
  18770. }
  18771. BfExprEvaluator exprEvaluator(this);
  18772. if (mCurMethodInstance->mMethodDef->mIsReadOnly)
  18773. exprEvaluator.mAllowReadOnlyReference = true;
  18774. UpdateSrcPos(expressionBody);
  18775. auto retVal = CreateValueFromExpression(exprEvaluator, expressionBody, expectingType, exprEvalFlags);
  18776. if ((retVal) && (!retVal.mType->IsVar()) && (expectingType != NULL))
  18777. {
  18778. mCurMethodState->mHadReturn = true;
  18779. retVal = LoadOrAggregateValue(retVal);
  18780. EmitReturn(retVal);
  18781. }
  18782. }
  18783. }
  18784. }
  18785. BF_ASSERT(mCurMethodState->mCurScope == &mCurMethodState->mHeadScope);
  18786. if (skipUpdateSrcPos)
  18787. {
  18788. // Skip
  18789. }
  18790. else if ((bodyBlock != NULL) && (bodyBlock->mCloseBrace != NULL))
  18791. UpdateSrcPos(bodyBlock->mCloseBrace);
  18792. else if (methodDef->mBody != NULL)
  18793. UpdateSrcPos(methodDef->mBody);
  18794. else if (methodDeclaration != NULL)
  18795. UpdateSrcPos(methodDeclaration);
  18796. else if (methodDef->mDeclaringType->mTypeDeclaration != NULL)
  18797. UpdateSrcPos(methodDef->mDeclaringType->mTypeDeclaration);
  18798. else
  18799. UseDefaultSrcPos();
  18800. if (methodDef->mMethodType == BfMethodType_CtorCalcAppend)
  18801. {
  18802. if (mCurMethodState->mRetVal)
  18803. {
  18804. mCurMethodState->SetHadReturn(true);
  18805. auto retVal = mBfIRBuilder->CreateLoad(mCurMethodState->mRetVal.mValue);
  18806. mBfIRBuilder->CreateRet(retVal);
  18807. }
  18808. else
  18809. AssertErrorState();
  18810. }
  18811. if (!mCurMethodState->mHadReturn)
  18812. {
  18813. // Clear off the stackallocs that have occurred after a scopeData break
  18814. EmitDeferredScopeCalls(false, &mCurMethodState->mHeadScope, mCurMethodState->mIRExitBlock);
  18815. }
  18816. if (mCurMethodState->mIRExitBlock)
  18817. {
  18818. for (auto preExitBlock : mCurMethodState->mHeadScope.mAtEndBlocks)
  18819. mBfIRBuilder->MoveBlockToEnd(preExitBlock);
  18820. mBfIRBuilder->MoveBlockToEnd(mCurMethodState->mIRExitBlock);
  18821. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRExitBlock);
  18822. if ((!mCurMethodState->mDIRetVal) && (wantsDIData))
  18823. CreateDIRetVal();
  18824. }
  18825. for (auto localVar : mCurMethodState->mLocals)
  18826. {
  18827. if (auto autoCtorDecl = BfNodeDynCast<BfAutoConstructorDeclaration>(methodDeclaration))
  18828. {
  18829. //
  18830. }
  18831. else if ((skipEndChecks) || (methodDef->mBody == NULL))
  18832. break;
  18833. LocalVariableDone(localVar, true);
  18834. }
  18835. if (mCurMethodState->mIRExitBlock)
  18836. {
  18837. if ((mCurMethodState->mRetVal) &&
  18838. ((mIsComptimeModule) || (mCurMethodInstance->GetStructRetIdx() == -1)))
  18839. {
  18840. auto loadedVal = mBfIRBuilder->CreateAlignedLoad(mCurMethodState->mRetVal.mValue, mCurMethodState->mRetVal.mType->mAlign);
  18841. CreateReturn(loadedVal);
  18842. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  18843. if (mCurMethodState->mDIRetVal)
  18844. mBfIRBuilder->DbgLifetimeEnd(mCurMethodState->mDIRetVal);
  18845. }
  18846. else
  18847. {
  18848. // Have something on the last line to step onto
  18849. if (mHasFullDebugInfo)
  18850. {
  18851. if ((bodyBlock != NULL) && (bodyBlock->mCloseBrace != NULL))
  18852. UpdateSrcPos(bodyBlock->mCloseBrace);
  18853. EmitEnsureInstructionAt();
  18854. if ((irParamCount == 0) && (!IsTargetingBeefBackend()) && (mCompiler->mOptions.mAllowHotSwapping))
  18855. {
  18856. // This may be a case where we only emit 4 bytes, whereas we need 5 for a hot replace jump
  18857. mBfIRBuilder->EnsureFunctionPatchable();
  18858. }
  18859. }
  18860. mBfIRBuilder->CreateRetVoid();
  18861. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  18862. if (mCurMethodState->mDIRetVal)
  18863. mBfIRBuilder->DbgLifetimeEnd(mCurMethodState->mDIRetVal);
  18864. }
  18865. }
  18866. if ((mCurMethodInstance->mReturnType == NULL) || (mCurMethodInstance->mReturnType->IsValuelessType()))
  18867. {
  18868. if ((!mCurMethodState->mHadReturn) && (!mCurMethodState->mIRExitBlock))
  18869. {
  18870. if ((!mIsComptimeModule) && (irParamCount == 0) && (!IsTargetingBeefBackend()) && (mCompiler->mOptions.mAllowHotSwapping))
  18871. {
  18872. // This may be a case where we only emit 4 bytes, whereas we need 5 for a hot replace jump
  18873. mBfIRBuilder->EnsureFunctionPatchable();
  18874. }
  18875. mBfIRBuilder->CreateRetVoid();
  18876. }
  18877. }
  18878. else
  18879. {
  18880. if (!mCurMethodState->mHadReturn)
  18881. {
  18882. auto refNode = mCurMethodInstance->mMethodDef->GetRefNode();
  18883. if (bodyBlock != NULL)
  18884. {
  18885. if (bodyBlock->mCloseBrace != NULL)
  18886. {
  18887. BfAstNode* target = bodyBlock->mCloseBrace;
  18888. if (!mCompiler->mHasRequiredTypes)
  18889. {
  18890. AddFailType(mCurTypeInstance);
  18891. mHadBuildError = true;
  18892. }
  18893. else
  18894. Fail("Method must return value", target);
  18895. }
  18896. else
  18897. {
  18898. // It's possible to not have a closing brace if the method ends in an EOF
  18899. AssertErrorState();
  18900. }
  18901. }
  18902. }
  18903. }
  18904. // Move 'init' into 'entry'
  18905. mBfIRBuilder->MergeBlockDown(mCurMethodState->mIRInitBlock, mCurMethodState->mIREntryBlock);
  18906. mBfIRBuilder->MergeBlockDown(mCurMethodState->mIRHeadBlock, mCurMethodState->mIREntryBlock);
  18907. if (((mCurMethodInstance->mIsUnspecialized) /*|| (typeDef->mIsFunction)*/ || (mCurTypeInstance->IsUnspecializedType())) &&
  18908. (!mIsComptimeModule))
  18909. {
  18910. // Don't keep instructions for unspecialized types
  18911. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  18912. }
  18913. // Avoid linking any internal funcs that were just supposed to be comptime-accessible
  18914. /*if ((methodDef->mHasComptime) && (!mIsComptimeModule))
  18915. wantsRemoveBody = true;*/
  18916. if ((hasExternSpecifier) && (!skipBody))
  18917. {
  18918. // If we hot swap, we want to make sure at least one method refers to this extern method so it gets pulled in
  18919. // incase it gets called later by some hot-loaded coded
  18920. if ((mCompiler->mOptions.mAllowHotSwapping) && (mCurMethodInstance->mIRFunction) && (!mCurMethodInstance->mIRFunction.IsFake()) && (mCurTypeInstance != mContext->mBfObjectType))
  18921. {
  18922. if (!mCurMethodInstance->mMethodDef->mName.StartsWith("Comptime_"))
  18923. CreateFakeCallerMethod(mangledName);
  18924. }
  18925. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  18926. }
  18927. else if ((methodInstance->GetImportKind() == BfImportKind_Import_Dynamic) && (!mCompiler->IsHotCompile()))
  18928. {
  18929. // We only need the DLL stub when we may be hot swapping
  18930. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  18931. }
  18932. else if (wantsRemoveBody)
  18933. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  18934. // We don't want to hold on to pointers to LLVMFunctions of unspecialized types.
  18935. // This allows us to delete the mScratchModule LLVM module without rebuilding all
  18936. // unspecialized types
  18937. if (((mCurTypeInstance->IsUnspecializedType()) && (!mIsComptimeModule)) ||
  18938. (mCurTypeInstance->IsInterface()))
  18939. {
  18940. BfLogSysM("ProcessMethod Clearing IRFunction: %p\n", methodInstance);
  18941. methodInstance->mIRFunction = BfIRFunction();
  18942. }
  18943. CheckAddFailType();
  18944. if (mHadBuildError)
  18945. prevHadBuildError.CancelRestore();
  18946. if (mHadBuildWarning)
  18947. prevHadWarning.CancelRestore();
  18948. if (!methodDef->mIsLocalMethod)
  18949. ProcessMethod_ProcessDeferredLocals();
  18950. mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  18951. if (methodState.mHotDataReferenceBuilder != NULL)
  18952. {
  18953. AddHotDataReferences(&hotDataReferenceBuilder);
  18954. }
  18955. else
  18956. {
  18957. if ((methodInstance->mHotMethod != NULL) && (!methodInstance->mIsReified))
  18958. {
  18959. // Remove the hot method data
  18960. auto hotMethod = methodInstance->mHotMethod;
  18961. auto prevMethod = hotMethod->mPrevVersion;
  18962. if (prevMethod != NULL)
  18963. {
  18964. // If there's a prev method then pull its data into the main HotMethod.
  18965. // This, in effect, removes the 'hotMethod' data and rebases 'prevMethod'
  18966. // over to the main HotMethod definition to keep the HotMethod address
  18967. // invariant
  18968. for (auto ref : hotMethod->mReferences)
  18969. ref->Deref();
  18970. hotMethod->mReferences.Clear();
  18971. BF_ASSERT(prevMethod->mRefCount == 1);
  18972. hotMethod->mReferences = prevMethod->mReferences;
  18973. if (hotMethod->mSrcTypeVersion != NULL)
  18974. hotMethod->mSrcTypeVersion->Deref();
  18975. hotMethod->mSrcTypeVersion = prevMethod->mSrcTypeVersion;
  18976. prevMethod->mSrcTypeVersion = NULL;
  18977. prevMethod->mReferences.Clear();
  18978. hotMethod->mPrevVersion = prevMethod->mPrevVersion;
  18979. prevMethod->mPrevVersion = NULL;
  18980. prevMethod->Deref();
  18981. }
  18982. hotMethod->Deref();
  18983. methodInstance->mHotMethod = NULL;
  18984. }
  18985. }
  18986. }
  18987. String BfModule::GetLocalMethodName(const StringImpl& baseName, BfAstNode* anchorNode, BfMethodState* declMethodState, BfMixinState* declMixinState)
  18988. {
  18989. String name;
  18990. bool found = false;
  18991. auto checkMethodState = mCurMethodState;
  18992. while (checkMethodState != NULL)
  18993. {
  18994. if (checkMethodState->mClosureState == NULL)
  18995. break;
  18996. if (checkMethodState->mClosureState->mClosureMethodDef != NULL)
  18997. {
  18998. found = true;
  18999. name += checkMethodState->mClosureState->mClosureMethodDef->mName;
  19000. break;
  19001. }
  19002. checkMethodState = checkMethodState->mPrevMethodState;
  19003. }
  19004. if (!found)
  19005. name += mCurMethodInstance->mMethodDef->mName;
  19006. int prevSepPos = (int)name.LastIndexOf('$');
  19007. if (prevSepPos != -1)
  19008. {
  19009. name.RemoveToEnd(prevSepPos);
  19010. }
  19011. name += "@";
  19012. name += baseName;
  19013. HashContext hashCtx;
  19014. if (anchorNode != NULL)
  19015. {
  19016. hashCtx.Mixin(anchorNode->GetStartCharId());
  19017. }
  19018. //
  19019. {
  19020. auto checkMethodState = declMethodState;
  19021. auto checkMixinState = declMixinState;
  19022. while (checkMethodState != NULL)
  19023. {
  19024. if (checkMixinState != NULL)
  19025. {
  19026. hashCtx.Mixin(checkMixinState->mSource->GetStartCharId());
  19027. }
  19028. checkMethodState = checkMethodState->mPrevMethodState;
  19029. if (checkMethodState != NULL)
  19030. checkMixinState = checkMethodState->mMixinState;
  19031. }
  19032. }
  19033. auto rootMethodState = mCurMethodState->GetRootMethodState();
  19034. if ((rootMethodState != NULL) && (rootMethodState->mMethodInstance != NULL) && (rootMethodState->mMethodInstance->mMethodInfoEx != NULL))
  19035. {
  19036. for (auto methodGenericArg : rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  19037. {
  19038. StringT<512> genericTypeName;
  19039. BfMangler::Mangle(genericTypeName, mCompiler->GetMangleKind(), methodGenericArg);
  19040. hashCtx.MixinStr(genericTypeName);
  19041. }
  19042. }
  19043. uint64 hashVal = hashCtx.Finish64();
  19044. name += "$";
  19045. name += BfTypeUtils::HashEncode64(hashVal);
  19046. return name;
  19047. }
  19048. BfMethodDef* BfModule::GetLocalMethodDef(BfLocalMethod* localMethod)
  19049. {
  19050. if (localMethod->mMethodDef != NULL)
  19051. return localMethod->mMethodDef;
  19052. auto rootMethodState = mCurMethodState->GetRootMethodState();
  19053. auto declMethodState = localMethod->mDeclMethodState;
  19054. auto declMixinState = localMethod->mDeclMixinState;
  19055. auto typeInst = mCurTypeInstance;
  19056. BfAstNode* body = NULL;
  19057. BfAstNode* anchorNode = NULL;
  19058. auto _AllocDirectTypeRef = [&](BfType* type)
  19059. {
  19060. BfDirectTypeReference* directTypeRef = localMethod->mDirectTypeRefs.Alloc();
  19061. directTypeRef->Init(type);
  19062. return directTypeRef;
  19063. };
  19064. auto methodDeclaration = localMethod->mMethodDeclaration;
  19065. if (methodDeclaration != NULL)
  19066. {
  19067. body = methodDeclaration->mBody;
  19068. anchorNode = methodDeclaration->mOpenParen;
  19069. }
  19070. else
  19071. {
  19072. body = localMethod->mLambdaBindExpr->mBody;
  19073. anchorNode = localMethod->mLambdaBindExpr->mFatArrowToken;
  19074. }
  19075. BF_ASSERT(rootMethodState->mCurLocalVarId >= 0);
  19076. int methodLocalIdx = rootMethodState->mCurLocalVarId++;
  19077. BfMethodDef* methodDef;
  19078. BfMethodDef* outerMethodDef = NULL;
  19079. if (localMethod->mOuterLocalMethod != NULL)
  19080. outerMethodDef = localMethod->mOuterLocalMethod->mMethodDef;
  19081. else if (rootMethodState->mMethodInstance != NULL)
  19082. outerMethodDef = rootMethodState->mMethodInstance->mMethodDef;
  19083. if (methodDeclaration != NULL)
  19084. {
  19085. BfDefBuilder defBuilder(mCompiler->mSystem);
  19086. defBuilder.mCurSource = localMethod->mMethodDeclaration->GetParser();
  19087. defBuilder.mPassInstance = mCompiler->mPassInstance;
  19088. defBuilder.mCurTypeDef = mCurMethodInstance->mMethodDef->mDeclaringType;
  19089. defBuilder.mCurDeclaringTypeDef = defBuilder.mCurTypeDef;
  19090. methodDef = defBuilder.CreateMethodDef(methodDeclaration, outerMethodDef);
  19091. }
  19092. else
  19093. {
  19094. auto invokeMethod = localMethod->mLambdaInvokeMethodInstance;
  19095. methodDef = new BfMethodDef();
  19096. methodDef->mName = localMethod->mMethodName;
  19097. methodDef->mDeclaringType = mCurMethodInstance->mMethodDef->mDeclaringType;
  19098. methodDef->mReturnTypeRef = _AllocDirectTypeRef(invokeMethod->mReturnType);
  19099. methodDef->mBody = body;
  19100. for (int paramIdx = 0; paramIdx < invokeMethod->GetParamCount(); paramIdx++)
  19101. {
  19102. auto paramType = invokeMethod->GetParamType(paramIdx);
  19103. String paramName;
  19104. if (paramIdx < (int)localMethod->mLambdaBindExpr->mParams.size())
  19105. paramName = localMethod->mLambdaBindExpr->mParams[paramIdx]->ToString();
  19106. else
  19107. paramName = invokeMethod->GetParamName(paramIdx);
  19108. auto paramDef = new BfParameterDef();
  19109. paramDef->mTypeRef = _AllocDirectTypeRef(paramType);
  19110. paramDef->mName = paramName;
  19111. methodDef->mParams.Add(paramDef);
  19112. }
  19113. if (outerMethodDef != NULL)
  19114. {
  19115. for (auto genericParam : outerMethodDef->mGenericParams)
  19116. {
  19117. auto* copiedGenericParamDef = new BfGenericParamDef();
  19118. *copiedGenericParamDef = *genericParam;
  19119. methodDef->mGenericParams.Add(copiedGenericParamDef);
  19120. }
  19121. }
  19122. }
  19123. methodDef->mIdx = ~methodLocalIdx;
  19124. BF_ASSERT(!localMethod->mExpectedFullName.IsEmpty());
  19125. methodDef->mName = localMethod->mExpectedFullName;
  19126. // methodDef->mName = GetLocalMethodName(methodDef->mName, anchorNode, declMethodState, declMixinState);
  19127. //
  19128. // if (!localMethod->mExpectedFullName.IsEmpty())
  19129. // BF_ASSERT(methodDef->mName == localMethod->mExpectedFullName);
  19130. methodDef->mIsStatic = true;
  19131. methodDef->mIsLocalMethod = true;
  19132. methodDef->mIsVirtual = false;
  19133. localMethod->mMethodDef = methodDef;
  19134. auto methodInstanceGroup = new BfMethodInstanceGroup();
  19135. localMethod->mMethodInstanceGroup = methodInstanceGroup;
  19136. methodInstanceGroup->mMethodIdx = -1;
  19137. methodInstanceGroup->mOwner = mCurTypeInstance;
  19138. methodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  19139. if ((declMethodState->mMixinState != NULL) && (declMethodState->mMixinState->mTarget))
  19140. {
  19141. methodInstanceGroup->mOwner = declMethodState->mMixinState->mTarget.mType->ToTypeInstance();
  19142. BF_ASSERT(methodInstanceGroup->mOwner != NULL);
  19143. }
  19144. if ((mCompiler->mResolvePassData != NULL) && (methodDeclaration != NULL))
  19145. {
  19146. mCompiler->mResolvePassData->HandleLocalReference(methodDeclaration->mNameNode, typeInst->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, methodLocalIdx);
  19147. auto autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  19148. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(methodDeclaration->mNameNode)))
  19149. {
  19150. autoComplete->SetDefinitionLocation(methodDeclaration->mNameNode);
  19151. autoComplete->mInsertStartIdx = methodDeclaration->mNameNode->GetSrcStart();
  19152. autoComplete->mInsertEndIdx = methodDeclaration->mNameNode->GetSrcEnd();
  19153. autoComplete->mDefType = typeInst->mTypeDef;
  19154. autoComplete->mDefMethod = rootMethodState->mMethodInstance->mMethodDef;
  19155. autoComplete->mReplaceLocalId = methodLocalIdx;
  19156. }
  19157. }
  19158. return localMethod->mMethodDef;
  19159. }
  19160. BfModuleMethodInstance BfModule::GetLocalMethodInstance(BfLocalMethod* localMethod, const BfTypeVector& methodGenericArguments, BfMethodInstance* methodInstance, bool force)
  19161. {
  19162. BP_ZONE_F("GetLocalMethodInstance %s", localMethod->mMethodName.c_str());
  19163. BfLogSysM("GetLocalMethodInstance %p\n", localMethod);
  19164. auto rootMethodState = mCurMethodState->GetRootMethodState();
  19165. auto declMethodState = localMethod->mDeclMethodState;
  19166. auto declMixinState = localMethod->mDeclMixinState;
  19167. auto callerMethodState = mCurMethodState;
  19168. auto typeInst = mCurTypeInstance;
  19169. if (mCurMethodState->mMixinState != NULL)
  19170. {
  19171. typeInst = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  19172. }
  19173. auto methodDef = GetLocalMethodDef(localMethod);
  19174. BfAstNode* body = NULL;
  19175. auto methodDeclaration = localMethod->mMethodDeclaration;
  19176. if (methodDeclaration != NULL)
  19177. {
  19178. body = methodDeclaration->mBody;
  19179. }
  19180. else
  19181. {
  19182. body = localMethod->mLambdaBindExpr->mBody;
  19183. }
  19184. bool hadConcreteInterfaceGenericArgument = false;
  19185. BfTypeVector sanitizedMethodGenericArguments;
  19186. // Ignore the outermost method's generic method arguments for the purpose of determining if we are the 'default' (ie: unspecialized)
  19187. // version of this method for this pass through the outermost method
  19188. int dependentGenericStartIdx = 0;
  19189. if ((rootMethodState->mMethodInstance != NULL) && (rootMethodState->mMethodInstance->mMethodInfoEx != NULL))
  19190. dependentGenericStartIdx = (int)rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  19191. BfMethodInstance* outerMethodInstance = mCurMethodInstance;
  19192. if (methodGenericArguments.size() == 0)
  19193. {
  19194. if ((rootMethodState->mMethodInstance != NULL) && (rootMethodState->mMethodInstance->mMethodInfoEx != NULL))
  19195. sanitizedMethodGenericArguments = rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments;
  19196. }
  19197. else
  19198. {
  19199. int genericArgIdx = 0;
  19200. // for (; genericArgIdx < (int)outerMethodInstance->mMethodGenericArguments.size(); genericArgIdx++)
  19201. // {
  19202. // BF_ASSERT(methodGenericArguments[genericArgIdx] == outerMethodInstance->mMethodGenericArguments[genericArgIdx]);
  19203. // sanitizedMethodGenericArguments.push_back(methodGenericArguments[genericArgIdx]);
  19204. // }
  19205. for (; genericArgIdx < (int)methodGenericArguments.size(); genericArgIdx++)
  19206. {
  19207. auto genericArgType = methodGenericArguments[genericArgIdx];
  19208. BF_ASSERT(!genericArgType->IsRef());
  19209. if (genericArgType->IsConcreteInterfaceType())
  19210. {
  19211. hadConcreteInterfaceGenericArgument = true;
  19212. auto concreteInterfaceType = (BfConcreteInterfaceType*)genericArgType;
  19213. genericArgType = concreteInterfaceType->mInterface;
  19214. }
  19215. sanitizedMethodGenericArguments.push_back(genericArgType);
  19216. }
  19217. }
  19218. bool wantPrematureMethodInstance = false;
  19219. if (!force)
  19220. {
  19221. wantPrematureMethodInstance = (callerMethodState->mClosureState != NULL) && (callerMethodState->mClosureState->mCaptureVisitingBody);
  19222. }
  19223. auto methodInstGroup = localMethod->mMethodInstanceGroup;
  19224. bool isDefaultPass = true;
  19225. BfTypeVector lookupMethodGenericArguments;
  19226. for (int genericArgIdx = dependentGenericStartIdx; genericArgIdx < (int)methodGenericArguments.size(); genericArgIdx++)
  19227. {
  19228. auto genericArgType = methodGenericArguments[genericArgIdx];
  19229. BF_ASSERT(!genericArgType->IsRef());
  19230. lookupMethodGenericArguments.Add(genericArgType);
  19231. if (genericArgType->IsGenericParam())
  19232. {
  19233. auto genericParam = (BfGenericParamType*)genericArgType;
  19234. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  19235. isDefaultPass = false;
  19236. }
  19237. else
  19238. {
  19239. isDefaultPass = false;
  19240. }
  19241. }
  19242. bool hadExistingMethodInstance = false;
  19243. if (methodInstance != NULL)
  19244. {
  19245. hadExistingMethodInstance = true;
  19246. }
  19247. else
  19248. {
  19249. if (isDefaultPass)
  19250. {
  19251. methodInstance = methodInstGroup->mDefault;
  19252. if (methodInstance != NULL)
  19253. {
  19254. hadExistingMethodInstance = true;
  19255. }
  19256. else
  19257. {
  19258. methodInstance = new BfMethodInstance();
  19259. methodInstGroup->mDefault = methodInstance;
  19260. }
  19261. }
  19262. else
  19263. {
  19264. BF_ASSERT(sanitizedMethodGenericArguments.size() != 0);
  19265. if (methodInstGroup->mMethodSpecializationMap == NULL)
  19266. methodInstGroup->mMethodSpecializationMap = new BfMethodInstanceGroup::MapType();
  19267. BfMethodInstance** methodInstancePtr = NULL;
  19268. if (!methodInstGroup->mMethodSpecializationMap->TryAdd(lookupMethodGenericArguments, NULL, &methodInstancePtr))
  19269. {
  19270. methodInstance = *methodInstancePtr;
  19271. hadExistingMethodInstance = true;
  19272. }
  19273. else
  19274. {
  19275. methodInstance = new BfMethodInstance();
  19276. *methodInstancePtr = methodInstance;
  19277. }
  19278. }
  19279. }
  19280. if (hadExistingMethodInstance)
  19281. {
  19282. if ((!methodInstance->mDisallowCalling) ||
  19283. ((wantPrematureMethodInstance) && (methodInstance->mDisallowCalling)))
  19284. return BfModuleMethodInstance(methodInstance);
  19285. BF_ASSERT((methodInstance->mMethodInfoEx == NULL) || (methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState == NULL));
  19286. }
  19287. else
  19288. {
  19289. auto methodInfoEx = methodInstance->GetMethodInfoEx();
  19290. methodInfoEx->mClosureInstanceInfo = new BfClosureInstanceInfo();
  19291. methodInfoEx->mClosureInstanceInfo->mLocalMethod = localMethod;
  19292. methodInstance->mIsReified = mCurMethodInstance->mIsReified;
  19293. methodInstance->mIsAutocompleteMethod = mCurMethodInstance->mIsAutocompleteMethod;
  19294. methodInstance->mMethodDef = methodDef;
  19295. methodInstance->mMethodInstanceGroup = localMethod->mMethodInstanceGroup;
  19296. if (hadConcreteInterfaceGenericArgument)
  19297. methodInstance->mIgnoreBody = true;
  19298. methodInfoEx->mMethodGenericArguments = sanitizedMethodGenericArguments;
  19299. for (auto genericArg : sanitizedMethodGenericArguments)
  19300. {
  19301. if (genericArg->IsPrimitiveType())
  19302. genericArg = GetWrappedStructType(genericArg);
  19303. AddDependency(genericArg, typeInst, BfDependencyMap::DependencyFlag_MethodGenericArg);
  19304. }
  19305. for (int genericParamIdx = (int)sanitizedMethodGenericArguments.size(); genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  19306. {
  19307. auto genericParamType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  19308. methodInfoEx->mMethodGenericArguments.push_back(genericParamType);
  19309. }
  19310. SetupMethodIdHash(methodInstance);
  19311. }
  19312. auto _SetupMethodInstance = [&]()
  19313. {
  19314. BF_ASSERT(methodInstance->GetNumGenericParams() == 0);
  19315. // Generic constraints
  19316. for (int genericParamIdx = 0; genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  19317. {
  19318. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, genericParamIdx);
  19319. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  19320. }
  19321. };
  19322. //////////////////////////////////////////////////////////////////////////
  19323. auto _VisitLambdaBody = [&]()
  19324. {
  19325. if (localMethod->mDeclOnly)
  19326. return;
  19327. if (mCompiler->mCanceling)
  19328. return;
  19329. if (auto blockBody = BfNodeDynCast<BfBlock>(body))
  19330. {
  19331. VisitCodeBlock(blockBody);
  19332. }
  19333. else if (auto bodyExpr = BfNodeDynCast<BfExpression>(body))
  19334. {
  19335. BfType* expectType = NULL;
  19336. if (!methodInstance->mReturnType->IsVoid())
  19337. expectType = methodInstance->mReturnType;
  19338. CreateValueFromExpression(bodyExpr, expectType, BfEvalExprFlags_AllowRefExpr);
  19339. }
  19340. };
  19341. auto _SafeResolveTypeRef = [&](BfTypeReference* typeRef)
  19342. {
  19343. SetAndRestoreValue<bool> prevIgnoreError(mIgnoreErrors, true);
  19344. auto result = ResolveTypeRef(typeRef);
  19345. if (result == NULL)
  19346. result = mContext->mBfObjectType;
  19347. return result;
  19348. };
  19349. BfTypeInstance* outerClosure = NULL;
  19350. if ((declMethodState->mClosureState != NULL) && (!declMethodState->mClosureState->mCapturing))
  19351. outerClosure = declMethodState->mClosureState->mClosureType;
  19352. BfMethodState methodState;
  19353. methodState.mPrevMethodState = declMethodState;//mCurMethodState;
  19354. BfIRFunctionType funcType;
  19355. auto voidType = GetPrimitiveType(BfTypeCode_None);
  19356. SizedArray<BfIRType, 0> paramTypes;
  19357. funcType = mBfIRBuilder->CreateFunctionType(mBfIRBuilder->MapType(voidType), paramTypes, methodInstance->IsVarArgs());
  19358. mBfIRBuilder->SaveDebugLocation();
  19359. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  19360. auto prevActiveFunction = mBfIRBuilder->GetActiveFunction();
  19361. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  19362. BfDeferredLocalAssignData deferredLocalAssignData;
  19363. //TODO: Why did we do this? It can cause us to pull in local variables that don't belong to us...
  19364. /*if (declMethodState->mDeferredLocalAssignData != NULL)
  19365. deferredLocalAssignData.ExtendFrom(declMethodState->mDeferredLocalAssignData);*/
  19366. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  19367. methodState.mIRHeadBlock = mBfIRBuilder->CreateBlock("head", true);
  19368. methodState.mIRInitBlock = mBfIRBuilder->CreateBlock("init", true);
  19369. methodState.mIREntryBlock = mBfIRBuilder->CreateBlock("entry", true);
  19370. methodState.mCurScope->mDIScope = localMethod->mDeclDIScope; //declMethodState->mCurScope->mDIScope ;
  19371. //methodState.mCurLocalVarId = declMethodState->mCurLocalVarId;
  19372. methodState.mIRFunction = declMethodState->mIRFunction;
  19373. methodState.mDeferredLocalAssignData = &deferredLocalAssignData;
  19374. if (auto blockBody = BfNodeDynCast<BfBlock>(body))
  19375. {
  19376. methodState.mCurScope->mAstBlock = blockBody;
  19377. methodState.mCurScope->mCloseNode = blockBody->mCloseBrace;
  19378. }
  19379. mBfIRBuilder->SetInsertPoint(methodState.mIREntryBlock);
  19380. BfClosureState closureState;
  19381. if (methodDef->mMethodType == BfMethodType_Mixin)
  19382. {
  19383. if (declMethodState != NULL)
  19384. {
  19385. if ((declMethodState->mClosureState != NULL) && (declMethodState->mClosureState->mReturnType != NULL))
  19386. closureState.mReturnType = declMethodState->mClosureState->mReturnType;
  19387. else if (declMethodState->mMethodInstance != NULL)
  19388. closureState.mReturnType = declMethodState->mMethodInstance->mReturnType;
  19389. }
  19390. }
  19391. if (closureState.mReturnType == NULL)
  19392. closureState.mReturnType = _SafeResolveTypeRef(methodDef->mReturnTypeRef);
  19393. closureState.mCapturing = true;
  19394. closureState.mLocalMethod = localMethod;
  19395. closureState.mClosureInstanceInfo = methodInstance->mMethodInfoEx->mClosureInstanceInfo;
  19396. closureState.mDeclaringMethodIsMutating = mCurMethodInstance->mMethodDef->mIsMutating;
  19397. methodState.mClosureState = &closureState;
  19398. closureState.mClosureType = outerClosure;
  19399. int outerLocalsCount = (int)methodState.mLocals.size();
  19400. if (!hadExistingMethodInstance)
  19401. {
  19402. BfLogSysM("LocalMethod %p premature DoMethodDeclaration %p (Source:%p)\n", localMethod, methodInstance, (methodDeclaration != NULL) ? methodDeclaration->GetSourceData() : NULL);
  19403. SetAndRestoreValue<bool> prevIgnoreWrites(mWantsIRIgnoreWrites, true);
  19404. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  19405. // Prematurely do declaration. We will have to undo this later, so don't write this one and don't throw errors
  19406. auto declareModule = this;
  19407. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  19408. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  19409. BF_ASSERT(declareModule != NULL);
  19410. methodInstance->mDeclModule = declareModule;
  19411. _SetupMethodInstance();
  19412. declareModule->DoMethodDeclaration(localMethod->mMethodDef->GetMethodDeclaration(), false, false);
  19413. methodInstance->mDisallowCalling = true; // Don't allow us to ACTUALLY call until we add the captures
  19414. }
  19415. if (wantPrematureMethodInstance)
  19416. {
  19417. // Return a premature methodInstance -- since we are partway through determining the capture of a local method, we can't rely on its
  19418. // capture information. This returned method instance can only be used for method matching, but we will visit it later to create
  19419. // its true method instance
  19420. //auto moduleMethodInstance = _CheckReturnedMethod(methodInstance);
  19421. //BF_ASSERT(moduleMethodInstance);
  19422. return BfModuleMethodInstance(methodInstance);
  19423. }
  19424. auto checkInsertBlock = mBfIRBuilder->GetInsertBlock();
  19425. BF_ASSERT(methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState == NULL);
  19426. closureState.mCaptureStartAccessId = mCurMethodState->GetRootMethodState()->mCurAccessId;
  19427. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState = &closureState;
  19428. closureState.mClosureMethodDef = methodDef;
  19429. bool wantsVisitBody = true;
  19430. if ((methodDef->mMethodType == BfMethodType_Mixin) && (!methodGenericArguments.IsEmpty()))
  19431. wantsVisitBody = false;
  19432. if (methodInstance->IsOrInUnspecializedVariation())
  19433. wantsVisitBody = false;
  19434. bool allowCapture = (methodDeclaration == NULL) || (methodDeclaration->mStaticSpecifier == NULL);
  19435. if (wantsVisitBody)
  19436. {
  19437. BP_ZONE("VisitLambdaBody");
  19438. // For generic methods, we capture for each specialization, so make sure mIsStatic is set to 'true' for
  19439. // this capture stage for each of those times
  19440. SetAndRestoreValue<bool> prevWasStatis(methodDef->mIsStatic, true);
  19441. /*
  19442. // Only generate errors once. Also there are some errors that will occur during this scanning phase
  19443. // that will not occur during the actual lambda method generation, for example: returning a value
  19444. // when our current method is a 'void' method. This shouldn't affect capture scanning since all
  19445. // our AST nodes will still be visited
  19446. SetAndRestoreValue<bool> ignoreError(mIgnoreErrors, true);
  19447. */
  19448. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  19449. //SetAndRestoreValue<bool> wantsIgnoreWrites(mWantsISIgnoreWrites, true);
  19450. mBfIRBuilder->SaveDebugLocation();
  19451. closureState.mCaptureVisitingBody = true;
  19452. BF_ASSERT(methodInstance->mMethodInfoEx != NULL);
  19453. methodState.mGenericTypeBindings = &methodInstance->mMethodInfoEx->mGenericTypeBindings;
  19454. methodState.mMethodInstance = methodInstance;
  19455. NewScopeState();
  19456. ProcessMethod_SetupParams(methodInstance, NULL, false, NULL);
  19457. if (methodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)
  19458. {
  19459. // Allow assigning to arguments when we're capturing - which may or may not be legal at the injection site (we throw error there)
  19460. for (auto localDef : methodState.mLocals)
  19461. {
  19462. if (localDef->mResolvedType->IsVar())
  19463. continue;
  19464. localDef->mAddr = CreateAlloca(localDef->mResolvedType);
  19465. }
  19466. }
  19467. // Keep outs for being marked as assigned
  19468. auto rootMethodState = mCurMethodState->GetRootMethodState();
  19469. BfDeferredLocalAssignData deferredLocalAssignData(rootMethodState->mCurScope);
  19470. deferredLocalAssignData.mVarIdBarrier = rootMethodState->mCurLocalVarId;
  19471. SetAndRestoreValue<BfDeferredLocalAssignData*> prevDLA(rootMethodState->mDeferredLocalAssignData, &deferredLocalAssignData);
  19472. if (!mIgnoreErrors)
  19473. localMethod->mDidBodyErrorPass = true;
  19474. _VisitLambdaBody();
  19475. RestoreScopeState();
  19476. closureState.mCaptureVisitingBody = false;
  19477. mBfIRBuilder->RestoreDebugLocation();
  19478. }
  19479. // If we ended up being called by a method with a lower captureStartAccessId, propagate that to whoever is calling us, too...
  19480. if ((methodState.mPrevMethodState->mClosureState != NULL) && (methodState.mPrevMethodState->mClosureState->mCapturing))
  19481. {
  19482. auto prevClosureState = methodState.mPrevMethodState->mClosureState;
  19483. if (closureState.mCaptureStartAccessId < prevClosureState->mCaptureStartAccessId)
  19484. prevClosureState->mCaptureStartAccessId = closureState.mCaptureStartAccessId;
  19485. }
  19486. // Actually get the referenced local methods. It's important we wait until after visiting the body, because then our own capture information
  19487. // can be used by these methods (which will be necessary if any of these methods call us directly or indirectly)
  19488. closureState.mClosureMethodDef = NULL;
  19489. for (auto methodInstance : closureState.mLocalMethodRefs)
  19490. {
  19491. GetLocalMethodInstance(methodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod, BfTypeVector(), methodInstance);
  19492. }
  19493. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState = NULL;
  19494. prevIgnoreWrites.Restore();
  19495. std::multiset<BfClosureCapturedEntry> capturedEntries;
  19496. //
  19497. {
  19498. auto varMethodState = declMethodState;
  19499. while (varMethodState != NULL)
  19500. {
  19501. if ((varMethodState->mMixinState != NULL) && (varMethodState->mMixinState->mLastTargetAccessId >= closureState.mCaptureStartAccessId))
  19502. {
  19503. BF_ASSERT(methodInstance->GetOwner() == varMethodState->mMixinState->mTarget.mType);
  19504. methodDef->mIsStatic = false;
  19505. if (rootMethodState->mMethodInstance->mMethodDef->mIsMutating)
  19506. methodDef->mIsMutating = true;
  19507. }
  19508. bool copyOuterCaptures = false;
  19509. for (int localIdx = 0; localIdx < varMethodState->mLocals.size(); localIdx++)
  19510. {
  19511. auto localVar = varMethodState->mLocals[localIdx];
  19512. if ((localVar->mReadFromId >= closureState.mCaptureStartAccessId) || (localVar->mWrittenToId >= closureState.mCaptureStartAccessId))
  19513. {
  19514. if (!allowCapture)
  19515. {
  19516. if ((!localVar->mIsStatic) && (!localVar->mConstValue))
  19517. continue;
  19518. }
  19519. if (localVar->mIsThis)
  19520. {
  19521. // We can only set mutating if our owning type is mutating
  19522. if (localVar->mWrittenToId >= closureState.mCaptureStartAccessId)
  19523. {
  19524. if (typeInst->IsValueType())
  19525. {
  19526. if (rootMethodState->mMethodInstance->mMethodDef->mIsMutating)
  19527. methodDef->mIsMutating = true;
  19528. }
  19529. }
  19530. methodDef->mIsStatic = false;
  19531. continue;
  19532. }
  19533. if ((localVar->mIsThis) && (outerClosure != NULL))
  19534. {
  19535. continue;
  19536. }
  19537. if ((localVar->mConstValue) || (localVar->mIsStatic) || (localVar->mResolvedType->IsValuelessType()))
  19538. {
  19539. closureState.mConstLocals.push_back(*localVar);
  19540. continue;
  19541. }
  19542. BfClosureCapturedEntry capturedEntry;
  19543. auto capturedType = localVar->mResolvedType;
  19544. bool captureByRef = false;
  19545. if (!capturedType->IsRef())
  19546. {
  19547. if (localVar->mIsThis)
  19548. {
  19549. if ((localVar->mResolvedType->IsValueType()) && (mCurMethodInstance->mMethodDef->HasNoThisSplat()))
  19550. captureByRef = true;
  19551. }
  19552. else if ((!localVar->mIsReadOnly) && (localVar->mWrittenToId >= closureState.mCaptureStartAccessId))
  19553. captureByRef = true;
  19554. }
  19555. else
  19556. {
  19557. if (localVar->mWrittenToId < closureState.mCaptureStartAccessId)
  19558. {
  19559. capturedType = ((BfRefType*)capturedType)->mElementType;
  19560. }
  19561. }
  19562. if (captureByRef)
  19563. {
  19564. //capturedEntry.mIsByReference = true;
  19565. capturedType = CreateRefType(capturedType);
  19566. }
  19567. else
  19568. {
  19569. //capturedEntry.mIsByReference = false;
  19570. }
  19571. capturedEntry.mNameNode = localVar->mNameNode;
  19572. capturedEntry.mType = capturedType;
  19573. capturedEntry.mName = localVar->mName;
  19574. //capturedEntry.mLocalVarDef = localVar;
  19575. capturedEntries.insert(capturedEntry);
  19576. }
  19577. }
  19578. varMethodState = varMethodState->mPrevMethodState;
  19579. if ((varMethodState == NULL) ||
  19580. (varMethodState->mMixinState != NULL) ||
  19581. ((varMethodState->mClosureState != NULL) && (!varMethodState->mClosureState->mCapturing)))
  19582. break;
  19583. }
  19584. }
  19585. for (auto& copyField : closureState.mReferencedOuterClosureMembers)
  19586. {
  19587. auto fieldDef = copyField->GetFieldDef();
  19588. BfClosureCapturedEntry capturedEntry;
  19589. capturedEntry.mName = copyField->GetFieldDef()->mName;
  19590. capturedEntry.mType = copyField->mResolvedType;
  19591. if (capturedEntry.mType->IsRef())
  19592. {
  19593. // Keep by ref
  19594. }
  19595. else if (!fieldDef->mIsReadOnly)
  19596. {
  19597. capturedEntry.mType = CreateRefType(capturedEntry.mType);
  19598. }
  19599. capturedEntries.insert(capturedEntry);
  19600. }
  19601. int captureIdx = 0;
  19602. for (auto& capturedEntry : capturedEntries)
  19603. {
  19604. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries.Add(capturedEntry);
  19605. }
  19606. /*if (isDefaultPass)
  19607. {
  19608. // Insert captured members a params at the start. If we added at the end then it would screw up varargs methods
  19609. int captureIdx = 0;
  19610. for (auto& capturedEntry : capturedEntries)
  19611. {
  19612. methodInstance->mClosureInstanceInfo->mCaptureNodes.Add(BfNodeDynCast<BfIdentifierNode>(capturedEntry.mNameNode));
  19613. BfParameterDef* paramDef = new BfParameterDef();
  19614. paramDef->mName = capturedEntry.mName;
  19615. BfDirectTypeReference* directTypeRef = new BfDirectTypeReference();
  19616. directTypeRef->mType = capturedEntry.mType;
  19617. typeInst->mTypeDef->mDirectAllocNodes.push_back(directTypeRef);
  19618. paramDef->mTypeRef = directTypeRef;
  19619. paramDef->mParamKind = BfParamKind_ImplicitCapture;
  19620. methodDef->mParams.Insert(captureIdx, paramDef);
  19621. captureIdx++;
  19622. }
  19623. }
  19624. else
  19625. {
  19626. auto defaultMethodInstance = methodInstGroup->mDefault;
  19627. methodInstance->mClosureInstanceInfo->mCaptureNodes = defaultMethodInstance->mClosureInstanceInfo->mCaptureNodes;
  19628. }*/
  19629. methodState.Reset();
  19630. closureState.mCapturing = false;
  19631. //////////////////////////////////////////////////////////////////////////
  19632. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, false);
  19633. if (methodInstance->mReturnType != NULL)
  19634. {
  19635. BF_ASSERT(methodInstance->mDisallowCalling);
  19636. // We did a premature declaration (without captures)
  19637. methodInstance->UndoDeclaration();
  19638. methodInstance->mDisallowCalling = false;
  19639. BfLogSysM("LocalMethod %p UndoingDeclaration %p\n", localMethod, methodInstance);
  19640. }
  19641. auto declareModule = this;
  19642. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  19643. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  19644. BF_ASSERT(declareModule != NULL);
  19645. methodInstance->mDeclModule = declareModule;
  19646. _SetupMethodInstance();
  19647. BfLogSysM("LocalMethod %p DoMethodDeclaration %p\n", localMethod, methodInstance);
  19648. declareModule->DoMethodDeclaration(localMethod->mMethodDef->GetMethodDeclaration(), false, false);
  19649. closureState.mReturnType = methodInstance->mReturnType;
  19650. mCompiler->mStats.mMethodsQueued++;
  19651. mCompiler->UpdateCompletion();
  19652. declareModule->mIncompleteMethodCount++;
  19653. mCompiler->mStats.mMethodsProcessed++;
  19654. if (!methodInstance->mIsReified)
  19655. mCompiler->mStats.mUnreifiedMethodsProcessed++;
  19656. auto deferMethodState = rootMethodState;
  19657. // 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)
  19658. if ((!localMethod->mDeclOnly) && (!methodInstance->IsOrInUnspecializedVariation()) &&
  19659. (methodDef->mMethodType != BfMethodType_Mixin) &&
  19660. ((!mWantsIRIgnoreWrites) || (!localMethod->mDidBodyErrorPass)) &&
  19661. (!mCompiler->IsDataResolvePass()))
  19662. {
  19663. BP_ZONE("BfDeferredLocalMethod:create");
  19664. BfDeferredLocalMethod* deferredLocalMethod = new BfDeferredLocalMethod();
  19665. deferredLocalMethod->mLocalMethod = localMethod;
  19666. deferredLocalMethod->mConstLocals = closureState.mConstLocals;
  19667. deferredLocalMethod->mMethodInstance = methodInstance;
  19668. auto checkMethodState = declMethodState;
  19669. while (checkMethodState != NULL)
  19670. {
  19671. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mActiveDeferredLocalMethod != NULL))
  19672. {
  19673. for (auto& mixinRecord : checkMethodState->mClosureState->mActiveDeferredLocalMethod->mMixinStateRecords)
  19674. deferredLocalMethod->mMixinStateRecords.Add(mixinRecord);
  19675. }
  19676. if (checkMethodState->mMixinState != NULL)
  19677. {
  19678. BfMixinRecord mixinRecord;
  19679. mixinRecord.mSource = checkMethodState->mMixinState->mSource;
  19680. deferredLocalMethod->mMixinStateRecords.Add(mixinRecord);
  19681. }
  19682. checkMethodState = checkMethodState->mPrevMethodState;
  19683. }
  19684. rootMethodState->mDeferredLocalMethods.Add(deferredLocalMethod);
  19685. }
  19686. mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  19687. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  19688. mBfIRBuilder->RestoreDebugLocation();
  19689. if (methodInstance == localMethod->mMethodInstanceGroup->mDefault)
  19690. {
  19691. auto checkMethodState = mCurMethodState;
  19692. while (checkMethodState != NULL)
  19693. {
  19694. BfLocalMethod* nextLocalMethod = NULL;
  19695. if (checkMethodState->mLocalMethodMap.TryGetValue(localMethod->mMethodName, &nextLocalMethod))
  19696. {
  19697. while (nextLocalMethod != NULL)
  19698. {
  19699. auto checkLocalMethod = nextLocalMethod;
  19700. nextLocalMethod = nextLocalMethod->mNextWithSameName;
  19701. if (checkLocalMethod == localMethod)
  19702. continue;
  19703. if (checkLocalMethod->mMethodInstanceGroup == NULL)
  19704. continue;
  19705. auto checkMethodInstance = checkLocalMethod->mMethodInstanceGroup->mDefault;
  19706. if (checkMethodInstance == NULL)
  19707. continue; // Not generated yet
  19708. if (CompareMethodSignatures(localMethod->mMethodInstanceGroup->mDefault, checkMethodInstance))
  19709. {
  19710. String error = "Method already declared with the same parameter types";
  19711. auto bfError = Fail(error, methodInstance->mMethodDef->GetRefNode(), true);
  19712. if ((bfError != NULL) && (methodInstance->mMethodDef->GetRefNode() != checkMethodInstance->mMethodDef->GetRefNode()))
  19713. mCompiler->mPassInstance->MoreInfo("First declaration", checkMethodInstance->mMethodDef->GetRefNode());
  19714. }
  19715. }
  19716. }
  19717. checkMethodState = checkMethodState->mPrevMethodState;
  19718. }
  19719. }
  19720. return BfModuleMethodInstance(methodInstance);
  19721. }
  19722. int BfModule::GetLocalInferrableGenericArgCount(BfMethodDef* methodDef)
  19723. {
  19724. if ((!methodDef->mIsLocalMethod) || (methodDef->mGenericParams.size() == 0))
  19725. return 0;
  19726. auto rootMethodState = mCurMethodState->GetRootMethodState();
  19727. int rootMethodGenericParamCount = 0;
  19728. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  19729. rootMethodGenericParamCount = (int)rootMethodState->mMethodInstance->mMethodInfoEx->mGenericParams.size();
  19730. if (mCurMethodInstance == NULL)
  19731. return rootMethodGenericParamCount;
  19732. if ((mCurMethodInstance->mMethodInfoEx == NULL) || (mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo == NULL))
  19733. return rootMethodGenericParamCount;
  19734. BfLocalMethod* callerLocalMethod = mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod;
  19735. if (callerLocalMethod == NULL)
  19736. return rootMethodGenericParamCount;
  19737. BfLocalMethod* calledLocalMethod = NULL;
  19738. rootMethodState->mLocalMethodCache.TryGetValue(methodDef->mName, &calledLocalMethod);
  19739. while ((calledLocalMethod != NULL) && (callerLocalMethod != NULL))
  19740. {
  19741. if (calledLocalMethod->mOuterLocalMethod == callerLocalMethod)
  19742. return (int)callerLocalMethod->mMethodDef->mGenericParams.size();
  19743. callerLocalMethod = calledLocalMethod->mOuterLocalMethod;
  19744. }
  19745. return rootMethodGenericParamCount;
  19746. }
  19747. void BfModule::GetMethodCustomAttributes(BfMethodInstance* methodInstance)
  19748. {
  19749. auto methodDef = methodInstance->mMethodDef;
  19750. auto customAttributes = methodInstance->GetCustomAttributes();
  19751. if (customAttributes != NULL)
  19752. return;
  19753. auto methodDeclaration = methodDef->GetMethodDeclaration();
  19754. auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration();
  19755. auto typeInstance = methodInstance->GetOwner();
  19756. if (typeInstance->IsInstanceOf(mCompiler->mValueTypeTypeDef))
  19757. return;
  19758. BfTypeState typeState(typeInstance);
  19759. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  19760. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  19761. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  19762. BfAttributeTargets attrTarget = ((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend)) ? BfAttributeTargets_Constructor : BfAttributeTargets_Method;
  19763. BfAttributeDirective* attributeDirective = NULL;
  19764. if (methodDeclaration != NULL)
  19765. attributeDirective = methodDeclaration->mAttributes;
  19766. else if (propertyMethodDeclaration != NULL)
  19767. {
  19768. attributeDirective = propertyMethodDeclaration->mAttributes;
  19769. if (auto exprBody = BfNodeDynCast<BfPropertyBodyExpression>(propertyMethodDeclaration->mPropertyDeclaration->mDefinitionBlock))
  19770. {
  19771. attributeDirective = propertyMethodDeclaration->mPropertyDeclaration->mAttributes;
  19772. attrTarget = (BfAttributeTargets)(BfAttributeTargets_Property | BfAttributeTargets_Method);
  19773. }
  19774. }
  19775. if (attributeDirective != NULL)
  19776. {
  19777. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes == NULL)
  19778. methodInstance->mMethodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  19779. if ((methodInstance == methodInstance->mMethodInstanceGroup->mDefault) && (methodInstance->mMethodInstanceGroup->mDefaultCustomAttributes != NULL))
  19780. {
  19781. // Take over prevoiusly-generated custom attributes
  19782. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes = methodInstance->mMethodInstanceGroup->mDefaultCustomAttributes;
  19783. methodInstance->mMethodInstanceGroup->mDefaultCustomAttributes = NULL;
  19784. }
  19785. else
  19786. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes = GetCustomAttributes(attributeDirective, attrTarget);
  19787. }
  19788. if ((propertyMethodDeclaration != NULL) && (propertyMethodDeclaration->mPropertyDeclaration->mAttributes != NULL) && ((attrTarget & BfAttributeTargets_Property) == 0))
  19789. {
  19790. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes != NULL)
  19791. {
  19792. GetCustomAttributes(methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes, propertyMethodDeclaration->mPropertyDeclaration->mAttributes, BfAttributeTargets_Property);
  19793. }
  19794. else
  19795. {
  19796. methodInstance->GetMethodInfoEx()->mMethodCustomAttributes = new BfMethodCustomAttributes();
  19797. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes = GetCustomAttributes(propertyMethodDeclaration->mPropertyDeclaration->mAttributes, BfAttributeTargets_Property);
  19798. }
  19799. }
  19800. customAttributes = methodInstance->GetCustomAttributes();
  19801. if (customAttributes == NULL)
  19802. {
  19803. auto owner = methodInstance->GetOwner();
  19804. if ((owner->IsDelegate()) || (owner->IsFunction()))
  19805. customAttributes = owner->mCustomAttributes;
  19806. }
  19807. methodInstance->mCallingConvention = methodDef->mCallingConvention;
  19808. if (customAttributes != NULL)
  19809. {
  19810. auto linkNameAttr = customAttributes->Get(mCompiler->mCallingConventionAttributeTypeDef);
  19811. if (linkNameAttr != NULL)
  19812. {
  19813. if (linkNameAttr->mCtorArgs.size() == 1)
  19814. {
  19815. auto constant = typeInstance->mConstHolder->GetConstant(linkNameAttr->mCtorArgs[0]);
  19816. if (constant != NULL)
  19817. methodInstance->mCallingConvention = (BfCallingConvention)constant->mInt32;
  19818. }
  19819. }
  19820. if (methodDef->mHasComptime)
  19821. methodInstance->mComptimeFlags = BfComptimeFlag_Comptime;
  19822. auto comptimeAttr = customAttributes->Get(mCompiler->mComptimeAttributeTypeDef);
  19823. if (comptimeAttr != NULL)
  19824. {
  19825. for (auto setProp : comptimeAttr->mSetProperties)
  19826. {
  19827. BfPropertyDef* propertyDef = setProp.mPropertyRef;
  19828. if (propertyDef->mName == "OnlyFromComptime")
  19829. {
  19830. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  19831. if ((constant != NULL) && (constant->mBool))
  19832. methodInstance->mComptimeFlags = (BfComptimeFlags)(methodInstance->mComptimeFlags | BfComptimeFlag_OnlyFromComptime);
  19833. }
  19834. else if (propertyDef->mName == "ConstEval")
  19835. {
  19836. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  19837. if ((constant != NULL) && (constant->mBool))
  19838. methodInstance->mComptimeFlags = (BfComptimeFlags)(methodInstance->mComptimeFlags | BfComptimeFlag_ConstEval);
  19839. }
  19840. }
  19841. }
  19842. }
  19843. auto delegateInfo = typeInstance->GetDelegateInfo();
  19844. if ((delegateInfo != NULL) && (methodInstance->mMethodDef->mMethodType == BfMethodType_Normal) && (methodInstance->mMethodDef->mName == "Invoke"))
  19845. methodInstance->mCallingConvention = delegateInfo->mCallingConvention;
  19846. }
  19847. void BfModule::SetupIRFunction(BfMethodInstance* methodInstance, StringImpl& mangledName, bool isTemporaryFunc, bool* outIsIntrinsic)
  19848. {
  19849. if (methodInstance->GetImportCallKind() == BfImportCallKind_GlobalVar)
  19850. {
  19851. // Don't create a func
  19852. return;
  19853. }
  19854. auto typeInstance = methodInstance->GetOwner();
  19855. auto methodDef = methodInstance->mMethodDef;
  19856. BfIRFunctionType funcType = mBfIRBuilder->MapMethod(methodInstance);
  19857. if (isTemporaryFunc)
  19858. {
  19859. BF_ASSERT(((mCompiler->mIsResolveOnly) && (mCompiler->mResolvePassData->mAutoComplete != NULL)) ||
  19860. (methodInstance->GetOwner()->mDefineState < BfTypeDefineState_Defined));
  19861. mangledName = "autocomplete_tmp";
  19862. }
  19863. if (!mBfIRBuilder->mIgnoreWrites)
  19864. {
  19865. BfIRFunction prevFunc;
  19866. // Remove old version (if we have one)
  19867. prevFunc = mBfIRBuilder->GetFunction(mangledName);
  19868. if (prevFunc)
  19869. {
  19870. if ((methodDef->mIsOverride) && (mCurTypeInstance->mTypeDef->mIsCombinedPartial))
  19871. {
  19872. bool takeover = false;
  19873. mCurTypeInstance->mTypeDef->PopulateMemberSets();
  19874. BfMethodDef* nextMethod = NULL;
  19875. BfMemberSetEntry* entry = NULL;
  19876. if (mCurTypeInstance->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  19877. nextMethod = (BfMethodDef*)entry->mMemberDef;
  19878. while (nextMethod != NULL)
  19879. {
  19880. auto checkMethod = nextMethod;
  19881. nextMethod = nextMethod->mNextWithSameName;
  19882. if (checkMethod == methodDef)
  19883. continue;
  19884. if (checkMethod->mIsOverride)
  19885. {
  19886. auto checkMethodInstance = mCurTypeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  19887. if (checkMethodInstance == NULL)
  19888. continue;
  19889. if ((checkMethodInstance->mIRFunction == prevFunc) &&
  19890. (checkMethodInstance->mMethodDef->mMethodDeclaration != NULL) &&
  19891. (checkMethodInstance->mVirtualTableIdx < 0))
  19892. {
  19893. BfAstNode* refNode = methodDef->GetRefNode();
  19894. if (auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration())
  19895. refNode = propertyMethodDeclaration->mPropertyDeclaration->mVirtualSpecifier;
  19896. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  19897. refNode = methodDeclaration->mVirtualSpecifier;
  19898. auto error = Fail(StrFormat("Conflicting extension override method '%s'", MethodToString(mCurMethodInstance).c_str()), refNode);
  19899. if (error != NULL)
  19900. mCompiler->mPassInstance->MoreInfo("See previous override", checkMethod->GetRefNode());
  19901. takeover = false;
  19902. break;
  19903. }
  19904. }
  19905. if (!checkMethod->mIsExtern)
  19906. continue;
  19907. auto checkMethodInstance = mCurTypeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  19908. if (checkMethodInstance == NULL)
  19909. continue;
  19910. if (!CompareMethodSignatures(checkMethodInstance, mCurMethodInstance))
  19911. continue;
  19912. // Take over function
  19913. takeover = true;
  19914. }
  19915. if (takeover)
  19916. mCurMethodInstance->mIRFunction = prevFunc;
  19917. if (!mCurMethodInstance->mIRFunction)
  19918. {
  19919. BfLogSysM("Function collision from inner override erased prevFunc %p: %d\n", methodInstance, prevFunc.mId);
  19920. if (!mIsComptimeModule)
  19921. mBfIRBuilder->Func_SafeRename(prevFunc);
  19922. }
  19923. }
  19924. else if (methodDef->mIsExtern)
  19925. {
  19926. // Allow this
  19927. BfLogSysM("Function collision allowed multiple extern functions for %p: %d\n", methodInstance, prevFunc.mId);
  19928. }
  19929. else if (typeInstance->IsIRFuncUsed(prevFunc))
  19930. {
  19931. // We can have a collision of names when we have generic methods that differ only in
  19932. // their constraints, but they should only collide in their unspecialized form
  19933. // since only one will be chosen for a given concrete type
  19934. if (!mIsComptimeModule)
  19935. mCurMethodInstance->mMangleWithIdx = true;
  19936. mangledName.Clear();
  19937. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  19938. prevFunc = mBfIRBuilder->GetFunction(mangledName);
  19939. BfLogSysM("Function collision forced mangleWithIdx for %p: %d\n", methodInstance, prevFunc.mId);
  19940. }
  19941. else
  19942. {
  19943. BfLogSysM("Function collision erased prevFunc %p: %d\n", methodInstance, prevFunc.mId);
  19944. if (!mIsComptimeModule)
  19945. mBfIRBuilder->Func_SafeRename(prevFunc);
  19946. }
  19947. }
  19948. }
  19949. if (typeInstance != mContext->mBfObjectType)
  19950. {
  19951. // Only allow attributes on System.Object methods that can be handled inside the DefBuilder
  19952. GetMethodCustomAttributes(methodInstance);
  19953. }
  19954. // if (prevFunc)
  19955. // {
  19956. // if (methodDef->mIsExtern)
  19957. // {
  19958. // BfLogSysM("Reusing function for %p: %d\n", methodInstance, prevFunc.mId);
  19959. // methodInstance->mIRFunction = prevFunc;
  19960. // }
  19961. // else
  19962. // {
  19963. // if ((methodInstance->IsSpecializedByAutoCompleteMethod()) ||
  19964. // ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mResolveType >= BfResolveType_GoToDefinition)))
  19965. // {
  19966. // // If we're doing re-pass over the methods for something like BfResolveType_ShowFileSymbolReferences, then allow this collision
  19967. // BfLogSysM("Ignoring function name collision\n");
  19968. // }
  19969. // else
  19970. // {
  19971. // if (methodDef->mMethodDeclaration == NULL)
  19972. // {
  19973. // AssertErrorState();
  19974. // }
  19975. // else
  19976. // {
  19977. // BF_ASSERT(mIsSpecialModule);
  19978. // if ((mCompiler->mRevision == 1) && (HasCompiledOutput()))
  19979. // {
  19980. // // We shouldn't have name collisions on the first run!
  19981. // AssertErrorState();
  19982. // }
  19983. // }
  19984. // }
  19985. // BfLogSysM("Before erase\n");
  19986. // mBfIRBuilder->Func_EraseFromParent(prevFunc);
  19987. // }
  19988. // }
  19989. bool isIntrinsic = false;
  19990. if (!methodInstance->mIRFunction)
  19991. {
  19992. BfIRFunction func;
  19993. bool wantsLLVMFunc = ((!typeInstance->IsUnspecializedType() || (mIsComptimeModule)) &&
  19994. (!methodDef->IsEmptyPartial())) && (funcType);
  19995. /*if (mCurTypeInstance->mTypeDef->mName->ToString() == "ClassA")
  19996. {
  19997. if (!mIsReified)
  19998. wantsLLVMFunc = false;
  19999. }*/
  20000. if (wantsLLVMFunc)
  20001. {
  20002. func = GetIntrinsic(methodInstance, true);
  20003. if (func)
  20004. {
  20005. isIntrinsic = true;
  20006. }
  20007. else
  20008. {
  20009. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, mangledName);
  20010. BfLogSysM("Creating FuncId:%d %s in module %p\n", func.mId, mangledName.c_str(), this);
  20011. if (methodInstance->mAlwaysInline)
  20012. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_AlwaysInline);
  20013. // if (prevFunc)
  20014. // BfLogSysM("Removing Func %d, replacing with %d\n", prevFunc.mId, func.mId);
  20015. }
  20016. methodInstance->mIRFunction = func;
  20017. //if (!ignoreWrites)
  20018. //BF_ASSERT(!func.IsFake());
  20019. }
  20020. }
  20021. if (outIsIntrinsic != NULL)
  20022. *outIsIntrinsic = isIntrinsic;
  20023. if (!isIntrinsic)
  20024. SetupIRMethod(methodInstance, methodInstance->mIRFunction, methodInstance->mAlwaysInline);
  20025. }
  20026. void BfModule::CheckHotMethod(BfMethodInstance* methodInstance, const StringImpl& inMangledName)
  20027. {
  20028. if (methodInstance->mHotMethod != NULL)
  20029. return;
  20030. if ((mCompiler->mOptions.mAllowHotSwapping) && (!methodInstance->mIsUnspecialized))
  20031. {
  20032. auto srcTypeInst = methodInstance->GetOwner();
  20033. StringT<128> mangledName = inMangledName;
  20034. if (mangledName.IsEmpty())
  20035. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  20036. // We always keep the current primary method at the same address
  20037. BfHotMethod* hotMethod;
  20038. BfHotMethod** hotMethodPtr;
  20039. if (mCompiler->mHotData->mMethodMap.TryAdd(mangledName, NULL, &hotMethodPtr))
  20040. {
  20041. hotMethod = new BfHotMethod();
  20042. *hotMethodPtr = hotMethod;
  20043. hotMethod->mRefCount = 1;
  20044. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  20045. #ifdef BF_DBG_HOTMETHOD_IDX
  20046. static int sMethodIdx = 0;
  20047. hotMethod->mMethodIdx = sMethodIdx++;
  20048. #endif
  20049. BfLogSysM("HotMethodData %p created for method %p %s - %s\n", hotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  20050. }
  20051. else
  20052. {
  20053. hotMethod = *hotMethodPtr;
  20054. if ((hotMethod->mFlags & BfHotDepDataFlag_IsBound) != 0)
  20055. {
  20056. // This is a duplicate mangled name - we link to this new entry via a 'BfHotDupMethod'
  20057. auto prevHotMethod = *hotMethodPtr;
  20058. hotMethod = new BfHotMethod();
  20059. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  20060. BfHotDupMethod* hotDupMethod = new BfHotDupMethod(hotMethod);
  20061. hotDupMethod->mRefCount++;
  20062. prevHotMethod->mReferences.Add(hotDupMethod);
  20063. prevHotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_HasDup);
  20064. BfLogSysM("HotMethodData %p (duplicate of %p) created for method %p %s - %s\n", hotMethod, prevHotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  20065. }
  20066. else if (mCompiler->IsHotCompile())
  20067. {
  20068. // Link the previous version into the mPrevVersion
  20069. BfHotMethod* prevMethod = new BfHotMethod();
  20070. prevMethod->mRefCount = 1;
  20071. prevMethod->mPrevVersion = hotMethod->mPrevVersion;
  20072. hotMethod->mPrevVersion = prevMethod;
  20073. prevMethod->mSrcTypeVersion = hotMethod->mSrcTypeVersion;
  20074. hotMethod->mSrcTypeVersion = NULL;
  20075. prevMethod->mFlags = hotMethod->mFlags;
  20076. hotMethod->mFlags = BfHotDepDataFlag_IsBound;
  20077. hotMethod->mReferences.MoveTo(prevMethod->mReferences);
  20078. #ifdef BF_DBG_HOTMETHOD_NAME
  20079. prevMethod->mMangledName = hotMethod->mMangledName;
  20080. #endif
  20081. BfLogSysM("HotMethodData %p created for prevmethod of %p for method %p %s\n", prevMethod, hotMethod, methodInstance, MethodToString(methodInstance).c_str());
  20082. }
  20083. else
  20084. {
  20085. BfLogSysM("HotMethodData %p used for method %p %s - %s\n", hotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  20086. hotMethod->Clear(true);
  20087. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  20088. }
  20089. }
  20090. if (methodInstance->mIsClosure)
  20091. {
  20092. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_RetainMethodWithoutBinding);
  20093. }
  20094. hotMethod->mSrcTypeVersion = srcTypeInst->mHotTypeData->GetLatestVersion();
  20095. hotMethod->mSrcTypeVersion->mRefCount++;
  20096. hotMethod->mRefCount++;
  20097. #ifdef BF_DBG_HOTMETHOD_NAME
  20098. hotMethod->mMangledName = mangledName;
  20099. #endif
  20100. if ((methodInstance->mMethodInstanceGroup->IsImplemented()) && (!IsHotCompile()))
  20101. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsOriginalBuild);
  20102. methodInstance->mHotMethod = hotMethod;
  20103. }
  20104. }
  20105. static void StackOverflow()
  20106. {
  20107. int i = 0;
  20108. if (i == 0)
  20109. StackOverflow();
  20110. }
  20111. void BfModule::StartMethodDeclaration(BfMethodInstance* methodInstance, BfMethodState* prevMethodState)
  20112. {
  20113. methodInstance->mHasStartedDeclaration = true;
  20114. auto methodDef = methodInstance->mMethodDef;
  20115. auto typeInstance = methodInstance->GetOwner();
  20116. bool hasNonGenericParams = false;
  20117. bool hasGenericParams = false;
  20118. int dependentGenericStartIdx = 0;
  20119. if (methodDef->mIsLocalMethod)
  20120. {
  20121. // If we're a local generic method inside an outer generic method, we can still be considered unspecialized
  20122. // if our outer method's generic args are specialized but ours are unspecialized. This is because locals get
  20123. // instantiated uniquely for each specialized or unspecialized pass through the outer method, but the local
  20124. // method still 'inherits' the outer's generic arguments -- but we still need to make an unspecialized pass
  20125. // over the local method each time
  20126. auto rootMethodInstance = prevMethodState->GetRootMethodState()->mMethodInstance;
  20127. dependentGenericStartIdx = 0;
  20128. if (rootMethodInstance != NULL)
  20129. {
  20130. if (rootMethodInstance->mMethodInfoEx != NULL)
  20131. dependentGenericStartIdx = (int)rootMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  20132. methodInstance->mIsUnspecialized = rootMethodInstance->mIsUnspecialized;
  20133. methodInstance->mIsUnspecializedVariation = rootMethodInstance->mIsUnspecializedVariation;
  20134. }
  20135. }
  20136. for (int genericArgIdx = dependentGenericStartIdx; genericArgIdx < (int)methodInstance->GetNumGenericArguments(); genericArgIdx++)
  20137. {
  20138. auto genericArgType = methodInstance->mMethodInfoEx->mMethodGenericArguments[genericArgIdx];
  20139. if (genericArgType->IsGenericParam())
  20140. {
  20141. hasGenericParams = true;
  20142. auto genericParam = (BfGenericParamType*)genericArgType;
  20143. methodInstance->mIsUnspecialized = true;
  20144. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  20145. methodInstance->mIsUnspecializedVariation = true;
  20146. }
  20147. else
  20148. {
  20149. hasNonGenericParams = true;
  20150. if (genericArgType->IsUnspecializedType())
  20151. {
  20152. methodInstance->mIsUnspecialized = true;
  20153. methodInstance->mIsUnspecializedVariation = true;
  20154. }
  20155. }
  20156. }
  20157. if ((hasGenericParams) && (hasNonGenericParams))
  20158. {
  20159. methodInstance->mIsUnspecializedVariation = true;
  20160. }
  20161. if (typeInstance->IsUnspecializedType())
  20162. {
  20163. // A specialized method within an unspecialized type is considered an unspecialized variation -- in the sense that we don't
  20164. // actually want to do method processing on it
  20165. if ((!methodInstance->mIsUnspecialized) && (methodInstance->GetNumGenericArguments() != 0))
  20166. methodInstance->mIsUnspecializedVariation = true;
  20167. methodInstance->mIsUnspecialized = true;
  20168. }
  20169. if (methodInstance->mIsUnspecializedVariation)
  20170. BF_ASSERT(methodInstance->mIsUnspecialized);
  20171. //TODO: Why did we do this?
  20172. if (methodDef->mMethodType == BfMethodType_Mixin)
  20173. {
  20174. if (methodInstance->IsSpecializedGenericMethod())
  20175. methodInstance->mIsUnspecializedVariation = true;
  20176. methodInstance->mIsUnspecialized = true;
  20177. }
  20178. }
  20179. // methodDeclaration is NULL for default constructors
  20180. void BfModule::DoMethodDeclaration(BfMethodDeclaration* methodDeclaration, bool isTemporaryFunc, bool addToWorkList)
  20181. {
  20182. BF_ASSERT((mCompiler->mCeMachine == NULL) || (!mCompiler->mCeMachine->mDbgPaused));
  20183. BP_ZONE("BfModule::DoMethodDeclaration");
  20184. // We could trigger a DoMethodDeclaration from a const resolver or other location, so we reset it here
  20185. // to effectively make mIgnoreWrites method-scoped
  20186. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mWantsIRIgnoreWrites || mCurMethodInstance->mIsUnspecialized || mCurTypeInstance->mResolvingVarField);
  20187. SetAndRestoreValue<bool> prevIsCapturingMethodMatchInfo;
  20188. SetAndRestoreValue<bool> prevAllowLockYield(mContext->mAllowLockYield, false);
  20189. BfTypeState typeState(mCurTypeInstance);
  20190. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  20191. if (mCompiler->IsAutocomplete())
  20192. prevIsCapturingMethodMatchInfo.Init(mCompiler->mResolvePassData->mAutoComplete->mIsCapturingMethodMatchInfo, false);
  20193. if (mCurMethodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference)
  20194. mCurMethodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingReference;
  20195. BfMethodState methodState;
  20196. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  20197. methodState.mTempKind = BfMethodState::TempKind_Static;
  20198. defer({ mCurMethodInstance->mHasBeenDeclared = true; });
  20199. // If we are doing this then we may end up creating methods when var types are unknown still, failing on splat/zero-sized info
  20200. BF_ASSERT((!mCurTypeInstance->mResolvingVarField) || (mBfIRBuilder->mIgnoreWrites));
  20201. bool ignoreWrites = mBfIRBuilder->mIgnoreWrites;
  20202. // if ((!isTemporaryFunc) && (mCurTypeInstance->mDefineState < BfTypeDefineState_Defined))
  20203. // {
  20204. // BF_ASSERT(mContext->mResolvingVarField);
  20205. // isTemporaryFunc = true;
  20206. // }
  20207. if ((mAwaitingInitFinish) && (!mBfIRBuilder->mIgnoreWrites))
  20208. FinishInit();
  20209. auto typeInstance = mCurTypeInstance;
  20210. auto typeDef = typeInstance->mTypeDef;
  20211. auto methodDef = mCurMethodInstance->mMethodDef;
  20212. BF_ASSERT(methodDef->mName != "__ASSERTNAME");
  20213. if (methodDef->mName == "__FATALERRORNAME")
  20214. BFMODULE_FATAL(this, "__FATALERRORNAME");
  20215. if (methodDef->mName == "__STACKOVERFLOW")
  20216. StackOverflow();
  20217. if (typeInstance->IsClosure())
  20218. {
  20219. if (methodDef->mName == "Invoke")
  20220. return;
  20221. }
  20222. auto methodInstance = mCurMethodInstance;
  20223. if ((methodInstance->IsSpecializedByAutoCompleteMethod()) || (mCurTypeInstance->IsFunction()))
  20224. addToWorkList = false;
  20225. if (!methodInstance->mHasStartedDeclaration)
  20226. StartMethodDeclaration(methodInstance, prevMethodState.mPrevVal);
  20227. BfAutoComplete* bfAutocomplete = NULL;
  20228. if (mCompiler->mResolvePassData != NULL)
  20229. bfAutocomplete = mCompiler->mResolvePassData->mAutoComplete;
  20230. if (methodInstance->mMethodInfoEx != NULL)
  20231. {
  20232. BfTypeInstance* unspecializedTypeInstance = NULL;
  20233. Array<BfTypeReference*> deferredResolveTypes;
  20234. for (int genericParamIdx = 0; genericParamIdx < (int)methodInstance->mMethodInfoEx->mGenericParams.size(); genericParamIdx++)
  20235. {
  20236. auto genericParam = methodInstance->mMethodInfoEx->mGenericParams[genericParamIdx];
  20237. if (genericParamIdx < (int)methodDef->mGenericParams.size())
  20238. {
  20239. genericParam->mExternType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  20240. }
  20241. else
  20242. {
  20243. auto externConstraintDef = genericParam->GetExternConstraintDef();
  20244. genericParam->mExternType = ResolveTypeRef(externConstraintDef->mTypeRef);
  20245. auto autoComplete = mCompiler->GetAutoComplete();
  20246. if (autoComplete != NULL)
  20247. autoComplete->CheckTypeRef(externConstraintDef->mTypeRef, false);
  20248. if (genericParam->mExternType != NULL)
  20249. {
  20250. //
  20251. }
  20252. else
  20253. genericParam->mExternType = GetPrimitiveType(BfTypeCode_Var);
  20254. }
  20255. ResolveGenericParamConstraints(genericParam, methodInstance->mIsUnspecialized, &deferredResolveTypes);
  20256. if (genericParamIdx < (int)methodDef->mGenericParams.size())
  20257. {
  20258. auto genericParamDef = methodDef->mGenericParams[genericParamIdx];
  20259. if (bfAutocomplete != NULL)
  20260. {
  20261. for (auto nameNode : genericParamDef->mNameNodes)
  20262. {
  20263. HandleMethodGenericParamRef(nameNode, typeDef, methodDef, genericParamIdx);
  20264. }
  20265. }
  20266. }
  20267. }
  20268. for (auto typeRef : deferredResolveTypes)
  20269. auto constraintType = ResolveTypeRef(typeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_None);
  20270. if (methodInstance->mMethodInfoEx != NULL)
  20271. {
  20272. ValidateGenericParams(BfGenericParamKind_Method,
  20273. Span<BfGenericParamInstance*>((BfGenericParamInstance**)methodInstance->mMethodInfoEx->mGenericParams.mVals,
  20274. methodInstance->mMethodInfoEx->mGenericParams.mSize));
  20275. }
  20276. for (auto genericParam : methodInstance->mMethodInfoEx->mGenericParams)
  20277. AddDependency(genericParam, mCurTypeInstance);
  20278. }
  20279. if ((methodInstance->mIsAutocompleteMethod) && (methodDeclaration != NULL) && (!methodInstance->IsSpecializedGenericMethod()) && (methodDef->mIdx >= 0))
  20280. {
  20281. auto autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  20282. BfAstNode* nameNode = methodDeclaration->mNameNode;
  20283. if (nameNode == NULL)
  20284. {
  20285. if (auto ctorDeclaration = BfNodeDynCast<BfConstructorDeclaration>(methodDeclaration))
  20286. nameNode = ctorDeclaration->mThisToken;
  20287. }
  20288. if ((autoComplete->IsAutocompleteNode(nameNode)) && (autoComplete->mResolveType != BfResolveType_Autocomplete))
  20289. {
  20290. autoComplete->mInsertStartIdx = nameNode->GetSrcStart();
  20291. autoComplete->mInsertEndIdx = nameNode->GetSrcEnd();
  20292. autoComplete->mDefType = typeDef;
  20293. autoComplete->mDefMethod = methodDef;
  20294. autoComplete->SetDefinitionLocation(nameNode);
  20295. if (methodDef->mIsOverride)
  20296. {
  20297. bool found = false;
  20298. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  20299. {
  20300. auto& ventry = typeInstance->mVirtualMethodTable[virtIdx];
  20301. if (ventry.mDeclaringMethod.mMethodNum == -1)
  20302. continue;
  20303. BfMethodInstance* virtMethod = ventry.mImplementingMethod;
  20304. if (virtMethod != NULL)
  20305. {
  20306. auto virtMethodDeclaration = virtMethod->mMethodDef->GetMethodDeclaration();
  20307. if ((virtMethod->GetOwner() == typeInstance) && (virtMethodDeclaration != NULL) &&
  20308. (virtMethodDeclaration->GetSrcStart() == methodDeclaration->GetSrcStart()))
  20309. {
  20310. // Is matching method
  20311. if (virtIdx < (int)typeInstance->mBaseType->mVirtualMethodTable.size())
  20312. {
  20313. auto baseType = typeInstance->mBaseType;
  20314. if (baseType != NULL)
  20315. {
  20316. found = true;
  20317. while ((baseType->mBaseType != NULL) && (virtIdx < baseType->mBaseType->mVirtualMethodTableSize))
  20318. baseType = baseType->mBaseType;
  20319. BfMethodInstance* baseVirtMethod = baseType->mVirtualMethodTable[virtIdx].mImplementingMethod;
  20320. autoComplete->SetDefinitionLocation(baseVirtMethod->mMethodDef->GetRefNode(), true);
  20321. autoComplete->mDefType = baseType->mTypeDef;
  20322. autoComplete->mDefMethod = baseVirtMethod->mMethodDef;
  20323. }
  20324. }
  20325. break;
  20326. }
  20327. }
  20328. }
  20329. if ((!found) && (autoComplete->mIsGetDefinition) && (methodDef->mDeclaringType->IsExtension()))
  20330. {
  20331. for (auto& methodGroup : typeInstance->mMethodInstanceGroups)
  20332. {
  20333. auto defaultMethod = methodGroup.mDefault;
  20334. if (defaultMethod == NULL)
  20335. continue;
  20336. if (!defaultMethod->mMethodDef->mIsExtern)
  20337. continue;
  20338. if (!CompareMethodSignatures(defaultMethod, methodInstance))
  20339. continue;
  20340. autoComplete->SetDefinitionLocation(defaultMethod->mMethodDef->GetRefNode(), true);
  20341. autoComplete->mDefType = typeInstance->mTypeDef;
  20342. autoComplete->mDefMethod = defaultMethod->mMethodDef;
  20343. }
  20344. }
  20345. }
  20346. }
  20347. }
  20348. bool reportErrors = true;
  20349. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  20350. reportErrors = true;
  20351. // Only the defining contexts needs to report errors here
  20352. SetAndRestoreValue<bool> prevReporErrors(mReportErrors, reportErrors);
  20353. if (methodDef->mMethodType == BfMethodType_Dtor)
  20354. {
  20355. if (methodDef->mIsStatic)
  20356. {
  20357. }
  20358. else
  20359. {
  20360. if ((typeInstance->IsStruct()) || (typeInstance->IsTypedPrimitive()))
  20361. {
  20362. BfAstNode* refNode = methodDeclaration;
  20363. if (refNode == NULL)
  20364. {
  20365. // Whatever caused this ctor to be generated should have caused another failure
  20366. // But that failure might not be generated until the ctor is generated
  20367. }
  20368. else
  20369. {
  20370. auto dtorDecl = BfNodeDynCast<BfDestructorDeclaration>(methodDeclaration);
  20371. if (dtorDecl != NULL)
  20372. refNode = dtorDecl->mThisToken;
  20373. Fail("Structs cannot have destructors", refNode);
  20374. }
  20375. }
  20376. auto methodDeclaration = methodDef->GetMethodDeclaration();
  20377. if ((methodDeclaration != NULL) && (methodDeclaration->mVirtualSpecifier != NULL) &&
  20378. (mCurTypeInstance != mContext->mBfObjectType))
  20379. {
  20380. Fail("Virtual specifier is not required, all destructors are implicitly virtual.", methodDeclaration->mVirtualSpecifier);
  20381. }
  20382. }
  20383. }
  20384. BfType* resolvedReturnType = NULL;
  20385. if (((methodDef->mMethodType == BfMethodType_Normal) || (methodDef->mMethodType == BfMethodType_Extension) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend) ||
  20386. (methodDef->mMethodType == BfMethodType_PropertyGetter) || (methodDef->mMethodType == BfMethodType_Operator)) &&
  20387. (methodDef->mReturnTypeRef != NULL))
  20388. {
  20389. SetAndRestoreValue<bool> prevIngoreErrors(mIgnoreErrors, mIgnoreErrors || (methodDef->GetPropertyDeclaration() != NULL));
  20390. BfResolveTypeRefFlags flags = (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_AllowRef | BfResolveTypeRefFlag_AllowRefGeneric);
  20391. if ((((methodInstance->mComptimeFlags & BfComptimeFlag_ConstEval) != 0) || (methodInstance->mIsAutocompleteMethod))
  20392. && (methodDef->mReturnTypeRef->IsA<BfVarTypeReference>()))
  20393. resolvedReturnType = GetPrimitiveType(BfTypeCode_Var);
  20394. else
  20395. resolvedReturnType = ResolveTypeRef(methodDef->mReturnTypeRef, BfPopulateType_Declaration, flags);
  20396. if (resolvedReturnType == NULL)
  20397. resolvedReturnType = GetPrimitiveType(BfTypeCode_Var);
  20398. if ((methodDef->mIsReadOnly) && (!resolvedReturnType->IsRef()))
  20399. {
  20400. if (auto methodDeclaration = BfNodeDynCast<BfMethodDeclaration>(methodInstance->mMethodDef->mMethodDeclaration))
  20401. if (methodDeclaration->mReadOnlySpecifier != NULL)
  20402. Fail("Readonly specifier is only valid on 'ref' return types", methodDeclaration->mReadOnlySpecifier);
  20403. }
  20404. }
  20405. else
  20406. {
  20407. resolvedReturnType = ResolveTypeDef(mSystem->mTypeVoid);
  20408. }
  20409. BF_ASSERT(resolvedReturnType != NULL);
  20410. mCurMethodInstance->mReturnType = resolvedReturnType;
  20411. //TODO: We used to NOT add the return value dependency for specialized methods, but when we have types that are
  20412. // specialized based on the method's generic param then they can get deleted if no one else has referred to them (yet)
  20413. //if (!methodInstance->IsSpecializedGenericMethod())
  20414. AddDependency(resolvedReturnType, typeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  20415. if (methodDef->mExplicitInterface != NULL)
  20416. {
  20417. auto autoComplete = mCompiler->GetAutoComplete();
  20418. if (autoComplete != NULL)
  20419. autoComplete->CheckTypeRef(methodDef->mExplicitInterface, false);
  20420. auto explicitType = ResolveTypeRef(methodDef->mExplicitInterface, BfPopulateType_Declaration);
  20421. BfTypeInstance* explicitInterface = NULL;
  20422. if (explicitType != NULL)
  20423. explicitInterface = explicitType->ToTypeInstance();
  20424. if (explicitInterface != NULL)
  20425. {
  20426. mCurMethodInstance->GetMethodInfoEx()->mExplicitInterface = explicitInterface->ToTypeInstance();
  20427. if (autoComplete != NULL)
  20428. {
  20429. BfTokenNode* dotToken = NULL;
  20430. BfAstNode* nameNode = NULL;
  20431. if (auto methodDeclaration = BfNodeDynCast<BfMethodDeclaration>(methodDef->mMethodDeclaration))
  20432. {
  20433. dotToken = methodDeclaration->mExplicitInterfaceDotToken;
  20434. nameNode = methodDeclaration->mNameNode;
  20435. }
  20436. autoComplete->CheckExplicitInterface(explicitInterface, dotToken, nameNode);
  20437. }
  20438. }
  20439. if ((mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mExplicitInterface != NULL))
  20440. {
  20441. bool interfaceFound = false;
  20442. for (auto ifaceInst : typeInstance->mInterfaces)
  20443. interfaceFound |= ifaceInst.mInterfaceType == mCurMethodInstance->mMethodInfoEx->mExplicitInterface;
  20444. if ((!interfaceFound) && (!typeInstance->mTypeFailed))
  20445. {
  20446. if (methodDef->mMethodDeclaration != NULL)
  20447. Fail("Containing class has not declared to implement this interface", methodDef->mMethodDeclaration);
  20448. else
  20449. {
  20450. // For property decls, we should have already given the error during type population
  20451. if (mCompiler->mRevision == 1)
  20452. AssertErrorState();
  20453. }
  20454. }
  20455. }
  20456. }
  20457. bool isThisStruct = mCurTypeInstance->IsStruct();
  20458. BfType* thisType = NULL;
  20459. if ((!methodDef->mIsStatic) && (!mCurTypeInstance->IsValuelessType()))
  20460. {
  20461. if ((isThisStruct) || (mCurTypeInstance->IsTypedPrimitive()))
  20462. {
  20463. thisType = mCurTypeInstance;
  20464. if (thisType == NULL)
  20465. return;
  20466. if ((thisType->IsSplattable()) && (!methodDef->HasNoThisSplat()))
  20467. {
  20468. BfTypeUtils::SplatIterate([&](BfType* checkType)
  20469. {
  20470. PopulateType(checkType, BfPopulateType_Data);
  20471. }, thisType);
  20472. }
  20473. }
  20474. else
  20475. {
  20476. thisType = mCurTypeInstance;
  20477. PopulateType(thisType, BfPopulateType_Declaration);
  20478. }
  20479. }
  20480. int implicitParamCount = 0;
  20481. if ((mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo != NULL))
  20482. implicitParamCount = (int)methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries.size();
  20483. methodInstance->mMethodDef->mParams.Reserve((int)methodDef->mParams.size());
  20484. bool hadDelegateParams = false;
  20485. bool hadParams = false;
  20486. for (int paramIdx = 0; paramIdx < (int)methodDef->mParams.size() + implicitParamCount; paramIdx++)
  20487. {
  20488. BfClosureCapturedEntry* closureCaptureEntry = NULL;
  20489. BfParameterDef* paramDef = NULL;
  20490. int paramDefIdx = -1;
  20491. if (paramIdx < implicitParamCount)
  20492. closureCaptureEntry = &methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries[paramIdx];
  20493. else
  20494. {
  20495. paramDefIdx = paramIdx - implicitParamCount;
  20496. paramDef = methodDef->mParams[paramDefIdx];
  20497. }
  20498. if (hadParams)
  20499. break;
  20500. if ((paramDef != NULL) && (paramDef->mParamKind == BfParamKind_VarArgs))
  20501. continue;
  20502. if ((paramDef != NULL) && (mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL) &&
  20503. (paramDef->mParamKind != BfParamKind_AppendIdx))
  20504. {
  20505. mCompiler->mResolvePassData->mAutoComplete->CheckTypeRef(paramDef->mTypeRef, false);
  20506. if (mCompiler->mResolvePassData->mAutoComplete->IsAutocompleteNode(paramDef->mTypeRef))
  20507. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("token", "in"), paramDef->mTypeRef->ToString());
  20508. }
  20509. if ((paramDef != NULL) && (paramDef->mParamDeclaration != NULL) && (paramDef->mParamDeclaration->mAttributes != NULL))
  20510. {
  20511. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes == NULL)
  20512. methodInstance->mMethodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  20513. while ((int)methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.size() < paramIdx)
  20514. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.push_back(NULL);
  20515. auto customAttributes = GetCustomAttributes(paramDef->mParamDeclaration->mAttributes, BfAttributeTargets_Parameter);
  20516. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.push_back(customAttributes);
  20517. }
  20518. BfType* resolvedParamType = NULL;
  20519. if (closureCaptureEntry != NULL)
  20520. resolvedParamType = closureCaptureEntry->mType;
  20521. else if ((paramDef->mTypeRef != NULL) && (paramDef->mTypeRef->IsA<BfLetTypeReference>()))
  20522. {
  20523. Fail("Cannot declare 'let' parameters", paramDef->mTypeRef);
  20524. resolvedParamType = mContext->mBfObjectType;
  20525. }
  20526. else if ((paramDef->mTypeRef != NULL) && (paramDef->mTypeRef->IsA<BfVarTypeReference>()))
  20527. {
  20528. if (methodDef->mMethodType != BfMethodType_Mixin)
  20529. {
  20530. Fail("Cannot declare var parameters", paramDef->mTypeRef);
  20531. resolvedParamType = mContext->mBfObjectType;
  20532. }
  20533. else
  20534. resolvedParamType = GetPrimitiveType(BfTypeCode_Var);
  20535. }
  20536. BfType* unresolvedParamType = resolvedParamType;
  20537. bool wasGenericParam = false;
  20538. if (resolvedParamType == NULL)
  20539. {
  20540. BfResolveTypeRefFlags resolveFlags = (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_AllowRef | BfResolveTypeRefFlag_AllowRefGeneric | BfResolveTypeRefFlag_AllowGenericMethodParamConstValue);
  20541. if (paramDef->mParamKind == BfParamKind_ExplicitThis)
  20542. resolveFlags = (BfResolveTypeRefFlags)(resolveFlags | BfResolveTypeRefFlag_NoWarnOnMut);
  20543. resolvedParamType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration, resolveFlags);
  20544. if ((paramDef->mParamKind == BfParamKind_ExplicitThis) && (resolvedParamType != NULL) && (resolvedParamType->IsRef()))
  20545. resolvedParamType = resolvedParamType->GetUnderlyingType();
  20546. }
  20547. if (resolvedParamType == NULL)
  20548. {
  20549. resolvedParamType = GetPrimitiveType(BfTypeCode_Var);
  20550. unresolvedParamType = resolvedParamType;
  20551. if (mCurTypeInstance->IsBoxed())
  20552. {
  20553. auto boxedType = (BfBoxedType*)mCurTypeInstance;
  20554. // If we failed a lookup here then we better have also failed it in the original type
  20555. BF_ASSERT(boxedType->mElementType->ToTypeInstance()->mModule->mHadBuildError || mContext->mFailTypes.Contains(boxedType->mElementType->ToTypeInstance()));
  20556. }
  20557. }
  20558. BF_ASSERT(!resolvedParamType->IsDeleting());
  20559. if (!methodInstance->IsSpecializedGenericMethod())
  20560. AddDependency(resolvedParamType, typeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  20561. PopulateType(resolvedParamType, BfPopulateType_Declaration);
  20562. AddDependency(resolvedParamType, mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
  20563. if ((paramDef != NULL) && (paramDef->mParamDeclaration != NULL) && (paramDef->mParamDeclaration->mInitializer != NULL) &&
  20564. (!paramDef->mParamDeclaration->mInitializer->IsA<BfBlock>()))
  20565. {
  20566. if (paramDef->mParamKind == BfParamKind_Params)
  20567. {
  20568. BfAstNode* refNode = paramDef->mParamDeclaration->mEqualsNode;
  20569. if (refNode != NULL)
  20570. refNode = paramDef->mParamDeclaration->mModToken;
  20571. Fail("Cannot specify a default value for a 'params' parameter", refNode);
  20572. }
  20573. BfTypedValue defaultValue;
  20574. if (resolvedParamType->IsConstExprValue())
  20575. {
  20576. auto constExprType = (BfConstExprValueType*)resolvedParamType;
  20577. BfExprEvaluator exprEvaluator(this);
  20578. exprEvaluator.mExpectingType = constExprType->mType;
  20579. exprEvaluator.GetLiteral(NULL, constExprType->mValue);
  20580. defaultValue = exprEvaluator.GetResult();
  20581. }
  20582. else
  20583. {
  20584. BfTypeState typeState;
  20585. typeState.mType = mCurTypeInstance;
  20586. typeState.mCurTypeDef = methodDef->mDeclaringType;
  20587. //typeState.mCurMethodDef = methodDef;
  20588. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  20589. BfConstResolver constResolver(this);
  20590. defaultValue = constResolver.Resolve(paramDef->mParamDeclaration->mInitializer, resolvedParamType, (BfConstResolveFlags)(BfConstResolveFlag_NoCast | BfConstResolveFlag_AllowGlobalVariable));
  20591. if ((defaultValue) && (defaultValue.mType != resolvedParamType))
  20592. {
  20593. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  20594. auto castedDefaultValue = Cast(paramDef->mParamDeclaration->mInitializer, defaultValue, resolvedParamType, (BfCastFlags)(BfCastFlags_SilentFail | BfCastFlags_NoConversionOperator));
  20595. if ((castedDefaultValue) && (castedDefaultValue.mValue.IsConst()))
  20596. {
  20597. defaultValue = castedDefaultValue; // Good!
  20598. }
  20599. else if (!CanCast(defaultValue, resolvedParamType))
  20600. {
  20601. // We only care that we get a constant value that can be implicitly casted at the callsite- even if that requires
  20602. // a conversion operator.
  20603. // This should throw an error
  20604. defaultValue = Cast(paramDef->mParamDeclaration->mInitializer, defaultValue, resolvedParamType);
  20605. AssertErrorState();
  20606. if (!defaultValue.mValue.IsConst())
  20607. defaultValue = BfTypedValue();
  20608. }
  20609. }
  20610. }
  20611. if (!defaultValue)
  20612. {
  20613. defaultValue = GetDefaultTypedValue(resolvedParamType);
  20614. if (!defaultValue.mValue.IsConst())
  20615. defaultValue = BfTypedValue();
  20616. }
  20617. if (defaultValue)
  20618. {
  20619. if (defaultValue.mType->IsVar())
  20620. {
  20621. AssertErrorState();
  20622. }
  20623. else
  20624. {
  20625. BF_ASSERT(defaultValue.mValue.IsConst());
  20626. while ((int)mCurMethodInstance->mDefaultValues.size() < paramDefIdx)
  20627. mCurMethodInstance->mDefaultValues.Add(BfTypedValue());
  20628. CurrentAddToConstHolder(defaultValue.mValue);
  20629. mCurMethodInstance->mDefaultValues.Add(defaultValue);
  20630. }
  20631. }
  20632. }
  20633. if ((paramDef != NULL) && (paramDef->mParamKind == BfParamKind_Params))
  20634. {
  20635. bool addParams = true;
  20636. bool isValid = false;
  20637. auto resolvedParamTypeInst = resolvedParamType->ToTypeInstance();
  20638. if ((resolvedParamTypeInst != NULL) && (resolvedParamTypeInst->IsInstanceOf(mCompiler->mSpanTypeDef)))
  20639. {
  20640. // Span<T>
  20641. isValid = true;
  20642. }
  20643. else if (resolvedParamType->IsArray())
  20644. {
  20645. // Array is the 'normal' params type
  20646. isValid = true;
  20647. }
  20648. else if (resolvedParamType->IsSizedArray())
  20649. {
  20650. isValid = true;
  20651. }
  20652. else if (resolvedParamType->IsVar())
  20653. {
  20654. isValid = true;
  20655. }
  20656. else if ((resolvedParamType->IsDelegate()) || (resolvedParamType->IsFunction()) || (resolvedParamType->IsMethodRef()))
  20657. {
  20658. hadDelegateParams = true;
  20659. // This means we copy the params from a delegate
  20660. BfMethodParam methodParam;
  20661. methodParam.mResolvedType = resolvedParamType;
  20662. methodParam.mParamDefIdx = paramDefIdx;
  20663. methodParam.mDelegateParamIdx = 0;
  20664. auto invokeMethodInstance = methodParam.GetDelegateParamInvoke();
  20665. for (int delegateParamIdx = 0; delegateParamIdx < invokeMethodInstance->GetParamCount(); delegateParamIdx++)
  20666. {
  20667. methodParam.mDelegateParamIdx = delegateParamIdx;
  20668. mCurMethodInstance->mParams.Add(methodParam);
  20669. auto paramType = invokeMethodInstance->GetParamType(delegateParamIdx);
  20670. if (!methodInstance->IsSpecializedGenericMethod())
  20671. AddDependency(paramType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  20672. }
  20673. isValid = true;
  20674. addParams = false;
  20675. }
  20676. else if (resolvedParamType->IsGenericParam())
  20677. {
  20678. auto genericParamInstance = GetGenericParamInstance((BfGenericParamType*)resolvedParamType);
  20679. if (genericParamInstance->mTypeConstraint != NULL)
  20680. {
  20681. auto typeInstConstraint = genericParamInstance->mTypeConstraint->ToTypeInstance();
  20682. if ((genericParamInstance->mTypeConstraint->IsArray()) || (genericParamInstance->mTypeConstraint->IsSizedArray()))
  20683. {
  20684. BfMethodParam methodParam;
  20685. methodParam.mResolvedType = resolvedParamType;
  20686. methodParam.mParamDefIdx = paramDefIdx;
  20687. mCurMethodInstance->mParams.Add(methodParam);
  20688. isValid = true;
  20689. }
  20690. else if ((genericParamInstance->mTypeConstraint->IsDelegate()) || (genericParamInstance->mTypeConstraint->IsFunction()) ||
  20691. ((genericParamInstance != NULL) && (typeInstConstraint != NULL) &&
  20692. ((typeInstConstraint->IsInstanceOf(mCompiler->mDelegateTypeDef)) || (typeInstConstraint->IsInstanceOf(mCompiler->mFunctionTypeDef)))))
  20693. {
  20694. mCurMethodInstance->mHadGenericDelegateParams = true;
  20695. isValid = true;
  20696. addParams = false;
  20697. }
  20698. }
  20699. }
  20700. else
  20701. {
  20702. auto paramTypeInst = resolvedParamType->ToTypeInstance();
  20703. if ((paramTypeInst != NULL) &&
  20704. ((paramTypeInst->IsInstanceOf(mCompiler->mDelegateTypeDef)) || (paramTypeInst->IsInstanceOf(mCompiler->mFunctionTypeDef))))
  20705. {
  20706. // If we have a 'params T' and 'T' gets specialized with actually 'Delegate' or 'Function' then just ignore it
  20707. isValid = true;
  20708. addParams = false;
  20709. }
  20710. }
  20711. if (!isValid)
  20712. {
  20713. Fail("Parameters with 'params' specifiers can only be used for array, span, delegate, or function types", paramDef->mParamDeclaration->mModToken);
  20714. // Failure case, make it an Object[]
  20715. resolvedParamType = CreateArrayType(mContext->mBfObjectType, 1);
  20716. }
  20717. if ((addParams) && (resolvedParamType != NULL))
  20718. {
  20719. BfMethodParam methodParam;
  20720. methodParam.mResolvedType = resolvedParamType;
  20721. methodParam.mParamDefIdx = paramDefIdx;
  20722. mCurMethodInstance->mParams.push_back(methodParam);
  20723. }
  20724. if (paramDefIdx < (int)methodDef->mParams.size() - 1)
  20725. {
  20726. Fail("Only the last parameter can specify 'params'", paramDef->mParamDeclaration->mModToken);
  20727. }
  20728. }
  20729. else
  20730. {
  20731. BfMethodParam methodParam;
  20732. methodParam.mResolvedType = resolvedParamType;
  20733. methodParam.mParamDefIdx = paramDefIdx;
  20734. mCurMethodInstance->mParams.Add(methodParam);
  20735. }
  20736. }
  20737. if (hadDelegateParams)
  20738. {
  20739. HashSet<String> usedNames;
  20740. Dictionary<int, int> usedParamDefIdx;
  20741. for (auto methodParam : methodDef->mParams)
  20742. {
  20743. usedNames.Add(methodParam->mName);
  20744. }
  20745. for (auto& methodParam : mCurMethodInstance->mParams)
  20746. {
  20747. if ((methodParam.mParamDefIdx != -1) && (methodParam.mDelegateParamIdx == 0))
  20748. {
  20749. int* refCount = NULL;
  20750. usedParamDefIdx.TryAdd(methodParam.mParamDefIdx, NULL, &refCount);
  20751. (*refCount)++;
  20752. }
  20753. }
  20754. for (auto& methodParam : mCurMethodInstance->mParams)
  20755. {
  20756. if (methodParam.mDelegateParamIdx != -1)
  20757. {
  20758. if (usedParamDefIdx[methodParam.mParamDefIdx] > 1)
  20759. methodParam.mDelegateParamNameCombine = true;
  20760. BfMethodInstance* invokeMethodInstance = methodParam.GetDelegateParamInvoke();
  20761. String paramName = invokeMethodInstance->GetParamName(methodParam.mDelegateParamIdx);
  20762. if (usedNames.Contains(paramName))
  20763. methodParam.mDelegateParamNameCombine = true;
  20764. }
  20765. }
  20766. }
  20767. int argIdx = 0;
  20768. PopulateType(methodInstance->mReturnType, BfPopulateType_Data);
  20769. if ((!methodDef->mIsStatic) && (!methodDef->mHasExplicitThis))
  20770. {
  20771. int thisIdx = methodDef->mHasExplicitThis ? 0 : -1;
  20772. auto thisType = methodInstance->GetOwner();
  20773. if (methodInstance->GetParamIsSplat(thisIdx))
  20774. argIdx += methodInstance->GetParamType(thisIdx)->GetSplatCount();
  20775. else if (!thisType->IsValuelessType())
  20776. {
  20777. BfTypeCode loweredTypeCode = BfTypeCode_None;
  20778. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  20779. if ((!mIsComptimeModule) && (!methodDef->mIsMutating))
  20780. thisType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2);
  20781. argIdx++;
  20782. if (loweredTypeCode2 != BfTypeCode_None)
  20783. argIdx++;
  20784. }
  20785. }
  20786. if ((!mIsComptimeModule) && (methodInstance->GetStructRetIdx() != -1))
  20787. argIdx++;
  20788. for (int paramIdx = 0; paramIdx < mCurMethodInstance->mParams.size(); paramIdx++)
  20789. {
  20790. auto& methodParam = mCurMethodInstance->mParams[paramIdx];
  20791. BfType* checkType = methodParam.mResolvedType;
  20792. int checkArgIdx = argIdx;
  20793. if ((paramIdx == 0) && (methodDef->mHasExplicitThis))
  20794. {
  20795. checkArgIdx = 0;
  20796. checkType = methodInstance->GetThisType();
  20797. }
  20798. if (checkType->IsMethodRef())
  20799. {
  20800. methodParam.mIsSplat = true;
  20801. }
  20802. else if ((checkType->IsComposite()) && (methodInstance->AllowsSplatting(paramIdx)))
  20803. {
  20804. PopulateType(checkType, BfPopulateType_Data);
  20805. if (checkType->IsSplattable())
  20806. {
  20807. bool isSplat = false;
  20808. auto checkTypeInstance = checkType->ToTypeInstance();
  20809. if ((checkTypeInstance != NULL) && (checkTypeInstance->mIsCRepr))
  20810. isSplat = true;
  20811. int splatCount = checkType->GetSplatCount();
  20812. if (checkArgIdx + splatCount <= mCompiler->mOptions.mMaxSplatRegs)
  20813. isSplat = true;
  20814. if (isSplat)
  20815. {
  20816. methodParam.mIsSplat = true;
  20817. argIdx += splatCount;
  20818. continue;
  20819. }
  20820. }
  20821. else if (!checkType->IsValuelessType())
  20822. {
  20823. BfTypeCode loweredTypeCode = BfTypeCode_None;
  20824. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  20825. if (!mIsComptimeModule)
  20826. checkType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2);
  20827. argIdx++;
  20828. if (loweredTypeCode2 != BfTypeCode_None)
  20829. argIdx++;
  20830. continue;
  20831. }
  20832. }
  20833. argIdx++;
  20834. }
  20835. bool hasExternSpecifier = (methodDeclaration != NULL) && (methodDeclaration->mExternSpecifier != NULL);
  20836. if ((hasExternSpecifier) && (methodDeclaration->mBody != NULL))
  20837. {
  20838. Fail("Cannot 'extern' and declare a body", methodDeclaration->mExternSpecifier);
  20839. }
  20840. else if ((methodDeclaration != NULL) && (methodDeclaration->mBody == NULL) && (!hasExternSpecifier) &&
  20841. (!typeInstance->IsInterface()) && (!mCurTypeInstance->IsDelegate()) && (!mCurTypeInstance->IsFunction()) &&
  20842. (!methodDef->mIsPartial) && (!methodDef->mIsAbstract) &&
  20843. (!methodDef->mIsSkipCall))
  20844. {
  20845. if (methodDeclaration->mEndSemicolon == NULL)
  20846. {
  20847. if (auto autoCtorDecl = BfNodeDynCast<BfAutoConstructorDeclaration>(methodDeclaration))
  20848. {
  20849. //
  20850. }
  20851. else
  20852. AssertParseErrorState();
  20853. }
  20854. else
  20855. {
  20856. bool isError = true;
  20857. if (typeInstance->IsTypedPrimitive())
  20858. {
  20859. if (auto operatorDeclaration = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  20860. {
  20861. if ((operatorDeclaration->mIsConvOperator) && (methodInstance->mParams.size() == 1))
  20862. {
  20863. if (((methodInstance->mReturnType == typeInstance) && (methodInstance->GetParamType(0) == typeInstance->GetUnderlyingType())) ||
  20864. ((methodInstance->mReturnType == typeInstance->GetUnderlyingType()) && (methodInstance->GetParamType(0) == typeInstance)))
  20865. {
  20866. isError = false;
  20867. }
  20868. }
  20869. }
  20870. }
  20871. if (isError)
  20872. {
  20873. Fail(StrFormat("'%s' must declare a body because it is not marked abstract, extern, or partial",
  20874. MethodToString(methodInstance).c_str()),
  20875. methodDef->GetRefNode());
  20876. }
  20877. }
  20878. }
  20879. if (methodDef->IsEmptyPartial())
  20880. hasExternSpecifier = true;
  20881. if (!methodInstance->IsAutocompleteMethod())
  20882. {
  20883. auto defaultMethodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  20884. int implicitParamCount = methodInstance->GetImplicitParamCount();
  20885. int defaultImplicitParamCount = defaultMethodInstance->GetImplicitParamCount();
  20886. int actualParamCount = (int)methodInstance->mParams.size() - implicitParamCount;
  20887. BF_ASSERT((actualParamCount == defaultMethodInstance->mParams.size() - defaultImplicitParamCount) || (defaultMethodInstance->mHadGenericDelegateParams));
  20888. mCurMethodInstance->mHadGenericDelegateParams = defaultMethodInstance->mHadGenericDelegateParams;
  20889. int paramIdx = 0;
  20890. int defaultParamIdx = 0;
  20891. while (true)
  20892. {
  20893. bool isDone = paramIdx + implicitParamCount >= (int)methodInstance->mParams.size();
  20894. bool isDefaultDone = defaultParamIdx + defaultImplicitParamCount >= (int)defaultMethodInstance->mParams.size();
  20895. if ((!isDone) && (methodInstance->mParams[paramIdx + implicitParamCount].mDelegateParamIdx >= 0))
  20896. {
  20897. paramIdx++;
  20898. continue;
  20899. }
  20900. if ((!isDefaultDone) && (defaultMethodInstance->mParams[defaultParamIdx + defaultImplicitParamCount].mDelegateParamIdx >= 0))
  20901. {
  20902. defaultParamIdx++;
  20903. continue;
  20904. }
  20905. if ((isDone) || (isDefaultDone))
  20906. {
  20907. // 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
  20908. // to cause us to throw an assertion in the declaration here
  20909. if ((!defaultMethodInstance->mHadGenericDelegateParams) && (!methodInstance->mHasFailed) && (!defaultMethodInstance->mHasFailed))
  20910. BF_ASSERT((isDone) && (isDefaultDone));
  20911. break;
  20912. }
  20913. BfType* paramType = defaultMethodInstance->mParams[defaultParamIdx + defaultImplicitParamCount].mResolvedType;
  20914. if (paramType->IsRef())
  20915. paramType = paramType->GetUnderlyingType();
  20916. methodInstance->mParams[paramIdx + implicitParamCount].mWasGenericParam = paramType->IsGenericParam();
  20917. paramIdx++;
  20918. defaultParamIdx++;
  20919. }
  20920. }
  20921. StringT<4096> mangledName;
  20922. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  20923. for (int paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  20924. {
  20925. auto paramType = methodInstance->GetParamType(paramIdx);
  20926. if (paramType->IsComposite())
  20927. PopulateType(paramType, BfPopulateType_Data);
  20928. if (!methodInstance->IsParamSkipped(paramIdx))
  20929. {
  20930. if (paramType->IsStruct())
  20931. {
  20932. //
  20933. }
  20934. else
  20935. {
  20936. PopulateType(paramType, BfPopulateType_Declaration);
  20937. }
  20938. }
  20939. }
  20940. // Only process method in default unspecialized mode, not in variations
  20941. if (methodInstance->mIsUnspecializedVariation)
  20942. return;
  20943. PopulateType(resolvedReturnType, BfPopulateType_Data);
  20944. auto retLLVMType = mBfIRBuilder->MapType(resolvedReturnType);
  20945. if (resolvedReturnType->IsValuelessType())
  20946. retLLVMType = mBfIRBuilder->GetPrimitiveType(BfTypeCode_None);
  20947. if (!mBfIRBuilder->mIgnoreWrites)
  20948. {
  20949. bool isIntrinsic = false;
  20950. if (!methodInstance->mIRFunction)
  20951. SetupIRFunction(methodInstance, mangledName, isTemporaryFunc, &isIntrinsic);
  20952. if (isIntrinsic)
  20953. {
  20954. addToWorkList = false;
  20955. }
  20956. }
  20957. else
  20958. {
  20959. GetMethodCustomAttributes(methodInstance);
  20960. }
  20961. auto func = methodInstance->mIRFunction;
  20962. // if (methodInstance->mIsReified)
  20963. // CheckHotMethod(methodInstance, mangledName);
  20964. for (auto& param : methodInstance->mParams)
  20965. {
  20966. BF_ASSERT(!param.mResolvedType->IsDeleting());
  20967. }
  20968. 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);
  20969. SizedArray<BfIRMDNode, 8> diParams;
  20970. diParams.push_back(mBfIRBuilder->DbgGetType(resolvedReturnType));
  20971. if ((!methodDef->mIsStatic) && (typeDef->mIsStatic) && (methodDef->mMethodDeclaration != NULL))
  20972. {
  20973. //CS0708
  20974. Fail("Cannot declare instance members in a static class", methodDef->GetRefNode());
  20975. }
  20976. if ((methodDef->mIsVirtual) && (methodDef->mGenericParams.size() != 0))
  20977. {
  20978. Fail("Virtual generic methods not supported", methodDeclaration->mVirtualSpecifier);
  20979. methodDef->mIsVirtual = false;
  20980. }
  20981. BfAstNode* mutSpecifier = NULL;
  20982. if (methodDeclaration != NULL)
  20983. mutSpecifier = methodDeclaration->mMutSpecifier;
  20984. else if (methodDef->GetPropertyMethodDeclaration() != NULL)
  20985. {
  20986. mutSpecifier = methodDef->GetPropertyMethodDeclaration()->mMutSpecifier;
  20987. if (mutSpecifier == NULL)
  20988. {
  20989. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  20990. if (propertyDeclaration != NULL)
  20991. {
  20992. if (auto propExprBody = BfNodeDynCast<BfPropertyBodyExpression>(propertyDeclaration->mDefinitionBlock))
  20993. mutSpecifier = propExprBody->mMutSpecifier;
  20994. }
  20995. }
  20996. }
  20997. if ((mutSpecifier != NULL) && (!mCurTypeInstance->IsBoxed()) && (!methodInstance->mIsForeignMethodDef))
  20998. {
  20999. if (methodDef->mIsStatic)
  21000. Warn(0, "Unnecessary 'mut' specifier, static methods have no implicit 'this' target to mutate", mutSpecifier);
  21001. else if ((!mCurTypeInstance->IsValueType()) && (!mCurTypeInstance->IsInterface()))
  21002. Warn(0, "Unnecessary 'mut' specifier, methods of reference types are implicitly mutating", mutSpecifier);
  21003. else if (methodDef->mMethodType == BfMethodType_Ctor)
  21004. Warn(0, "Unnecessary 'mut' specifier, constructors are implicitly mutating", mutSpecifier);
  21005. else if (methodDef->mMethodType == BfMethodType_Dtor)
  21006. Warn(0, "Unnecessary 'mut' specifier, destructors are implicitly mutating", mutSpecifier);
  21007. }
  21008. if (isTemporaryFunc)
  21009. {
  21010. // This handles temporary methods for autocomplete types
  21011. //BF_ASSERT(mIsScratchModule);
  21012. //BF_ASSERT(mCompiler->IsAutocomplete());
  21013. BfLogSysM("DoMethodDeclaration isTemporaryFunc bailout\n");
  21014. return; // Bail out early for autocomplete pass
  21015. }
  21016. //TODO: We used to have this (this != mContext->mExternalFuncModule) check, but it caused us to keep around
  21017. // an invalid mFuncRefernce (which came from GetMethodInstanceAtIdx) which later got remapped by the
  21018. // autocompleter. Why did we have this check anyway?
  21019. /*if ((typeInstance->mContext != mContext) && (!methodDef->IsEmptyPartial()))
  21020. {
  21021. AddMethodReference(methodInstance);
  21022. mFuncReferences[methodInstance] = func;
  21023. BfLogSysM("Adding func reference (DoMethodDeclaration). Module:%p MethodInst:%p LLVMFunc:%p\n", this, methodInstance, func);
  21024. }*/
  21025. if (mParentModule != NULL)
  21026. {
  21027. // For extension modules we need to keep track of our own methods so we can know which methods
  21028. // we have defined ourselves and which are from the parent module or other extensions
  21029. if (!func.IsFake())
  21030. {
  21031. if (func)
  21032. mFuncReferences[methodInstance] = func;
  21033. }
  21034. }
  21035. if (methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet)
  21036. {
  21037. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingDecl;
  21038. auto owningModule = methodInstance->GetOwner()->mModule;
  21039. if (!owningModule->mIsScratchModule)
  21040. owningModule->mOnDemandMethodCount++;
  21041. VerifyOnDemandMethods();
  21042. }
  21043. bool wasAwaitingDecl = methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl;
  21044. if (wasAwaitingDecl)
  21045. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingReference;
  21046. if (addToWorkList)
  21047. {
  21048. if ((!methodDef->mIsAbstract) && (!methodInstance->mIgnoreBody))
  21049. {
  21050. AddMethodToWorkList(methodInstance);
  21051. }
  21052. else
  21053. {
  21054. BfLogSysM("DoMethodDeclaration ignoring method body %d %d %d\n", hasExternSpecifier, methodDef->mIsAbstract, methodInstance->mIgnoreBody);
  21055. methodInstance->mIgnoreBody = true;
  21056. if (typeInstance->IsUnspecializedType())
  21057. {
  21058. // Don't hold on to actual Function for unspecialized types
  21059. methodInstance->mIRFunction = BfIRFunction();
  21060. }
  21061. }
  21062. }
  21063. else
  21064. {
  21065. //BF_ASSERT(methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference);
  21066. }
  21067. if ((!methodInstance->IsSpecializedGenericMethodOrType()) && (!mCurTypeInstance->IsBoxed()) &&
  21068. (!methodDef->mIsLocalMethod) &&
  21069. (!CheckDefineMemberProtection(methodDef->mProtection, methodInstance->mReturnType)) &&
  21070. (!methodDef->mReturnTypeRef->IsTemporary()))
  21071. {
  21072. if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  21073. {
  21074. //TODO:
  21075. //CS0053
  21076. Fail(StrFormat("Inconsistent accessibility: property type '%s' is less accessible than property '%s'",
  21077. TypeToString(methodInstance->mReturnType).c_str(), MethodToString(methodInstance).c_str()),
  21078. methodDef->mReturnTypeRef, true);
  21079. }
  21080. else
  21081. {
  21082. //CS0050
  21083. Fail(StrFormat("Inconsistent accessibility: return type '%s' is less accessible than method '%s'",
  21084. TypeToString(methodInstance->mReturnType).c_str(), MethodToString(methodInstance).c_str()),
  21085. methodDef->mReturnTypeRef, true);
  21086. }
  21087. }
  21088. if (typeInstance->IsInterface())
  21089. {
  21090. if (methodDef->mMethodType == BfMethodType_Ctor)
  21091. Fail("Interfaces cannot contain constructors", methodDeclaration);
  21092. if (methodDeclaration != NULL)
  21093. {
  21094. if (methodDef->mBody == NULL)
  21095. {
  21096. if (methodDef->mProtection != BfProtection_Public) //TODO: MAKE AN ERROR
  21097. Warn(0, "Protection specifiers can only be used with interface methods containing a default implementation body", methodDeclaration->mProtectionSpecifier);
  21098. if ((methodDeclaration->mVirtualSpecifier != NULL) &&
  21099. (methodDeclaration->mVirtualSpecifier->mToken != BfToken_Abstract) &&
  21100. (methodDeclaration->mVirtualSpecifier->mToken != BfToken_Concrete)) //TODO: MAKE AN ERROR
  21101. Warn(0, "Virtual specifiers can only be used with interface methods containing a default implementation body", methodDeclaration->mVirtualSpecifier);
  21102. }
  21103. }
  21104. }
  21105. bool foundHiddenMethod = false;
  21106. BfTokenNode* virtualToken = NULL;
  21107. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  21108. if (propertyDeclaration != NULL)
  21109. virtualToken = propertyDeclaration->mVirtualSpecifier;
  21110. else if (methodDeclaration != NULL)
  21111. virtualToken = methodDeclaration->mVirtualSpecifier;
  21112. // Don't compare specialized generic methods against normal methods
  21113. if ((((mCurMethodInstance->mIsUnspecialized) || (mCurMethodInstance->mMethodDef->mGenericParams.size() == 0))) &&
  21114. (!methodDef->mIsLocalMethod) && (!mCurTypeInstance->IsUnspecializedTypeVariation()))
  21115. {
  21116. if ((!methodInstance->mIsForeignMethodDef) && (methodDef->mMethodType != BfMethodType_Init))
  21117. {
  21118. typeDef->PopulateMemberSets();
  21119. BfMethodDef* nextMethod = NULL;
  21120. BfMemberSetEntry* entry = NULL;
  21121. if (typeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  21122. nextMethod = (BfMethodDef*)entry->mMemberDef;
  21123. while (nextMethod != NULL)
  21124. {
  21125. auto checkMethod = nextMethod;
  21126. nextMethod = nextMethod->mNextWithSameName;
  21127. if (checkMethod == methodDef)
  21128. continue;
  21129. auto checkMethodInstance = typeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  21130. if (checkMethodInstance == NULL)
  21131. {
  21132. if ((methodDef->mDeclaringType->IsExtension()) && (!checkMethod->mDeclaringType->IsExtension()))
  21133. checkMethodInstance = GetRawMethodInstanceAtIdx(typeInstance, checkMethod->mIdx);
  21134. if (checkMethodInstance == NULL)
  21135. continue;
  21136. }
  21137. if (((checkMethodInstance->mChainType == BfMethodChainType_None) || (checkMethodInstance->mChainType == BfMethodChainType_ChainHead)) &&
  21138. (checkMethodInstance->GetExplicitInterface() == methodInstance->GetExplicitInterface()) &&
  21139. (checkMethod->mIsMutating == methodDef->mIsMutating) &&
  21140. (CompareMethodSignatures(checkMethodInstance, mCurMethodInstance)))
  21141. {
  21142. bool canChain = false;
  21143. if ((methodDef->mParams.empty()) &&
  21144. (checkMethodInstance->mMethodDef->mIsStatic == methodInstance->mMethodDef->mIsStatic))
  21145. {
  21146. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) || (methodDef->mMethodType == BfMethodType_Dtor))
  21147. canChain = true;
  21148. else if (methodDef->mMethodType == BfMethodType_Normal)
  21149. {
  21150. if ((methodDef->mName == BF_METHODNAME_MARKMEMBERS) ||
  21151. (methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC) ||
  21152. (methodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS))
  21153. canChain = true;
  21154. }
  21155. }
  21156. if (canChain)
  21157. {
  21158. bool isBetter;
  21159. bool isWorse;
  21160. CompareDeclTypes(checkMethodInstance->mMethodDef->mDeclaringType, methodInstance->mMethodDef->mDeclaringType, isBetter, isWorse);
  21161. if (isBetter && !isWorse)
  21162. {
  21163. methodInstance->mChainType = BfMethodChainType_ChainHead;
  21164. checkMethodInstance->mChainType = BfMethodChainType_ChainMember;
  21165. }
  21166. else
  21167. {
  21168. checkMethodInstance->mChainType = BfMethodChainType_ChainHead;
  21169. methodInstance->mChainType = BfMethodChainType_ChainMember;
  21170. }
  21171. }
  21172. else
  21173. {
  21174. if (!typeInstance->IsTypeMemberAccessible(checkMethod->mDeclaringType, methodDef->mDeclaringType))
  21175. continue;
  21176. bool silentlyAllow = false;
  21177. bool extensionWarn = false;
  21178. if (checkMethod->mDeclaringType != methodDef->mDeclaringType)
  21179. {
  21180. if (typeInstance->IsInterface())
  21181. {
  21182. if (methodDef->mIsOverride)
  21183. silentlyAllow = true;
  21184. }
  21185. else
  21186. {
  21187. if ((methodDef->mIsOverride) && (checkMethod->mIsExtern))
  21188. {
  21189. silentlyAllow = true;
  21190. methodInstance->mIsInnerOverride = true;
  21191. CheckOverridenMethod(methodInstance, checkMethodInstance);
  21192. }
  21193. else if (!checkMethod->mDeclaringType->IsExtension())
  21194. {
  21195. foundHiddenMethod = true;
  21196. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mIsStatic))
  21197. silentlyAllow = true;
  21198. else if (methodDef->mIsNew)
  21199. {
  21200. silentlyAllow = true;
  21201. }
  21202. else if (checkMethod->GetMethodDeclaration() == NULL)
  21203. silentlyAllow = true;
  21204. else if (methodDef->mIsOverride)
  21205. silentlyAllow = true;
  21206. else
  21207. extensionWarn = true;
  21208. }
  21209. else
  21210. silentlyAllow = true;
  21211. }
  21212. }
  21213. if ((checkMethod->mCommutableKind == BfCommutableKind_Reverse) || (methodDef->mCommutableKind == BfCommutableKind_Reverse))
  21214. silentlyAllow = true;
  21215. if (!silentlyAllow)
  21216. {
  21217. if ((!methodDef->mName.IsEmpty()) || (checkMethodInstance->mMethodDef->mIsOperator))
  21218. {
  21219. auto refNode = methodDef->GetRefNode();
  21220. BfError* bfError;
  21221. if (extensionWarn)
  21222. {
  21223. if (methodDef->mDeclaringType->mProject != checkMethod->mDeclaringType->mProject)
  21224. bfError = Warn(BfWarning_CS0114_MethodHidesInherited,
  21225. 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'.",
  21226. checkMethod->mDeclaringType->mProject->mName.c_str()), refNode);
  21227. else
  21228. bfError = Warn(BfWarning_CS0114_MethodHidesInherited,
  21229. "This method hides a method in the root type definition. Use the 'new' keyword if the hiding was intentional.", refNode);
  21230. }
  21231. else
  21232. {
  21233. bfError = Fail(StrFormat("Method '%s' already declared with the same parameter types", MethodToString(checkMethodInstance).c_str()), refNode, true);
  21234. }
  21235. if ((bfError != NULL) && (checkMethod->GetRefNode() != refNode))
  21236. mCompiler->mPassInstance->MoreInfo("First declaration", checkMethod->GetRefNode());
  21237. }
  21238. }
  21239. }
  21240. }
  21241. }
  21242. }
  21243. // Virtual methods give their error while slotting
  21244. if ((!typeInstance->IsBoxed()) && (!methodDef->mIsVirtual) && (methodDef->mProtection != BfProtection_Private) &&
  21245. (!methodDef->mIsLocalMethod) &&
  21246. (!methodInstance->mIsForeignMethodDef) && (typeInstance->mBaseType != NULL) &&
  21247. (methodDef->mMethodType == BfMethodType_Normal) && (methodDef->mMethodDeclaration != NULL))
  21248. {
  21249. auto baseType = typeInstance->mBaseType;
  21250. while (baseType != NULL)
  21251. {
  21252. auto baseTypeDef = baseType->mTypeDef;
  21253. baseTypeDef->PopulateMemberSets();
  21254. BfMethodDef* checkMethod = NULL;
  21255. BfMemberSetEntry* entry = NULL;
  21256. if (baseTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  21257. checkMethod = (BfMethodDef*)entry->mMemberDef;
  21258. while (checkMethod != NULL)
  21259. {
  21260. if (checkMethod->mMethodDeclaration == NULL)
  21261. {
  21262. checkMethod = checkMethod->mNextWithSameName;
  21263. continue;
  21264. }
  21265. if (baseType->mMethodInstanceGroups.size() == 0)
  21266. {
  21267. BF_ASSERT(baseType->IsIncomplete() && mCompiler->IsAutocomplete());
  21268. break;
  21269. }
  21270. if (checkMethod == methodDef)
  21271. {
  21272. checkMethod = checkMethod->mNextWithSameName;
  21273. continue;
  21274. }
  21275. if (checkMethod->mName != methodDef->mName)
  21276. {
  21277. checkMethod = checkMethod->mNextWithSameName;
  21278. continue;
  21279. }
  21280. auto checkMethodInstance = GetRawMethodInstanceAtIdx(baseType, checkMethod->mIdx);
  21281. if (checkMethodInstance != NULL)
  21282. {
  21283. if ((checkMethodInstance->GetExplicitInterface() == methodInstance->GetExplicitInterface()) &&
  21284. (checkMethod->mProtection != BfProtection_Private) &&
  21285. (CompareMethodSignatures(checkMethodInstance, mCurMethodInstance)))
  21286. {
  21287. if (!methodDef->mIsNew)
  21288. {
  21289. BfAstNode* refNode = methodInstance->mMethodDef->GetRefNode();
  21290. if (refNode != NULL)
  21291. {
  21292. 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?
  21293. if (bfError != NULL)
  21294. bfError->mIsPersistent = true;
  21295. }
  21296. }
  21297. foundHiddenMethod = true;
  21298. break;
  21299. }
  21300. }
  21301. checkMethod = checkMethod->mNextWithSameName;
  21302. }
  21303. if (foundHiddenMethod)
  21304. break;
  21305. baseType = baseType->mBaseType;
  21306. }
  21307. if ((methodDef->mIsNew) && (!foundHiddenMethod) && (!mCurTypeInstance->IsSpecializedType()))
  21308. {
  21309. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  21310. auto tokenNode = (propertyDeclaration != NULL) ? propertyDeclaration->mNewSpecifier :
  21311. methodDeclaration->mNewSpecifier;
  21312. Fail("Method does not hide an inherited member. The 'new' keyword is not required", tokenNode, true);
  21313. }
  21314. }
  21315. }
  21316. if ((methodDef->mIsConcrete) && (!methodInstance->mIsForeignMethodDef) && (!mCurTypeInstance->IsInterface()))
  21317. {
  21318. Fail("Only interfaces methods can be declared as 'concrete'", methodDeclaration->mVirtualSpecifier);
  21319. }
  21320. if ((methodDef->mIsVirtual) && (methodDef->mIsStatic) && (!methodInstance->mIsInnerOverride))
  21321. {
  21322. if ((virtualToken != NULL) && (virtualToken->mToken == BfToken_Override) && (methodDef->mDeclaringType->mTypeCode == BfTypeCode_Extension))
  21323. Fail("No suitable method found to override", virtualToken, true);
  21324. else
  21325. Fail("Static members cannot be marked as override, virtual, or abstract", virtualToken, true);
  21326. }
  21327. else if (methodDef->mIsVirtual)
  21328. {
  21329. if ((methodDef->mProtection == BfProtection_Private) && (virtualToken != NULL))
  21330. Fail("Virtual or abstract members cannot be 'private'", virtualToken, true);
  21331. if ((methodDef->mProtection == BfProtection_Internal) && (virtualToken != NULL))
  21332. Fail("Virtual or abstract members cannot be 'internal'. Consider using the 'protected internal' access specifier.", virtualToken, true);
  21333. }
  21334. mCompiler->mStats.mMethodDeclarations++;
  21335. mCompiler->UpdateCompletion();
  21336. }
  21337. void BfModule::UniqueSlotVirtualMethod(BfMethodInstance* methodInstance)
  21338. {
  21339. BF_ASSERT(methodInstance->GetOwner() == mCurTypeInstance);
  21340. auto typeInstance = mCurTypeInstance;
  21341. auto methodDef = methodInstance->mMethodDef;
  21342. int virtualMethodMatchIdx = -1;
  21343. if (typeInstance->mHotTypeData != NULL)
  21344. {
  21345. if (typeInstance->mHotTypeData->mVTableOrigLength != -1)
  21346. {
  21347. BF_ASSERT(mCompiler->IsHotCompile());
  21348. // In the 'normal' case we'd assert that mIsOverride is false, but if we can't find the declaring method then we
  21349. // may slot this override anyway (?)
  21350. int vTableStart = 0;
  21351. auto implBaseType = typeInstance->GetImplBaseType();
  21352. if (implBaseType != NULL)
  21353. vTableStart = implBaseType->mVirtualMethodTableSize;
  21354. StringT<512> mangledName;
  21355. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  21356. for (int checkIdxOfs = 0; checkIdxOfs < (int)typeInstance->mHotTypeData->mVTableEntries.size(); checkIdxOfs++)
  21357. {
  21358. // O(1) checking when virtual methods haven't changed
  21359. int checkIdx = (typeInstance->mVirtualMethodTableSize - vTableStart + checkIdxOfs) % (int)typeInstance->mHotTypeData->mVTableEntries.size();
  21360. auto& entry = typeInstance->mHotTypeData->mVTableEntries[checkIdx];
  21361. if (mangledName == entry.mFuncName)
  21362. {
  21363. virtualMethodMatchIdx = vTableStart + checkIdx;
  21364. break;
  21365. }
  21366. }
  21367. if (virtualMethodMatchIdx != -1)
  21368. {
  21369. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  21370. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod = methodInstance;
  21371. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod = methodInstance;
  21372. }
  21373. typeInstance->mVirtualMethodTableSize = (int)typeInstance->mVirtualMethodTable.size();
  21374. }
  21375. }
  21376. if (virtualMethodMatchIdx == -1)
  21377. {
  21378. methodInstance->mVirtualTableIdx = typeInstance->mVirtualMethodTableSize++;
  21379. BfVirtualMethodEntry entry = { methodInstance, methodInstance };
  21380. typeInstance->mVirtualMethodTable.push_back(entry);
  21381. }
  21382. }
  21383. void BfModule::CompareDeclTypes(BfTypeDef* newDeclType, BfTypeDef* prevDeclType, bool& isBetter, bool& isWorse)
  21384. {
  21385. if ((!prevDeclType->IsExtension()) && (newDeclType->IsExtension()))
  21386. {
  21387. // When we provide an extension override in the same project a root type override
  21388. isBetter = true;
  21389. isWorse = false;
  21390. }
  21391. else
  21392. {
  21393. isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  21394. isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  21395. }
  21396. }
  21397. bool BfModule::SlotVirtualMethod(BfMethodInstance* methodInstance, BfAmbiguityContext* ambiguityContext)
  21398. {
  21399. BP_ZONE("BfModule::SlotVirtualMethod");
  21400. if (mCurTypeInstance->IsUnspecializedTypeVariation())
  21401. return false;
  21402. auto _AddVirtualDecl = [&](BfMethodInstance* declMethodInstance)
  21403. {
  21404. if (!mCompiler->mOptions.mAllowHotSwapping)
  21405. return;
  21406. if ((!methodInstance->mIsReified) || (!declMethodInstance->mIsReified))
  21407. return;
  21408. if (methodInstance->mHotMethod == NULL)
  21409. CheckHotMethod(methodInstance, "");
  21410. if (methodInstance->mHotMethod == NULL)
  21411. return;
  21412. //BF_ASSERT(declMethodInstance->mHotMethod != NULL);
  21413. if (declMethodInstance->mHotMethod == NULL)
  21414. CheckHotMethod(declMethodInstance, "");
  21415. auto virtualDecl = mCompiler->mHotData->GetVirtualDeclaration(declMethodInstance->mHotMethod);
  21416. virtualDecl->mRefCount++;
  21417. methodInstance->mHotMethod->mReferences.Add(virtualDecl);
  21418. };
  21419. auto typeInstance = mCurTypeInstance;
  21420. auto typeDef = typeInstance->mTypeDef;
  21421. auto methodDef = methodInstance->mMethodDef;
  21422. auto methodDeclaration = methodDef->GetMethodDeclaration();
  21423. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  21424. auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration();
  21425. if (methodInstance->mIsInnerOverride)
  21426. return false;
  21427. BfAstNode* declaringNode = methodDeclaration;
  21428. if (propertyMethodDeclaration != NULL)
  21429. declaringNode = propertyMethodDeclaration->mNameNode;
  21430. BfMethodInstance* methodOverriden = NULL;
  21431. bool usedMethod = false;
  21432. BfTokenNode* virtualToken = NULL;
  21433. if (propertyDeclaration != NULL)
  21434. virtualToken = propertyDeclaration->mVirtualSpecifier;
  21435. else if (methodDeclaration != NULL)
  21436. virtualToken = methodDeclaration->mVirtualSpecifier;
  21437. if ((methodDef->mIsVirtual) && (methodDef->mIsStatic))
  21438. {
  21439. //Fail: Static members cannot be marked as override, virtual, or abstract
  21440. }
  21441. else if (methodDef->mIsVirtual)
  21442. {
  21443. if (IsHotCompile())
  21444. mContext->EnsureHotMangledVirtualMethodName(methodInstance);
  21445. BfTypeInstance* checkBase = typeInstance;
  21446. // If we are in an extension, look in ourselves first
  21447. if (methodDef->mDeclaringType->mTypeDeclaration == typeInstance->mTypeDef->mTypeDeclaration)
  21448. checkBase = checkBase->mBaseType;
  21449. if (typeInstance->IsValueType())
  21450. {
  21451. if (typeInstance->mBaseType == NULL)
  21452. return false; // It's actually ValueType
  21453. // We allow structs to override object methods for when they get boxed, so just ignore 'override' keyword until it gets boxed
  21454. if (!methodDef->mIsOverride)
  21455. {
  21456. Fail("Structs cannot have virtual methods", virtualToken, true);
  21457. return false;
  21458. }
  21459. checkBase = mContext->mBfObjectType;
  21460. if (checkBase->mVirtualMethodTableSize == 0)
  21461. PopulateType(checkBase, BfPopulateType_Full);
  21462. if (checkBase->mDefineState < BfTypeDefineState_DefinedAndMethodsSlotted)
  21463. return false; // System circular ref, don't do struct checking on those
  21464. }
  21465. int virtualMethodMatchIdx = -1;
  21466. bool hadHidingError = false;
  21467. BfMethodInstance* bestOverrideMethodInstance = NULL;
  21468. BfMethodInstance* ambiguousOverrideMethodInstance = NULL;
  21469. int bestOverrideMethodIdx = -1;
  21470. int ambiguousOverrideMethodIdx = -1;
  21471. if (checkBase != NULL)
  21472. {
  21473. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  21474. auto lookupType = checkBase;
  21475. while (lookupType != NULL)
  21476. {
  21477. lookupType->mTypeDef->PopulateMemberSets();
  21478. BfMethodDef* nextMethodDef = NULL;
  21479. BfMemberSetEntry* entry;
  21480. if (lookupType->mTypeDef->mMethodSet.TryGetWith((StringImpl&)methodInstance->mMethodDef->mName, &entry))
  21481. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  21482. while (nextMethodDef != NULL)
  21483. {
  21484. auto checkMethodDef = nextMethodDef;
  21485. nextMethodDef = nextMethodDef->mNextWithSameName;
  21486. if ((!checkMethodDef->mIsVirtual) || (checkMethodDef->mIsOverride))
  21487. continue;
  21488. BfMethodInstance* baseMethodInstance = NULL;
  21489. int checkMethodIdx = -1;
  21490. BfMethodInstance* lookupMethodInstance = lookupType->mMethodInstanceGroups[checkMethodDef->mIdx].mDefault;
  21491. if ((lookupMethodInstance == NULL) || (lookupMethodInstance->mVirtualTableIdx == -1))
  21492. {
  21493. if (lookupType->IsUnspecializedTypeVariation())
  21494. {
  21495. if (!lookupMethodInstance->mMethodDef->mIsOverride)
  21496. {
  21497. baseMethodInstance = lookupMethodInstance;
  21498. checkMethodIdx = -2;
  21499. }
  21500. }
  21501. if (baseMethodInstance == NULL)
  21502. continue;
  21503. }
  21504. if (baseMethodInstance == NULL)
  21505. {
  21506. checkMethodIdx = lookupMethodInstance->mVirtualTableIdx;
  21507. if (checkMethodIdx >= baseVirtualMethodTable.mSize)
  21508. FatalError("SlotVirtualMethod OOB in baseVirtualMethodTable[checkMethodIdx]");
  21509. auto& baseMethodRef = baseVirtualMethodTable[checkMethodIdx];
  21510. if (baseMethodRef.mDeclaringMethod.mMethodNum == -1)
  21511. {
  21512. BF_ASSERT(mCompiler->mOptions.mHasVDataExtender);
  21513. continue;
  21514. }
  21515. baseMethodInstance = baseVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  21516. if (baseMethodInstance == NULL)
  21517. {
  21518. AssertErrorState();
  21519. continue;
  21520. }
  21521. }
  21522. if ((baseMethodInstance != NULL) && (CompareMethodSignatures(baseMethodInstance, methodInstance)))
  21523. {
  21524. if (methodDef->mIsOverride)
  21525. {
  21526. BfMethodInstance* checkMethodInstance;
  21527. if (checkMethodIdx == -2)
  21528. checkMethodInstance = baseMethodInstance;
  21529. else if (typeInstance->IsValueType())
  21530. checkMethodInstance = checkBase->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  21531. else
  21532. checkMethodInstance = typeInstance->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  21533. auto newDeclType = checkMethodInstance->mMethodDef->mDeclaringType;
  21534. if (!typeInstance->IsTypeMemberAccessible(newDeclType, methodDef->mDeclaringType->mProject))
  21535. continue;
  21536. if (bestOverrideMethodInstance != NULL)
  21537. {
  21538. auto prevDeclType = bestOverrideMethodInstance->mMethodDef->mDeclaringType;
  21539. bool isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  21540. bool isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  21541. if (isBetter == isWorse)
  21542. {
  21543. ambiguousOverrideMethodInstance = bestOverrideMethodInstance;
  21544. }
  21545. else
  21546. {
  21547. if (isWorse)
  21548. continue;
  21549. ambiguousOverrideMethodInstance = NULL;
  21550. }
  21551. }
  21552. bestOverrideMethodInstance = checkMethodInstance;
  21553. bestOverrideMethodIdx = checkMethodIdx;
  21554. }
  21555. else
  21556. {
  21557. if ((baseMethodInstance->GetOwner() != methodInstance->GetOwner()) && (!methodDef->mIsNew))
  21558. {
  21559. if (!hadHidingError)
  21560. Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use either 'override' or 'new'.", TypeToString(checkBase).c_str()), declaringNode);
  21561. hadHidingError = true;
  21562. }
  21563. }
  21564. }
  21565. }
  21566. lookupType = lookupType->mBaseType;
  21567. }
  21568. }
  21569. //TODO:
  21570. if ((checkBase != NULL)
  21571. && (false)
  21572. )
  21573. {
  21574. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  21575. for (int checkMethodIdx = (int) baseVirtualMethodTable.size() - 1; checkMethodIdx >= 0; checkMethodIdx--)
  21576. {
  21577. auto& baseMethodRef = baseVirtualMethodTable[checkMethodIdx];
  21578. if (baseMethodRef.mDeclaringMethod.mMethodNum == -1)
  21579. {
  21580. BF_ASSERT(mCompiler->mOptions.mHasVDataExtender);
  21581. continue;
  21582. }
  21583. BfMethodInstance* baseMethodInstance = baseVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  21584. if (baseMethodInstance == NULL)
  21585. {
  21586. AssertErrorState();
  21587. continue;
  21588. }
  21589. if ((baseMethodInstance != NULL) && (CompareMethodSignatures(baseMethodInstance, methodInstance)))
  21590. {
  21591. if (methodDef->mIsOverride)
  21592. {
  21593. BfMethodInstance* checkMethodInstance;
  21594. if (typeInstance->IsValueType())
  21595. checkMethodInstance = checkBase->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  21596. else
  21597. checkMethodInstance = typeInstance->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  21598. auto newDeclType = checkMethodInstance->mMethodDef->mDeclaringType;
  21599. if (!typeInstance->IsTypeMemberAccessible(newDeclType, methodDef->mDeclaringType->mProject))
  21600. continue;
  21601. if (bestOverrideMethodInstance != NULL)
  21602. {
  21603. auto prevDeclType = bestOverrideMethodInstance->mMethodDef->mDeclaringType;
  21604. bool isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  21605. bool isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  21606. if (isBetter == isWorse)
  21607. {
  21608. ambiguousOverrideMethodInstance = bestOverrideMethodInstance;
  21609. }
  21610. else
  21611. {
  21612. if (isWorse)
  21613. continue;
  21614. ambiguousOverrideMethodInstance = NULL;
  21615. }
  21616. }
  21617. bestOverrideMethodInstance = checkMethodInstance;
  21618. bestOverrideMethodIdx = checkMethodIdx;
  21619. }
  21620. else
  21621. {
  21622. if ((baseMethodInstance->GetOwner() != methodInstance->GetOwner()) && (!methodDef->mIsNew))
  21623. {
  21624. if (!hadHidingError)
  21625. Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use either 'override' or 'new'.", TypeToString(checkBase).c_str()), declaringNode);
  21626. hadHidingError = true;
  21627. }
  21628. }
  21629. }
  21630. }
  21631. }
  21632. if (bestOverrideMethodInstance != NULL)
  21633. {
  21634. if (ambiguousOverrideMethodInstance != NULL)
  21635. {
  21636. bool allow = false;
  21637. // 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.
  21638. // When when specialize, the specialized type will determine wither it has illegally pulled in both declarations or not
  21639. bool canSeeEachOther = false;
  21640. //
  21641. {
  21642. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, ambiguousOverrideMethodInstance);
  21643. if (bestOverrideMethodInstance->GetOwner()->IsTypeMemberIncluded(bestOverrideMethodInstance->mMethodDef->mDeclaringType, ambiguousOverrideMethodInstance->mMethodDef->mDeclaringType, this))
  21644. canSeeEachOther = true;
  21645. }
  21646. //
  21647. {
  21648. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, bestOverrideMethodInstance);
  21649. if (ambiguousOverrideMethodInstance->GetOwner()->IsTypeMemberIncluded(ambiguousOverrideMethodInstance->mMethodDef->mDeclaringType, bestOverrideMethodInstance->mMethodDef->mDeclaringType, this))
  21650. canSeeEachOther = true;
  21651. }
  21652. if (!canSeeEachOther)
  21653. {
  21654. BF_ASSERT(bestOverrideMethodInstance->GetOwner()->IsUnspecializedType() && ambiguousOverrideMethodInstance->GetOwner()->IsUnspecializedType());
  21655. }
  21656. else
  21657. {
  21658. auto error = Fail(StrFormat("Method '%s' is an ambiguous override", MethodToString(methodInstance).c_str()), methodDef->GetRefNode());
  21659. if (error != NULL)
  21660. {
  21661. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", MethodToString(bestOverrideMethodInstance).c_str()), bestOverrideMethodInstance->mMethodDef->GetRefNode());
  21662. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", MethodToString(ambiguousOverrideMethodInstance).c_str()), ambiguousOverrideMethodInstance->mMethodDef->GetRefNode());
  21663. }
  21664. }
  21665. }
  21666. }
  21667. if (bestOverrideMethodIdx == -2)
  21668. {
  21669. // Comes from an unspecialized variation
  21670. virtualMethodMatchIdx = bestOverrideMethodIdx;
  21671. }
  21672. else if ((bestOverrideMethodInstance != NULL) && (bestOverrideMethodIdx != -1))
  21673. {
  21674. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  21675. BfMethodInstance* baseVirtualMethodInstance = baseVirtualMethodTable[bestOverrideMethodIdx].mDeclaringMethod;
  21676. if ((baseVirtualMethodInstance != methodInstance) && (methodDef->mIsOverride))
  21677. {
  21678. if (baseVirtualMethodInstance->mReturnType != methodInstance->mReturnType)
  21679. {
  21680. BfTypeReference* returnTypeRef;
  21681. if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  21682. {
  21683. returnTypeRef = propertyDeclaration->mTypeRef;
  21684. Fail("Property differs from overridden property by type", returnTypeRef, true);
  21685. }
  21686. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  21687. {
  21688. returnTypeRef = methodDeclaration->mReturnType;
  21689. Fail("Method differs from overridden method by return value", returnTypeRef, true);
  21690. }
  21691. else
  21692. {
  21693. Fail(StrFormat("Internal error with method '%s'", MethodToString(methodInstance).c_str()));
  21694. }
  21695. return usedMethod;
  21696. }
  21697. }
  21698. if (methodDef->mIsOverride)
  21699. {
  21700. // We can have multiple matches when a virtual method is used to implement interface methods
  21701. // It doesn't matter what we set mVirtualTableIdx, as all base classes will override all matching
  21702. // vtable entries for this method signature
  21703. virtualMethodMatchIdx = bestOverrideMethodIdx;
  21704. if (!typeInstance->IsValueType())
  21705. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  21706. if (typeInstance->IsValueType())
  21707. {
  21708. methodOverriden = checkBase->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod;
  21709. }
  21710. else
  21711. {
  21712. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  21713. bool preferRootDefinition = (methodDef->mName == BF_METHODNAME_MARKMEMBERS) || (methodDef->mMethodType == BfMethodType_Dtor);
  21714. BfMethodInstance* setMethodInstance = methodInstance;
  21715. bool doOverride = false;
  21716. auto& overridenRef = typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod;
  21717. if (overridenRef.mKind != BfMethodRefKind_AmbiguousRef)
  21718. {
  21719. methodOverriden = overridenRef;
  21720. doOverride = true;
  21721. if (methodOverriden->GetOwner() == methodInstance->GetOwner())
  21722. {
  21723. bool isBetter = false;
  21724. bool isWorse = false;
  21725. CompareDeclTypes(methodInstance->mMethodDef->mDeclaringType, methodOverriden->mMethodDef->mDeclaringType, isBetter, isWorse);
  21726. if (isBetter == isWorse)
  21727. {
  21728. // We have to resolve later per-project
  21729. if ((ambiguityContext != NULL) && (ambiguityContext->mIsProjectSpecific))
  21730. {
  21731. auto declMethodInstance = checkBase->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod;
  21732. ambiguityContext->Add(virtualMethodMatchIdx, NULL, -1, methodOverriden, methodInstance);
  21733. }
  21734. if ((ambiguityContext == NULL) || (!ambiguityContext->mIsProjectSpecific))
  21735. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod.mKind = BfMethodRefKind_AmbiguousRef;
  21736. doOverride = false;
  21737. }
  21738. else
  21739. {
  21740. if ((isBetter) && (ambiguityContext != NULL))
  21741. {
  21742. ambiguityContext->Remove(virtualMethodMatchIdx);
  21743. }
  21744. if ((isBetter) && (methodInstance->GetOwner() == methodOverriden->GetOwner()))
  21745. {
  21746. if (preferRootDefinition)
  21747. {
  21748. // Leave the master GCMarkMember
  21749. isBetter = false;
  21750. isWorse = true;
  21751. }
  21752. }
  21753. doOverride = isBetter;
  21754. }
  21755. }
  21756. }
  21757. else if ((preferRootDefinition) && (!methodDef->mDeclaringType->IsExtension()))
  21758. {
  21759. methodOverriden = overridenRef;
  21760. doOverride = true;
  21761. }
  21762. if (doOverride)
  21763. {
  21764. auto declMethodInstance = (BfMethodInstance*)typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod;
  21765. _AddVirtualDecl(declMethodInstance);
  21766. setMethodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  21767. auto& implMethodRef = typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod;
  21768. if ((!mCompiler->mIsResolveOnly) && (implMethodRef.mMethodNum >= 0) &&
  21769. (implMethodRef.mTypeInstance == typeInstance) && (methodInstance->GetOwner() == typeInstance))
  21770. {
  21771. auto prevImplMethodInstance = (BfMethodInstance*)implMethodRef;
  21772. if (prevImplMethodInstance->mMethodDef->mDeclaringType->mProject != methodInstance->mMethodDef->mDeclaringType->mProject)
  21773. {
  21774. // We may need to have to previous method reified when we must re-slot in another project during vdata creation
  21775. BfReifyMethodDependency dep;
  21776. dep.mDepMethod = typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod;
  21777. dep.mMethodIdx = implMethodRef.mMethodNum;
  21778. typeInstance->mReifyMethodDependencies.Add(dep);
  21779. }
  21780. if (!methodInstance->mMangleWithIdx)
  21781. {
  21782. // Keep mangled names from conflicting
  21783. methodInstance->mMangleWithIdx = true;
  21784. if ((methodInstance->mIRFunction) && (methodInstance->mDeclModule->mIsModuleMutable))
  21785. {
  21786. StringT<4096> mangledName;
  21787. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  21788. methodInstance->mDeclModule->mBfIRBuilder->SetFunctionName(methodInstance->mIRFunction, mangledName);
  21789. }
  21790. }
  21791. }
  21792. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod = setMethodInstance;
  21793. }
  21794. }
  21795. if (methodOverriden != NULL)
  21796. {
  21797. CheckOverridenMethod(methodInstance, methodOverriden);
  21798. }
  21799. }
  21800. }
  21801. if ((virtualMethodMatchIdx == -1) && ((ambiguityContext == NULL) || (!ambiguityContext->mIsReslotting)))
  21802. {
  21803. if (methodDef->mIsOverride)
  21804. {
  21805. BfTokenNode* overrideToken = NULL;
  21806. if (auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration())
  21807. overrideToken = propertyMethodDeclaration->mPropertyDeclaration->mVirtualSpecifier;
  21808. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  21809. overrideToken = methodDeclaration->mVirtualSpecifier;
  21810. if (overrideToken != NULL)
  21811. {
  21812. if ((propertyDeclaration != NULL) && (propertyDeclaration->mNameNode != NULL) &&
  21813. ((methodDef->mMethodType == BfMethodType_PropertyGetter) || (methodDef->mMethodType == BfMethodType_PropertySetter)))
  21814. Fail(StrFormat("No suitable method found to override for '%s.%s'",
  21815. propertyDeclaration->mNameNode->ToString().c_str(), (methodDef->mMethodType == BfMethodType_PropertyGetter) ? "get" : "set"), overrideToken, true);
  21816. else
  21817. Fail("No suitable method found to override", overrideToken, true);
  21818. }
  21819. return usedMethod;
  21820. }
  21821. UniqueSlotVirtualMethod(methodInstance);
  21822. }
  21823. else
  21824. usedMethod = true;
  21825. if (typeInstance->IsValueType())
  21826. return usedMethod;
  21827. }
  21828. bool foundInterface = false;
  21829. bool hadAnyMatch = false;
  21830. // See if this method matches interfaces
  21831. for (auto& ifaceTypeInst : typeInstance->mInterfaces)
  21832. {
  21833. auto ifaceInst = ifaceTypeInst.mInterfaceType;
  21834. if (ifaceInst->IsIncomplete())
  21835. PopulateType(ifaceInst, BfPopulateType_DataAndMethods);
  21836. int startIdx = ifaceTypeInst.mStartInterfaceTableIdx;
  21837. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  21838. // See "bidirectional" rules mentioned in DoTypeInstanceMethodProcessing
  21839. if ((!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, ifaceTypeInst.mDeclaringType)) &&
  21840. (!typeInstance->IsTypeMemberAccessible(ifaceTypeInst.mDeclaringType, methodDef->mDeclaringType)))
  21841. continue;
  21842. if (!typeInstance->IsTypeMemberIncluded(methodDef->mDeclaringType, ifaceTypeInst.mDeclaringType, this))
  21843. continue;
  21844. bool hadMatch = false;
  21845. BfMethodInstance* hadNameMatch = NULL;
  21846. BfType* expectedReturnType = NULL;
  21847. bool showedError = false;
  21848. // We go through our VTable looking for NULL entries within the interface sections
  21849. // The only instance of finding a "better" method is when we have explicitly interface-dotted method
  21850. // because a normal method declared in this type could have matched earlier
  21851. //for (int iMethodIdx = 0; iMethodIdx < iMethodCount; iMethodIdx++)
  21852. ifaceInst->mTypeDef->PopulateMemberSets();
  21853. BfMethodDef* checkMethodDef = NULL;
  21854. BfMemberSetEntry* entry;
  21855. if (ifaceInst->mTypeDef->mMethodSet.TryGetWith((StringImpl&)methodInstance->mMethodDef->mName, &entry))
  21856. checkMethodDef = (BfMethodDef*)entry->mMemberDef;
  21857. while (checkMethodDef != NULL)
  21858. {
  21859. int iMethodIdx = checkMethodDef->mIdx;
  21860. int iTableIdx = iMethodIdx + startIdx;
  21861. BfTypeInterfaceMethodEntry* interfaceMethodEntry = &typeInstance->mInterfaceMethodTable[iTableIdx];
  21862. auto iMethodPtr = &interfaceMethodEntry->mMethodRef;
  21863. bool storeIFaceMethod = false;
  21864. if ((mCompiler->mPassInstance->HasFailed()) && (iMethodIdx >= (int)ifaceInst->mMethodInstanceGroups.size()))
  21865. {
  21866. checkMethodDef = checkMethodDef->mNextWithSameName;
  21867. continue;
  21868. }
  21869. auto& iMethodGroup = ifaceInst->mMethodInstanceGroups[iMethodIdx];
  21870. auto iMethodInst = iMethodGroup.mDefault;
  21871. if (iMethodInst == NULL)
  21872. {
  21873. if ((!ifaceInst->IsGenericTypeInstance()) || (!ifaceInst->mTypeDef->mIsCombinedPartial))
  21874. AssertErrorState();
  21875. checkMethodDef = checkMethodDef->mNextWithSameName;
  21876. continue;
  21877. }
  21878. if (iMethodInst->mMethodDef->mName == methodInstance->mMethodDef->mName)
  21879. hadNameMatch = iMethodInst;
  21880. bool doesMethodSignatureMatch = CompareMethodSignatures(iMethodInst, methodInstance);
  21881. if ((!doesMethodSignatureMatch) && (interfaceMethodEntry->mMethodRef.IsNull()))
  21882. {
  21883. doesMethodSignatureMatch = IsCompatibleInterfaceMethod(iMethodInst, methodInstance);
  21884. }
  21885. if ((doesMethodSignatureMatch) && (methodInstance->GetOwner()->IsValueType()))
  21886. {
  21887. if ((!iMethodInst->mMethodDef->mIsMutating) && (methodInstance->mMethodDef->mIsMutating))
  21888. {
  21889. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface == ifaceInst))
  21890. {
  21891. auto error = mCompiler->mPassInstance->Fail(StrFormat("Implementation method '%s' cannot specify 'mut' because the interface method does not allow it",
  21892. MethodToString(methodInstance).c_str()), methodInstance->mMethodDef->GetMutNode());
  21893. if (error != NULL)
  21894. mCompiler->mPassInstance->MoreInfo(StrFormat("Declare the interface method as 'mut' to allow matching 'mut' implementations"), iMethodInst->mMethodDef->mMethodDeclaration);
  21895. showedError = true;
  21896. }
  21897. }
  21898. }
  21899. if (doesMethodSignatureMatch)
  21900. {
  21901. usedMethod = true;
  21902. hadMatch = true;
  21903. hadAnyMatch = true;
  21904. storeIFaceMethod = true;
  21905. if ((iMethodPtr->mKind != BfMethodRefKind_AmbiguousRef) && (iMethodPtr->mTypeInstance != NULL))
  21906. {
  21907. auto prevMethod = (BfMethodInstance*)*iMethodPtr;
  21908. if ((mCompiler->mIsResolveOnly) && (prevMethod == methodInstance) && (!mIsComptimeModule))
  21909. {
  21910. // When autocompletion regenerates a single method body but not the whole type then
  21911. // we will see ourselves in the vtable already
  21912. return usedMethod;
  21913. }
  21914. bool isBetter = false;
  21915. bool isWorse = false;
  21916. isBetter = (methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL);
  21917. isWorse = (prevMethod->mMethodInfoEx != NULL) && (prevMethod->mMethodInfoEx->mExplicitInterface != NULL);
  21918. if (isBetter == isWorse)
  21919. CompareDeclTypes(methodInstance->mMethodDef->mDeclaringType, prevMethod->mMethodDef->mDeclaringType, isBetter, isWorse);
  21920. if (isBetter == isWorse)
  21921. {
  21922. if (ambiguityContext != NULL)
  21923. {
  21924. ambiguityContext->Add(~iTableIdx, &ifaceTypeInst, iMethodIdx, prevMethod, methodInstance);
  21925. }
  21926. iMethodPtr->mKind = BfMethodRefKind_AmbiguousRef;
  21927. storeIFaceMethod = true;
  21928. }
  21929. else
  21930. {
  21931. if ((isBetter) && (ambiguityContext != NULL))
  21932. ambiguityContext->Remove(~iTableIdx);
  21933. storeIFaceMethod = isBetter;
  21934. }
  21935. }
  21936. }
  21937. if (storeIFaceMethod)
  21938. {
  21939. if (methodInstance->GetNumGenericParams() != 0)
  21940. _AddVirtualDecl(iMethodInst);
  21941. *iMethodPtr = methodInstance;
  21942. }
  21943. checkMethodDef = checkMethodDef->mNextWithSameName;
  21944. }
  21945. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface == ifaceInst) && (!hadMatch) && (!showedError))
  21946. {
  21947. if (expectedReturnType != NULL)
  21948. Fail(StrFormat("Wrong return type, expected '%s'", TypeToString(expectedReturnType).c_str()), declaringNode, true);
  21949. else if (hadNameMatch != NULL)
  21950. {
  21951. auto error = Fail("Method parameters don't match interface method", declaringNode, true);
  21952. if (error != NULL)
  21953. mCompiler->mPassInstance->MoreInfo("See interface method declaration", hadNameMatch->mMethodDef->GetRefNode());
  21954. }
  21955. else
  21956. {
  21957. auto propertyDecl = methodDef->GetPropertyDeclaration();
  21958. if (propertyDecl != NULL)
  21959. {
  21960. auto propertyMethodDecl = methodDef->GetPropertyMethodDeclaration();
  21961. String name;
  21962. if (auto indexerDeclaration = BfNodeDynCast<BfIndexerDeclaration>(propertyDecl))
  21963. name = "this[]";
  21964. else if (propertyDecl->mNameNode != NULL)
  21965. propertyDecl->mNameNode->ToString(name);
  21966. Fail(StrFormat("Property '%s' %s accessor not defined in interface '%s'", name.c_str(),
  21967. (methodDef->mMethodType == BfMethodType_PropertyGetter) ? "get" : "set", TypeToString(ifaceInst).c_str()), methodDef->GetRefNode(), true);
  21968. }
  21969. else
  21970. Fail(StrFormat("Method '%s' not found in interface '%s'", methodDef->mName.c_str(), TypeToString(ifaceInst).c_str()), methodDef->GetRefNode(), true);
  21971. }
  21972. }
  21973. }
  21974. // Any overriden virtual methods that were used in interfaces also need to be replaced
  21975. if (methodOverriden != NULL)
  21976. {
  21977. for (auto& methodEntry : typeInstance->mInterfaceMethodTable)
  21978. {
  21979. if (methodEntry.mMethodRef == methodOverriden)
  21980. methodEntry.mMethodRef = methodInstance;
  21981. }
  21982. }
  21983. return usedMethod;
  21984. }
  21985. void BfModule::CheckOverridenMethod(BfMethodInstance* methodInstance, BfMethodInstance* methodOverriden)
  21986. {
  21987. auto methodDef = methodInstance->mMethodDef;
  21988. auto prevProtection = methodOverriden->mMethodDef->mProtection;
  21989. if ((methodDef->mProtection != prevProtection) && (methodDef->mMethodType != BfMethodType_Dtor))
  21990. {
  21991. const char* protectionNames[] = { "hidden", "private", "internal", "protected", "protected internal", "public" };
  21992. BF_STATIC_ASSERT(BF_ARRAY_COUNT(protectionNames) == BfProtection_COUNT);
  21993. BfAstNode* protectionRefNode = NULL;
  21994. if (auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration())
  21995. {
  21996. protectionRefNode = propertyMethodDeclaration->mProtectionSpecifier;
  21997. if (protectionRefNode == NULL)
  21998. protectionRefNode = propertyMethodDeclaration->mPropertyDeclaration->mProtectionSpecifier;
  21999. if (protectionRefNode == NULL)
  22000. protectionRefNode = propertyMethodDeclaration->mPropertyDeclaration->mNameNode;
  22001. }
  22002. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  22003. {
  22004. protectionRefNode = methodDeclaration->mProtectionSpecifier;
  22005. if (protectionRefNode == NULL)
  22006. protectionRefNode = methodDeclaration->mNameNode;
  22007. }
  22008. if (protectionRefNode != NULL)
  22009. Fail(StrFormat("Cannot change access modifiers when overriding '%s' inherited member", protectionNames[(int)prevProtection]), protectionRefNode, true);
  22010. }
  22011. }
  22012. bool BfModule::SlotInterfaceMethod(BfMethodInstance* methodInstance)
  22013. {
  22014. auto typeInstance = mCurTypeInstance;
  22015. auto methodDef = methodInstance->mMethodDef;
  22016. if (methodDef->mMethodType == BfMethodType_Ctor)
  22017. return true;
  22018. bool foundOverride = false;
  22019. if ((methodDef->mBody == NULL) && (methodDef->mProtection == BfProtection_Private))
  22020. {
  22021. auto methodDeclaration = methodDef->GetMethodDeclaration();
  22022. BfAstNode* refNode = NULL;
  22023. if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  22024. refNode = propertyDeclaration->mProtectionSpecifier;
  22025. else if (methodDeclaration != NULL)
  22026. refNode = methodDeclaration->mProtectionSpecifier;
  22027. Fail("Private interface methods must provide a body", refNode);
  22028. }
  22029. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL) && (!methodDef->mIsOverride))
  22030. {
  22031. Fail("Explicit interfaces can only be specified for overrides in interface declarations", methodDef->GetMethodDeclaration()->mExplicitInterface);
  22032. }
  22033. BfAstNode* declaringNode = methodDef->GetRefNode();
  22034. for (auto& ifaceTypeInst : typeInstance->mInterfaces)
  22035. {
  22036. auto ifaceInst = ifaceTypeInst.mInterfaceType;
  22037. int startIdx = ifaceTypeInst.mStartInterfaceTableIdx;
  22038. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  22039. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != ifaceInst))
  22040. continue;
  22041. ifaceInst->mTypeDef->PopulateMemberSets();
  22042. BfMethodDef* nextMethod = NULL;
  22043. BfMemberSetEntry* entry = NULL;
  22044. if (ifaceInst->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  22045. nextMethod = (BfMethodDef*)entry->mMemberDef;
  22046. while (nextMethod != NULL)
  22047. {
  22048. auto checkMethod = nextMethod;
  22049. nextMethod = nextMethod->mNextWithSameName;
  22050. auto ifaceMethod = ifaceInst->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  22051. if (ifaceMethod == NULL)
  22052. continue;
  22053. if (CompareMethodSignatures(ifaceMethod, methodInstance))
  22054. {
  22055. if (methodDef->mIsOverride)
  22056. {
  22057. if (ifaceMethod->mMethodDef->mProtection == BfProtection_Private)
  22058. {
  22059. auto error = Fail(StrFormat("Interface method '%s' cannot override private interface method '%s'", MethodToString(methodInstance).c_str(), MethodToString(ifaceMethod).c_str()), declaringNode);
  22060. if (error != NULL)
  22061. {
  22062. mCompiler->mPassInstance->MoreInfo("See base interface method", ifaceMethod->mMethodDef->GetRefNode());
  22063. }
  22064. }
  22065. foundOverride = true;
  22066. }
  22067. else if (!methodDef->mIsNew)
  22068. {
  22069. Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use the 'new' keyword if hiding was intentional.", TypeToString(ifaceInst).c_str()), declaringNode);
  22070. }
  22071. }
  22072. }
  22073. }
  22074. if ((methodDef->mIsOverride) && (!foundOverride))
  22075. {
  22076. // This allows us to declare a method in the base definition or in an extension and then provide
  22077. // an implementation in a more-specific extension
  22078. typeInstance->mTypeDef->PopulateMemberSets();
  22079. BfMethodDef* nextMethod = NULL;
  22080. BfMemberSetEntry* entry = NULL;
  22081. if (typeInstance->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  22082. nextMethod = (BfMethodDef*)entry->mMemberDef;
  22083. while (nextMethod != NULL)
  22084. {
  22085. auto checkMethod = nextMethod;
  22086. nextMethod = nextMethod->mNextWithSameName;
  22087. auto ifaceMethod = typeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  22088. if (ifaceMethod == NULL)
  22089. continue;
  22090. if (ifaceMethod->mMethodDef->mDeclaringType == methodInstance->mMethodDef->mDeclaringType)
  22091. continue;
  22092. if (CompareMethodSignatures(ifaceMethod, methodInstance))
  22093. {
  22094. foundOverride = true;
  22095. }
  22096. }
  22097. // for (int methodIdx = 0; methodIdx < typeInstance->mMethodInstanceGroups.size(); methodIdx++)
  22098. // {
  22099. // auto ifaceMethod = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  22100. // if (ifaceMethod == NULL)
  22101. // continue;
  22102. // if (ifaceMethod->mMethodDef->mDeclaringType == methodInstance->mMethodDef->mDeclaringType)
  22103. // continue;
  22104. //
  22105. // if (CompareMethodSignatures(ifaceMethod, methodInstance))
  22106. // {
  22107. // foundOverride = true;
  22108. // }
  22109. // }
  22110. }
  22111. if (methodDef->mIsOverride)
  22112. {
  22113. if (!foundOverride)
  22114. {
  22115. BfTokenNode* overrideToken = NULL;
  22116. if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  22117. overrideToken = propertyDeclaration->mVirtualSpecifier;
  22118. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  22119. overrideToken = methodDeclaration->mVirtualSpecifier;
  22120. if (overrideToken != NULL)
  22121. {
  22122. Fail("No suitable method found to override", overrideToken, true);
  22123. }
  22124. else
  22125. {
  22126. // Possible cause - DTOR with params
  22127. AssertErrorState();
  22128. }
  22129. }
  22130. return true;
  22131. }
  22132. // Generic methods can't be called virtually
  22133. if (methodInstance->GetNumGenericParams() != 0)
  22134. return true;
  22135. // Only public methods can be called virtually
  22136. if (methodDef->mProtection != BfProtection_Public)
  22137. return true;
  22138. UniqueSlotVirtualMethod(methodInstance);
  22139. return true;
  22140. }
  22141. void BfModule::SetMethodDependency(BfMethodInstance* methodInstance)
  22142. {
  22143. if (methodInstance->mMethodInfoEx == NULL)
  22144. return;
  22145. int wantMinDepth = -1;
  22146. if (mCurTypeInstance != NULL)
  22147. wantMinDepth = mCurTypeInstance->mDependencyMap.mMinDependDepth + 1;
  22148. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mMinDependDepth != -1))
  22149. {
  22150. int wantTypeMinDepth = mCurMethodInstance->mMethodInfoEx->mMinDependDepth + 1;
  22151. if ((wantMinDepth == -1) || (wantTypeMinDepth < wantMinDepth))
  22152. wantMinDepth = wantTypeMinDepth;
  22153. }
  22154. if ((methodInstance->mMethodInfoEx->mMinDependDepth == -1) || (wantMinDepth < methodInstance->mMethodInfoEx->mMinDependDepth))
  22155. methodInstance->mMethodInfoEx->mMinDependDepth = wantMinDepth;
  22156. }
  22157. void BfModule::DbgFinish()
  22158. {
  22159. if ((mBfIRBuilder == NULL) || (mExtensionCount != 0))
  22160. return;
  22161. if (mAwaitingInitFinish)
  22162. FinishInit();
  22163. if (mHasForceLinkMarker)
  22164. return;
  22165. String markerName;
  22166. BfIRValue linkMarker;
  22167. if (mBfIRBuilder->DbgHasInfo())
  22168. {
  22169. bool needForceLinking = false;
  22170. for (auto& ownedType : mOwnedTypeInstances)
  22171. {
  22172. bool hasConfirmedReference = false;
  22173. for (auto& methodInstGroup : ownedType->mMethodInstanceGroups)
  22174. {
  22175. if ((methodInstGroup.IsImplemented()) && (methodInstGroup.mDefault != NULL) &&
  22176. (!methodInstGroup.mDefault->mMethodDef->mIsStatic) && (methodInstGroup.mDefault->mIsReified) && (!methodInstGroup.mDefault->mAlwaysInline) &&
  22177. ((methodInstGroup.mOnDemandKind == BfMethodOnDemandKind_AlwaysInclude) || (methodInstGroup.mOnDemandKind == BfMethodOnDemandKind_Referenced)) &&
  22178. (methodInstGroup.mHasEmittedReference))
  22179. {
  22180. hasConfirmedReference = true;
  22181. }
  22182. }
  22183. if ((!hasConfirmedReference) || (ownedType->IsBoxed()))
  22184. needForceLinking = true;
  22185. }
  22186. if ((needForceLinking) && (mProject->mCodeGenOptions.mAsmKind == BfAsmKind_None))
  22187. {
  22188. BfMethodState methodState;
  22189. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  22190. methodState.mTempKind = BfMethodState::TempKind_Static;
  22191. mHasForceLinkMarker = true;
  22192. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  22193. SizedArray<BfIRType, 0> paramTypes;
  22194. BfIRFunctionType funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  22195. String linkName = "FORCELINKMOD_" + mModuleName;
  22196. BfIRFunction func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, linkName);
  22197. mBfIRBuilder->SetActiveFunction(func);
  22198. auto entryBlock = mBfIRBuilder->CreateBlock("main", true);
  22199. mBfIRBuilder->SetInsertPoint(entryBlock);
  22200. auto firstType = mOwnedTypeInstances[0];
  22201. UpdateSrcPos(mContext->mBfObjectType->mTypeDef->GetRefNode());
  22202. SizedArray<BfIRMDNode, 1> diParamTypes;
  22203. diParamTypes.Add(mBfIRBuilder->DbgGetType(GetPrimitiveType(BfTypeCode_None)));
  22204. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParamTypes);
  22205. auto diScope = mBfIRBuilder->DbgCreateFunction(mDICompileUnit, "FORCELINKMOD", linkName, mCurFilePosition.mFileInstance->mDIFile,
  22206. mCurFilePosition.mCurLine + 1, diFuncType, false, true, mCurFilePosition.mCurLine + 1, 0, false, func);
  22207. methodState.mCurScope->mDIScope = diScope;
  22208. UpdateSrcPos(mContext->mBfObjectType->mTypeDef->GetRefNode(), BfSrcPosFlag_Force);
  22209. SizedArray<BfIRValue, 8> args;
  22210. BfExprEvaluator exprEvaluator(this);
  22211. for (auto& ownedType : mOwnedTypeInstances)
  22212. {
  22213. auto alloca = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int8)));
  22214. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(diScope, "variable", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(ownedType));
  22215. mBfIRBuilder->DbgInsertDeclare(alloca, diVariable);
  22216. }
  22217. mBfIRBuilder->CreateRetVoid();
  22218. mBfIRBuilder->SetActiveFunction(BfIRFunction());
  22219. }
  22220. }
  22221. }
  22222. bool BfModule::Finish()
  22223. {
  22224. BP_ZONE("BfModule::Finish");
  22225. BfLogSysM("BfModule finish: %p\n", this);
  22226. if (mHadBuildError)
  22227. {
  22228. // Don't AssertErrorState here, this current pass may not have failed but
  22229. // the module was still queued in mFinishedModuleWorkList
  22230. ClearModule();
  22231. return true;
  22232. }
  22233. if (mUsedSlotCount != -1)
  22234. {
  22235. BF_ASSERT(mCompiler->mMaxInterfaceSlots != -1);
  22236. mUsedSlotCount = mCompiler->mMaxInterfaceSlots;
  22237. }
  22238. if ((!mGeneratesCode) && (!mAddedToCount))
  22239. return true;
  22240. BF_ASSERT(mAddedToCount);
  22241. mAddedToCount = false;
  22242. mAwaitingFinish = false;
  22243. mCompiler->mStats.mModulesFinished++;
  22244. if (HasCompiledOutput())
  22245. {
  22246. BF_ASSERT(!mBfIRBuilder->mIgnoreWrites);
  22247. DbgFinish();
  22248. if (mAwaitingInitFinish)
  22249. FinishInit();
  22250. for (auto ownedTypeInst : mOwnedTypeInstances)
  22251. {
  22252. // Generate dbg info and add global variables if we haven't already
  22253. mBfIRBuilder->PopulateType(ownedTypeInst);
  22254. }
  22255. if (mBfIRBuilder->DbgHasInfo())
  22256. {
  22257. mBfIRBuilder->DbgFinalize();
  22258. }
  22259. String objOutputPath;
  22260. String irOutputPath;
  22261. mIsModuleMutable = false;
  22262. //mOutFileNames.Clear();
  22263. BF_ASSERT(((int)mOutFileNames.size() >= mExtensionCount) || (mParentModule != NULL));
  22264. bool writeModule = mBfIRBuilder->HasExports();
  22265. String outputPath;
  22266. BfCodeGenOptions codeGenOptions = mProject->mCodeGenOptions;
  22267. auto& compilerOpts = mCompiler->mOptions;
  22268. codeGenOptions.mSIMDSetting = compilerOpts.mSIMDSetting;
  22269. auto moduleOptions = GetModuleOptions();
  22270. codeGenOptions.mOptLevel = moduleOptions.mOptLevel;
  22271. codeGenOptions.mSIMDSetting = moduleOptions.mSIMDSetting;
  22272. codeGenOptions.mWriteLLVMIR = mCompiler->mOptions.mWriteIR;
  22273. codeGenOptions.mWriteObj = mCompiler->mOptions.mGenerateObj;
  22274. codeGenOptions.mWriteBitcode = mCompiler->mOptions.mGenerateBitcode;
  22275. codeGenOptions.mVirtualMethodOfs = 1 + mCompiler->GetDynCastVDataCount() + mCompiler->mMaxInterfaceSlots;
  22276. codeGenOptions.mDynSlotOfs = mSystem->mPtrSize - mCompiler->GetDynCastVDataCount() * 4;
  22277. mCompiler->mStats.mIRBytes += mBfIRBuilder->mStream.GetSize();
  22278. mCompiler->mStats.mConstBytes += mBfIRBuilder->mTempAlloc.GetAllocSize();
  22279. bool allowWriteToLib = true;
  22280. if ((allowWriteToLib) && (codeGenOptions.mOptLevel == BfOptLevel_OgPlus) &&
  22281. (!mCompiler->IsHotCompile()) && (mModuleName != "vdata"))
  22282. {
  22283. codeGenOptions.mWriteToLib = true;
  22284. mWroteToLib = true;
  22285. }
  22286. else
  22287. {
  22288. mWroteToLib = false;
  22289. }
  22290. for (int fileIdx = 0; fileIdx <= mExtensionCount; fileIdx++)
  22291. {
  22292. outputPath = mModuleName;
  22293. outputPath = mCompiler->mOutputDirectory + "/" + mProject->mName + "/" + outputPath;
  22294. BfModuleFileName moduleFileName;
  22295. if (mParentModule != NULL)
  22296. {
  22297. for (auto&& checkPair : mParentModule->mSpecializedMethodModules)
  22298. {
  22299. if (checkPair.mValue == this)
  22300. moduleFileName.mProjects = checkPair.mKey;
  22301. }
  22302. }
  22303. moduleFileName.mProjects.Add(mProject);
  22304. if (fileIdx > 0)
  22305. outputPath += StrFormat("@%d", fileIdx + 1);
  22306. if (mCompiler->mOptions.mWriteIR)
  22307. irOutputPath = outputPath + ".ll";
  22308. if (mCompiler->mOptions.mGenerateObj)
  22309. {
  22310. objOutputPath = outputPath + BF_OBJ_EXT;
  22311. moduleFileName.mFileName = objOutputPath;
  22312. }
  22313. else if (mCompiler->mOptions.mWriteIR)
  22314. {
  22315. moduleFileName.mFileName = irOutputPath;
  22316. }
  22317. else if ((!mCompiler->mOptions.mGenerateObj) && (!mCompiler->mOptions.mGenerateBitcode) && (!mCompiler->mOptions.mWriteIR))
  22318. {
  22319. BFMODULE_FATAL(this, "Neither obj nor IR specified");
  22320. }
  22321. moduleFileName.mModuleWritten = writeModule;
  22322. moduleFileName.mWroteToLib = mWroteToLib;
  22323. if (!mOutFileNames.Contains(moduleFileName))
  22324. mOutFileNames.Add(moduleFileName);
  22325. }
  22326. if (mCompiler->IsHotCompile())
  22327. {
  22328. codeGenOptions.mIsHotCompile = true;
  22329. if (mParentModule != NULL)
  22330. mParentModule->mHadHotObjectWrites = true;
  22331. mHadHotObjectWrites = true;
  22332. }
  22333. //TODO: Testing VDATA
  22334. /*if (mModuleName == "vdata")
  22335. {
  22336. codeGenOptions.mOptLevel = 4;
  22337. }*/
  22338. codeGenOptions.GenerateHash();
  22339. BP_ZONE("BfModule::Finish.WriteObjectFile");
  22340. if ((writeModule) && (!mBfIRBuilder->mIgnoreWrites))
  22341. mCompiler->mCodeGen.WriteObjectFile(this, outputPath, codeGenOptions);
  22342. mLastModuleWrittenRevision = mCompiler->mRevision;
  22343. }
  22344. else
  22345. {
  22346. for (auto type : mOwnedTypeInstances)
  22347. {
  22348. BF_ASSERT((!type->IsIncomplete()) || (type->IsSpecializedByAutoCompleteMethod()));
  22349. }
  22350. }
  22351. for (auto& specModulePair : mSpecializedMethodModules)
  22352. {
  22353. auto specModule = specModulePair.mValue;
  22354. if ((specModule->mIsModuleMutable) && (!specModule->mAwaitingFinish))
  22355. {
  22356. BfLogSysM(" Mutable spec module remaining: %p\n", specModule);
  22357. }
  22358. }
  22359. CleanupFileInstances();
  22360. // We can't ClearModuleData here because we need the mSpecializedMethodModules to remain valid until we Finish them too
  22361. return true;
  22362. }
  22363. void BfModule::ReportMemory(MemReporter* memReporter)
  22364. {
  22365. memReporter->Add(sizeof(BfModule));
  22366. if (mBfIRBuilder != NULL)
  22367. {
  22368. memReporter->BeginSection("IRBuilder_ConstData");
  22369. memReporter->Add("Used", mBfIRBuilder->mTempAlloc.GetAllocSize());
  22370. memReporter->Add("Unused", mBfIRBuilder->mTempAlloc.GetTotalAllocSize() - mBfIRBuilder->mTempAlloc.GetAllocSize());
  22371. memReporter->EndSection();
  22372. memReporter->BeginSection("IRBuilder_BFIR");
  22373. memReporter->Add("Used", (int)(mBfIRBuilder->mStream.GetSize()));
  22374. memReporter->Add("Unused", (int)(mBfIRBuilder->mStream.mPools.size() * ChunkedDataBuffer::ALLOC_SIZE) - mBfIRBuilder->mStream.GetSize());
  22375. memReporter->EndSection();
  22376. memReporter->Add(sizeof(BfIRBuilder));
  22377. }
  22378. memReporter->BeginSection("FileInstanceMap");
  22379. memReporter->AddMap(mFileInstanceMap);
  22380. memReporter->AddMap(mNamedFileInstanceMap);
  22381. memReporter->Add((int)mNamedFileInstanceMap.size() * sizeof(BfFileInstance));
  22382. memReporter->EndSection();
  22383. memReporter->AddVec(mOwnedTypeInstances, false);
  22384. memReporter->AddVec(mSpecializedMethodModules, false);
  22385. memReporter->AddVec(mOutFileNames, false);
  22386. memReporter->AddMap("FuncReferences", mFuncReferences, false);
  22387. memReporter->AddMap(mInterfaceSlotRefs, false);
  22388. memReporter->AddMap(mStaticFieldRefs, false);
  22389. memReporter->AddMap(mClassVDataRefs, false);
  22390. memReporter->AddMap("VDataExtMap", mClassVDataExtRefs, false);
  22391. memReporter->AddMap(mTypeDataRefs, false);
  22392. memReporter->AddMap(mDbgRawAllocDataRefs, false);
  22393. memReporter->AddMap(mDeferredMethodCallData, false);
  22394. memReporter->AddHashSet(mDeferredMethodIds, false);
  22395. memReporter->AddHashSet("ModuleRefs", mModuleRefs, false);
  22396. }
  22397. // ClearModuleData is called immediately after the module is compiled, so don't clear out any data that needs to
  22398. // be transient through the next compile
  22399. void BfModule::ClearModuleData(bool clearTransientData)
  22400. {
  22401. BfLogSysM("ClearModuleData %p\n", this);
  22402. if (mAddedToCount)
  22403. {
  22404. mCompiler->mStats.mModulesFinished++;
  22405. mAddedToCount = false;
  22406. }
  22407. mDICompileUnit = BfIRMDNode();
  22408. if (clearTransientData)
  22409. mIncompleteMethodCount = 0;
  22410. mHasGenericMethods = false;
  22411. // We don't want to clear these because we want it to persist through module extensions-
  22412. // otherwise we may think an extension succeeds even though the base module failed
  22413. //mHadBuildError = false;
  22414. //mHadBuildWarning = false;
  22415. mClassVDataRefs.Clear();
  22416. mClassVDataExtRefs.Clear();
  22417. for (auto& kv : mTypeDataRefs)
  22418. kv.mValue = BfIRValue();
  22419. mStringCharPtrPool.Clear();
  22420. mStringObjectPool.Clear();
  22421. mStaticFieldRefs.Clear();
  22422. BF_ASSERT(!mIgnoreErrors);
  22423. for (auto prevIRBuilder : mPrevIRBuilders)
  22424. delete prevIRBuilder;
  22425. mPrevIRBuilders.Clear();
  22426. for (auto& specPair : mSpecializedMethodModules)
  22427. {
  22428. auto specModule = specPair.mValue;
  22429. specModule->ClearModuleData();
  22430. }
  22431. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  22432. mBuiltInFuncs[i] = BfIRFunction();
  22433. if (mNextAltModule != NULL)
  22434. mNextAltModule->ClearModuleData();
  22435. BfLogSysM("ClearModuleData. Deleting IRBuilder: %p\n", mBfIRBuilder);
  22436. mIsModuleMutable = false;
  22437. delete mBfIRBuilder;
  22438. mBfIRBuilder = NULL;
  22439. mWantsIRIgnoreWrites = false;
  22440. }
  22441. void BfModule::DisownMethods()
  22442. {
  22443. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  22444. mBuiltInFuncs[i] = BfIRFunction();
  22445. BfModule* methodModule = this;
  22446. if (mParentModule != NULL)
  22447. methodModule = mParentModule;
  22448. for (auto typeInst : methodModule->mOwnedTypeInstances)
  22449. {
  22450. for (auto& methodGroup : typeInst->mMethodInstanceGroups)
  22451. {
  22452. if (methodGroup.mDefault != NULL)
  22453. {
  22454. if (methodGroup.mDefault->mIRFunction)
  22455. {
  22456. BF_ASSERT(methodGroup.mDefault->mDeclModule != NULL);
  22457. if (methodGroup.mDefault->mDeclModule == this)
  22458. {
  22459. methodGroup.mDefault->mIRFunction = BfIRFunction();
  22460. }
  22461. }
  22462. }
  22463. if (methodGroup.mMethodSpecializationMap != NULL)
  22464. {
  22465. for (auto& mapPair : *methodGroup.mMethodSpecializationMap)
  22466. {
  22467. auto methodInstance = mapPair.mValue;
  22468. if (methodInstance->mDeclModule == this)
  22469. {
  22470. methodInstance->mIRFunction = BfIRFunction();
  22471. }
  22472. }
  22473. }
  22474. }
  22475. }
  22476. }
  22477. void BfModule::ClearModule()
  22478. {
  22479. ClearModuleData();
  22480. DisownMethods();
  22481. for (auto& specPair : mSpecializedMethodModules)
  22482. {
  22483. auto specModule = specPair.mValue;
  22484. specModule->ClearModule();
  22485. }
  22486. if (mNextAltModule != NULL)
  22487. mNextAltModule->ClearModule();
  22488. }