BfModule.cpp 700 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764
  1. //#define USE_THUNKED_MddLLOC..
  2. #include "BeefySysLib/util/AllocDebug.h"
  3. #pragma warning(push) // 6
  4. #pragma warning(disable:4996)
  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 <fcntl.h>
  12. #include "BfConstResolver.h"
  13. #include "BfMangler.h"
  14. #include "BeefySysLib/util/PerfTimer.h"
  15. #include "BeefySysLib/util/BeefPerf.h"
  16. #include "BeefySysLib/util/StackHelper.h"
  17. #include "BfSourceClassifier.h"
  18. #include "BfAutoComplete.h"
  19. #include "BfDemangler.h"
  20. #include "BfResolvePass.h"
  21. #include "BfFixits.h"
  22. #include "BfIRCodeGen.h"
  23. #include "BfDefBuilder.h"
  24. #include "BfDeferEvalChecker.h"
  25. #pragma warning(pop)
  26. //////////////////////////////////////////////////////////////////////////
  27. static bool gDebugStuff = false;
  28. USING_NS_BF;
  29. //////////////////////////////////////////////////////////////////////////
  30. void BfLocalVariable::Init()
  31. {
  32. if (mResolvedType->IsValuelessType())
  33. {
  34. mIsAssigned = true;
  35. return;
  36. }
  37. if (mIsAssigned)
  38. return;
  39. bool isStruct = mResolvedType->IsStruct();
  40. if (mResolvedType->IsRef())
  41. isStruct = mResolvedType->GetUnderlyingType()->IsStruct();
  42. if ((isStruct) || ((mIsThis) && (mResolvedType->IsStructOrStructPtr())))
  43. {
  44. auto resolvedTypeRef = mResolvedType;
  45. if ((resolvedTypeRef->IsPointer()) || (resolvedTypeRef->IsRef()))
  46. resolvedTypeRef = resolvedTypeRef->GetUnderlyingType();
  47. auto typeInstance = resolvedTypeRef->ToTypeInstance();
  48. mUnassignedFieldFlags = (1 << typeInstance->mMergedFieldDataCount) - 1;
  49. if ((mIsThis) && (typeInstance->mBaseType != NULL))
  50. {
  51. // Base ctor is responsible for initializing its own fields
  52. mUnassignedFieldFlags &= ~(((int64)1 << typeInstance->mBaseType->mMergedFieldDataCount) - 1);
  53. }
  54. if (mUnassignedFieldFlags == 0)
  55. mIsAssigned = true;
  56. }
  57. else
  58. {
  59. mUnassignedFieldFlags = 1;
  60. }
  61. }
  62. BfLocalMethod::~BfLocalMethod()
  63. {
  64. BfLogSys(mSystem, "~BfLocalMethod %p\n", this);
  65. if (mMethodDeclaration != NULL)
  66. {
  67. mSource->mRefCount--;
  68. BF_ASSERT(mSource->mRefCount >= 0);
  69. }
  70. delete mMethodDef;
  71. delete mMethodInstanceGroup;
  72. }
  73. void BfDeferredLocalAssignData::ExtendFrom(BfDeferredLocalAssignData* outerLocalAssignData, bool doChain)
  74. {
  75. mIsChained = doChain;
  76. if (outerLocalAssignData == NULL)
  77. return;
  78. mChainedAssignData = outerLocalAssignData;
  79. if (!doChain)
  80. {
  81. outerLocalAssignData->BreakExtendChain();
  82. mAssignedLocals = outerLocalAssignData->mAssignedLocals;
  83. }
  84. mVarIdBarrier = outerLocalAssignData->mVarIdBarrier;
  85. }
  86. // The "extend chain" is broken when we have a conditional where the variable may not be defined after the block.
  87. // IE: "a" will be defined after the following, but "b" will not necessarily be defined.
  88. // if ((GetValue(out a)) && (GetValue(out b)) {}
  89. void BfDeferredLocalAssignData::BreakExtendChain()
  90. {
  91. if (!mIsChained)
  92. return;
  93. mIsChained = false;
  94. if (mChainedAssignData == NULL)
  95. return;
  96. mChainedAssignData->BreakExtendChain();
  97. mAssignedLocals = mChainedAssignData->mAssignedLocals;
  98. }
  99. void BfDeferredLocalAssignData::SetIntersection(const BfDeferredLocalAssignData& otherLocalAssignData)
  100. {
  101. BreakExtendChain();
  102. //TODO: We got rid of this case because we now set the proper assigned data when we do a return
  103. // If one of these had a return then treat that case as if it did have an assign -- because it doesn't
  104. // cause an UNASSIGNED value to be used
  105. // if (mHadReturn || otherLocalAssignData.mHadReturn)
  106. // {
  107. // SetUnion(otherLocalAssignData);
  108. // mHadFallthrough = mHadFallthrough && otherLocalAssignData.mHadFallthrough;
  109. // return;
  110. // }
  111. for (int i = 0; i < (int)mAssignedLocals.size(); )
  112. {
  113. auto& local = mAssignedLocals[i];
  114. if (!otherLocalAssignData.mAssignedLocals.Contains(local))
  115. {
  116. mAssignedLocals.RemoveAt(i);
  117. }
  118. else
  119. i++;
  120. }
  121. mHadFallthrough = mHadFallthrough && otherLocalAssignData.mHadFallthrough;
  122. }
  123. void BfDeferredLocalAssignData::Validate() const
  124. {
  125. for (auto var : mAssignedLocals)
  126. {
  127. BF_ASSERT((uintptr)var.mLocalVar->mName.length() < 100000);
  128. }
  129. }
  130. void BfDeferredLocalAssignData::SetUnion(const BfDeferredLocalAssignData& otherLocalAssignData)
  131. {
  132. BreakExtendChain();
  133. Validate();
  134. otherLocalAssignData.Validate();
  135. auto otherItr = otherLocalAssignData.mAssignedLocals.begin();
  136. while (otherItr != otherLocalAssignData.mAssignedLocals.end())
  137. {
  138. if (!mAssignedLocals.Contains(*otherItr))
  139. mAssignedLocals.push_back(*otherItr);
  140. ++otherItr;
  141. }
  142. mHadFallthrough = mHadFallthrough || otherLocalAssignData.mHadFallthrough;
  143. }
  144. BfMethodState::~BfMethodState()
  145. {
  146. BF_ASSERT(mPendingNullConditional == NULL);
  147. if (mPrevMethodState != NULL)
  148. {
  149. BF_ASSERT(mCurAccessId == 1);
  150. BF_ASSERT(mCurLocalVarId <= 0);
  151. }
  152. for (auto local : mLocals)
  153. delete local;
  154. for (auto& kv : mLambdaCache)
  155. delete kv.mValue;
  156. }
  157. BfMethodState* BfMethodState::GetMethodStateForLocal(BfLocalVariable* localVar)
  158. {
  159. auto checkMethodState = this;
  160. while (checkMethodState != NULL)
  161. {
  162. if ((localVar->mLocalVarIdx < checkMethodState->mLocals.size()) &&
  163. (checkMethodState->mLocals[localVar->mLocalVarIdx] == localVar))
  164. return checkMethodState;
  165. checkMethodState = checkMethodState->mPrevMethodState;
  166. }
  167. BF_FATAL("Failed to find method state for localvar");
  168. return NULL;
  169. }
  170. void BfMethodState::LocalDefined(BfLocalVariable* localVar, int fieldIdx)
  171. {
  172. auto localVarMethodState = GetMethodStateForLocal(localVar);
  173. if (localVarMethodState != this)
  174. {
  175. return;
  176. }
  177. //BF_ASSERT(localVarMethodState == this);
  178. if (!localVar->mIsAssigned)
  179. {
  180. BfDeferredLocalAssignData* ifDeferredLocalAssignData = NULL;
  181. // 'a' is always defined, but 'b' isn't:
  182. // if (Check(out a) || Check(out b)) { } int z = a;
  183. auto deferredLocalAssignData = mDeferredLocalAssignData;
  184. if ((deferredLocalAssignData != NULL) &&
  185. (deferredLocalAssignData->mIsIfCondition) &&
  186. (!deferredLocalAssignData->mIfMayBeSkipped))
  187. {
  188. ifDeferredLocalAssignData = deferredLocalAssignData;
  189. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  190. }
  191. while ((deferredLocalAssignData != NULL) &&
  192. ((deferredLocalAssignData->mIsChained) || (deferredLocalAssignData->mIsUnconditional)))
  193. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  194. if ((deferredLocalAssignData == NULL) || (localVar->mLocalVarId >= deferredLocalAssignData->mVarIdBarrier))
  195. {
  196. if (fieldIdx >= 0)
  197. {
  198. localVar->mUnassignedFieldFlags &= ~((int64)1 << fieldIdx);
  199. /*if ((localVar->mResolvedTypeRef != NULL) && (localVar->mResolvedTypeRef->IsUnion()))
  200. {
  201. }*/
  202. if (localVar->mUnassignedFieldFlags == 0)
  203. localVar->mIsAssigned = true;
  204. }
  205. else
  206. {
  207. localVar->mIsAssigned = true;
  208. }
  209. }
  210. else
  211. {
  212. BF_ASSERT(deferredLocalAssignData->mVarIdBarrier != -1);
  213. BfAssignedLocal defineVal = {localVar, fieldIdx + 1};
  214. auto& assignedLocals = deferredLocalAssignData->mAssignedLocals;
  215. if (!assignedLocals.Contains(defineVal))
  216. assignedLocals.push_back(defineVal);
  217. if (ifDeferredLocalAssignData != NULL)
  218. {
  219. auto& assignedLocals = ifDeferredLocalAssignData->mAssignedLocals;
  220. if (!assignedLocals.Contains(defineVal))
  221. assignedLocals.push_back(defineVal);
  222. }
  223. }
  224. }
  225. localVar->mWrittenToId = GetRootMethodState()->mCurAccessId++;
  226. }
  227. void BfMethodState::ApplyDeferredLocalAssignData(const BfDeferredLocalAssignData& deferredLocalAssignData)
  228. {
  229. BF_ASSERT(&deferredLocalAssignData != mDeferredLocalAssignData);
  230. for (auto& assignedLocal : deferredLocalAssignData.mAssignedLocals)
  231. {
  232. LocalDefined(assignedLocal.mLocalVar);
  233. }
  234. }
  235. void BfMethodState::Reset()
  236. {
  237. mHeadScope.mDeferredCallEntries.DeleteAll();
  238. }
  239. //////////////////////////////////////////////////////////////////////////
  240. void BfAmbiguityContext::Add(int id, BfTypeInterfaceEntry* interfaceEntry, int methodIdx, BfMethodInstance* candidateA, BfMethodInstance* candidateB)
  241. {
  242. Entry* entry = NULL;
  243. if (mEntries.TryAdd(id, NULL, &entry))
  244. {
  245. entry->mInterfaceEntry = interfaceEntry;
  246. entry->mMethodIdx = methodIdx;
  247. }
  248. if (!entry->mCandidates.Contains(candidateA))
  249. entry->mCandidates.push_back(candidateA);
  250. if (!entry->mCandidates.Contains(candidateB))
  251. entry->mCandidates.push_back(candidateB);
  252. }
  253. void BfAmbiguityContext::Remove(int id)
  254. {
  255. mEntries.Remove(id);
  256. }
  257. void BfAmbiguityContext::Finish()
  258. {
  259. for (auto& entryPair : mEntries)
  260. {
  261. int id = entryPair.mKey;
  262. auto entry = &entryPair.mValue;
  263. if (id >= 0)
  264. {
  265. auto declMethodInstance = mTypeInstance->mVirtualMethodTable[id].mDeclaringMethod;
  266. auto error = mModule->Fail(StrFormat("Method '%s' has ambiguous overrides", mModule->MethodToString(declMethodInstance).c_str()), declMethodInstance->mMethodDef->GetRefNode());
  267. for (auto candidate : entry->mCandidates)
  268. {
  269. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", mModule->MethodToString(candidate).c_str()), candidate->mMethodDef->GetRefNode());
  270. }
  271. }
  272. else
  273. {
  274. auto iMethodInst = entry->mInterfaceEntry->mInterfaceType->mMethodInstanceGroups[entry->mMethodIdx].mDefault;
  275. auto error = mModule->Fail(StrFormat("Interface method '%s' has ambiguous implementations", mModule->MethodToString(iMethodInst).c_str()), entry->mInterfaceEntry->mDeclaringType->GetRefNode());
  276. for (auto candidate : entry->mCandidates)
  277. {
  278. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", mModule->MethodToString(candidate).c_str()), candidate->mMethodDef->GetRefNode());
  279. }
  280. }
  281. }
  282. }
  283. //////////////////////////////////////////////////////////////////////////
  284. class HasAppendAllocVisitor : BfElementVisitor
  285. {
  286. public:
  287. bool mHas;
  288. public:
  289. HasAppendAllocVisitor()
  290. {
  291. mHas = false;
  292. }
  293. void Visit(BfObjectCreateExpression* objCreateExpr)
  294. {
  295. if (auto newToken = BfNodeDynCast<BfTokenNode>(objCreateExpr->mNewNode))
  296. {
  297. if (newToken->GetToken() == BfToken_Append)
  298. {
  299. mHas = true;
  300. }
  301. }
  302. }
  303. bool HasAppendAlloc(BfAstNode* node)
  304. {
  305. mHas = false;
  306. VisitChild(node);
  307. return mHas;
  308. }
  309. };
  310. class AppendAllocVisitor : public BfStructuralVisitor
  311. {
  312. public:
  313. BfModule* mModule;
  314. HasAppendAllocVisitor mHasAppendAllocVisitor;
  315. BfTypedValue mConstAccum;
  316. bool mFailed;
  317. bool mIsFirstConstPass;
  318. int mCurAppendAlign;
  319. public:
  320. AppendAllocVisitor()
  321. {
  322. mFailed = false;
  323. mIsFirstConstPass = false;
  324. mCurAppendAlign = 0;
  325. }
  326. void EmitAppendAlign(int align, int sizeMultiple = 0)
  327. {
  328. if (mIsFirstConstPass)
  329. mModule->mCurMethodInstance->mAppendAllocAlign = BF_MAX((int)mModule->mCurMethodInstance->mAppendAllocAlign, align);
  330. if (sizeMultiple == 0)
  331. sizeMultiple = align;
  332. if (mCurAppendAlign == 0)
  333. mCurAppendAlign = sizeMultiple;
  334. else
  335. {
  336. if (sizeMultiple % align == 0)
  337. mCurAppendAlign = align;
  338. else
  339. mCurAppendAlign = sizeMultiple % align;
  340. }
  341. if (mConstAccum)
  342. {
  343. auto constant = mModule->mBfIRBuilder->GetConstant(mConstAccum.mValue);
  344. if (constant != NULL)
  345. mConstAccum.mValue = mModule->GetConstValue(BF_ALIGN(constant->mInt64, align));
  346. else
  347. BF_ASSERT(mIsFirstConstPass);
  348. return;
  349. }
  350. mModule->EmitAppendAlign(align, sizeMultiple);
  351. }
  352. void Visit(BfAstNode* astNode)
  353. {
  354. mModule->VisitChild(astNode);
  355. }
  356. void DoObjectCreate(BfObjectCreateExpression* objCreateExpr, BfVariableDeclaration* variableDecl)
  357. {
  358. if (auto newToken = BfNodeDynCast<BfTokenNode>(objCreateExpr->mNewNode))
  359. {
  360. if (newToken->GetToken() == BfToken_Append)
  361. {
  362. //auto variableDecl = BfNodeDynCast<BfVariableDeclaration>(objCreateExpr->mParent);
  363. auto accumValuePtr = mModule->mCurMethodState->mRetVal.mValue;
  364. auto intPtrType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  365. BfArrayType* arrayType = NULL;
  366. bool isArrayAlloc = false;
  367. bool isRawArrayAlloc = objCreateExpr->mStarToken != NULL;
  368. SizedArray<BfIRValue, 2> dimLengthVals;
  369. BfType* origResolvedTypeRef = NULL;
  370. if (auto dotTypeRef = BfNodeDynCast<BfDotTypeReference>(objCreateExpr->mTypeRef))
  371. {
  372. if (variableDecl != NULL)
  373. {
  374. origResolvedTypeRef = mModule->ResolveTypeRef(variableDecl->mTypeRef, BfPopulateType_Data, BfResolveTypeRefFlag_NoResolveGenericParam);
  375. if (origResolvedTypeRef->IsObject())
  376. {
  377. if (origResolvedTypeRef->IsArray())
  378. {
  379. arrayType = (BfArrayType*)origResolvedTypeRef;
  380. origResolvedTypeRef = origResolvedTypeRef->GetUnderlyingType();
  381. isArrayAlloc = true;
  382. }
  383. }
  384. else if (origResolvedTypeRef->IsPointer())
  385. {
  386. origResolvedTypeRef = origResolvedTypeRef->GetUnderlyingType();
  387. }
  388. }
  389. }
  390. else if (auto arrayTypeRef = BfNodeDynCast<BfArrayTypeRef>(objCreateExpr->mTypeRef))
  391. {
  392. isArrayAlloc = true;
  393. origResolvedTypeRef = mModule->ResolveTypeRef(arrayTypeRef->mElementType);
  394. int dimensions = 1;
  395. if (arrayTypeRef->mParams.size() != 0)
  396. {
  397. auto intType = mModule->ResolveTypeDef(mModule->mSystem->mTypeIntPtr);
  398. for (auto arg : arrayTypeRef->mParams)
  399. {
  400. if (auto tokenNode = BfNodeDynCastExact<BfTokenNode>(arg))
  401. {
  402. if (tokenNode->GetToken() == BfToken_Comma)
  403. {
  404. if (isRawArrayAlloc)
  405. {
  406. mModule->Fail("Sized arrays cannot be multidimensional", tokenNode);
  407. continue;
  408. }
  409. dimensions++;
  410. continue;
  411. }
  412. }
  413. auto expr = BfNodeDynCast<BfExpression>(arg);
  414. if ((isRawArrayAlloc) && (!dimLengthVals.IsEmpty()))
  415. {
  416. mModule->CreateValueFromExpression(expr, intType);
  417. continue;
  418. }
  419. BfTypedValue dimLength;
  420. if (expr == NULL)
  421. {
  422. // Not specified
  423. dimLengthVals.push_back(BfIRValue());
  424. continue;
  425. }
  426. if (arg != NULL)
  427. dimLength = mModule->CreateValueFromExpression(expr, intType);
  428. if (!dimLength)
  429. {
  430. dimLength = mModule->GetDefaultTypedValue(intType);
  431. }
  432. dimLengthVals.push_back(dimLength.mValue);
  433. }
  434. }
  435. if (!isRawArrayAlloc)
  436. arrayType = mModule->CreateArrayType(origResolvedTypeRef, dimensions);
  437. }
  438. if (origResolvedTypeRef == NULL)
  439. origResolvedTypeRef = mModule->ResolveTypeRef(objCreateExpr->mTypeRef, BfPopulateType_Data, BfResolveTypeRefFlag_NoResolveGenericParam);
  440. if (origResolvedTypeRef == NULL)
  441. {
  442. mModule->AssertErrorState();
  443. return;
  444. }
  445. bool isGenericParam = origResolvedTypeRef->IsGenericParam();
  446. auto resolvedTypeRef = origResolvedTypeRef;
  447. auto resultType = resolvedTypeRef;
  448. BfIRValue sizeValue;
  449. int curAlign = 0;
  450. if (isArrayAlloc)
  451. {
  452. int dimensions = 1;
  453. if (arrayType != NULL)
  454. dimensions = arrayType->mDimensions;
  455. bool sizeFailed = false;
  456. //
  457. {
  458. BfAstNode* initNode = objCreateExpr;
  459. for (int dim = 0; dim < dimensions; dim++)
  460. {
  461. BfAstNode* nextInitNode = NULL;
  462. int dimSize = -1;
  463. if (initNode == objCreateExpr)
  464. {
  465. dimSize = objCreateExpr->mArguments.size();
  466. if (!objCreateExpr->mArguments.IsEmpty())
  467. nextInitNode = objCreateExpr->mArguments[0];
  468. }
  469. else if (auto tupleNode = BfNodeDynCast<BfTupleExpression>(initNode))
  470. {
  471. dimSize = (int)tupleNode->mCommas.size() + 1;
  472. }
  473. if (dimSize >= 0)
  474. {
  475. if (dim >= dimLengthVals.size())
  476. dimLengthVals.Add(mModule->GetConstValue(dimSize));
  477. }
  478. else
  479. {
  480. sizeFailed = true;
  481. }
  482. }
  483. }
  484. BfIRValue allocCount;
  485. if (!sizeFailed)
  486. {
  487. if (!dimLengthVals.IsEmpty())
  488. {
  489. allocCount = dimLengthVals[0];
  490. for (int dim = 1; dim < (int)dimLengthVals.size(); dim++)
  491. allocCount = mModule->mBfIRBuilder->CreateMul(allocCount, dimLengthVals[dim]);
  492. }
  493. }
  494. if (!allocCount)
  495. {
  496. mFailed = true;
  497. if (!mIsFirstConstPass)
  498. {
  499. if (!mConstAccum)
  500. mModule->Fail("Unable to determine append alloc size", objCreateExpr->mNewNode);
  501. return;
  502. }
  503. }
  504. if (isRawArrayAlloc)
  505. {
  506. curAlign = resultType->mAlign;
  507. EmitAppendAlign(resultType->mAlign);
  508. sizeValue = mModule->mBfIRBuilder->CreateMul(mModule->GetConstValue(resultType->mSize), allocCount);
  509. }
  510. else
  511. {
  512. if (arrayType == NULL)
  513. arrayType = mModule->CreateArrayType(resultType, 1);
  514. // Array is a special case where the total size isn't aligned with mAlign
  515. // since we add arbitrary elements to the end without padding the end to align
  516. EmitAppendAlign(arrayType->mAlign, resultType->mAlign);
  517. curAlign = arrayType->mAlign;
  518. auto firstElementField = &arrayType->mFieldInstances.back();
  519. int arrayClassSize = arrayType->mInstSize - firstElementField->mDataSize;
  520. sizeValue = mModule->GetConstValue(arrayClassSize);
  521. BfIRValue elementDataSize = mModule->mBfIRBuilder->CreateMul(mModule->GetConstValue(resultType->mSize), allocCount);
  522. sizeValue = mModule->mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  523. }
  524. }
  525. else
  526. {
  527. auto typeInst = resultType->ToTypeInstance();
  528. if (typeInst != NULL)
  529. {
  530. curAlign = typeInst->mInstAlign;
  531. EmitAppendAlign(typeInst->mInstAlign, typeInst->mInstSize);
  532. sizeValue = mModule->GetConstValue(typeInst->mInstSize);
  533. }
  534. else
  535. {
  536. curAlign = resultType->mAlign;
  537. EmitAppendAlign(resultType->mAlign, resultType->mSize);
  538. sizeValue = mModule->GetConstValue(resultType->mSize);
  539. }
  540. BfTypedValue emtpyThis(mModule->mBfIRBuilder->GetFakeVal(), resultType, (typeInst == NULL) || (typeInst->IsComposite()));
  541. BfExprEvaluator exprEvaluator(mModule);
  542. SetAndRestoreValue<bool> prevNoBind(exprEvaluator.mNoBind, exprEvaluator.mNoBind || isGenericParam);
  543. BfFunctionBindResult bindResult;
  544. bindResult.mWantsArgs = true;
  545. exprEvaluator.mFunctionBindResult = &bindResult;
  546. SizedArray<BfExpression*, 8> copiedArgs;
  547. for (BfExpression* arg : objCreateExpr->mArguments)
  548. copiedArgs.push_back(arg);
  549. BfSizedArray<BfExpression*> sizedArgExprs(copiedArgs);
  550. BfResolvedArgs argValues(&sizedArgExprs);
  551. if (typeInst != NULL)
  552. {
  553. exprEvaluator.ResolveArgValues(argValues);
  554. exprEvaluator.MatchConstructor(objCreateExpr->mTypeRef, objCreateExpr, emtpyThis, typeInst, argValues, false, true);
  555. }
  556. exprEvaluator.mFunctionBindResult = NULL;
  557. if (bindResult.mMethodInstance != NULL)
  558. {
  559. if (bindResult.mMethodInstance->mMethodDef->mHasAppend)
  560. {
  561. auto calcAppendArgs = bindResult.mIRArgs;
  562. BF_ASSERT(calcAppendArgs[0].IsFake());
  563. calcAppendArgs.RemoveRange(0, 2); // Remove 'this' and 'appendIdx'
  564. auto calcAppendMethodModule = mModule->GetMethodInstanceAtIdx(bindResult.mMethodInstance->GetOwner(), bindResult.mMethodInstance->mMethodDef->mIdx + 1, BF_METHODNAME_CALCAPPEND);
  565. auto subDependSize = mModule->TryConstCalcAppend(bindResult.mMethodInstance, calcAppendArgs);
  566. if (calcAppendMethodModule.mMethodInstance->mAppendAllocAlign > 0)
  567. {
  568. EmitAppendAlign(calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  569. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign > -1);
  570. mModule->mCurMethodState->mCurAppendAlign = BF_MAX(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign, 0);
  571. }
  572. curAlign = std::max(curAlign, (int)calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  573. if ((!subDependSize) && (!mConstAccum))
  574. {
  575. BF_ASSERT(calcAppendMethodModule.mFunc);
  576. subDependSize = exprEvaluator.CreateCall(calcAppendMethodModule.mMethodInstance, calcAppendMethodModule.mFunc, false, calcAppendArgs);
  577. BF_ASSERT(subDependSize.mType == mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  578. }
  579. if (subDependSize)
  580. sizeValue = mModule->mBfIRBuilder->CreateAdd(sizeValue, subDependSize.mValue);
  581. else
  582. mFailed = true;
  583. }
  584. }
  585. }
  586. if (sizeValue)
  587. {
  588. if (mConstAccum)
  589. {
  590. if (!sizeValue.IsConst())
  591. {
  592. mFailed = true;
  593. if (!mIsFirstConstPass)
  594. return;
  595. }
  596. mConstAccum.mValue = mModule->mBfIRBuilder->CreateAdd(sizeValue, mConstAccum.mValue);
  597. }
  598. else
  599. {
  600. auto prevVal = mModule->mBfIRBuilder->CreateLoad(accumValuePtr);
  601. auto addedVal = mModule->mBfIRBuilder->CreateAdd(sizeValue, prevVal);
  602. mModule->mBfIRBuilder->CreateStore(addedVal, accumValuePtr);
  603. }
  604. }
  605. }
  606. }
  607. }
  608. void Visit(BfObjectCreateExpression* objCreateExpr) override
  609. {
  610. DoObjectCreate(objCreateExpr, NULL);
  611. }
  612. void Visit(BfVariableDeclaration* varDecl) override
  613. {
  614. if (mHasAppendAllocVisitor.HasAppendAlloc(varDecl))
  615. {
  616. if (auto objectCreateExpr = BfNodeDynCast<BfObjectCreateExpression>(varDecl->mInitializer))
  617. DoObjectCreate(objectCreateExpr, varDecl);
  618. else
  619. VisitChild(varDecl->mInitializer);
  620. if (varDecl->mNameNode != NULL)
  621. {
  622. BfLocalVariable* localDef = new BfLocalVariable();
  623. localDef->mName = varDecl->mNameNode->ToString();
  624. localDef->mNameNode = BfNodeDynCast<BfIdentifierNode>(varDecl->mNameNode);
  625. localDef->mResolvedType = mModule->GetPrimitiveType(BfTypeCode_None);
  626. localDef->mIsReadOnly = true;
  627. localDef->mParamFailed = true;
  628. localDef->mReadFromId = 0;
  629. mModule->AddLocalVariableDef(localDef);
  630. }
  631. }
  632. else
  633. {
  634. mModule->Visit(varDecl);
  635. }
  636. }
  637. void Visit(BfExpressionStatement* exprStatement) override
  638. {
  639. VisitChild(exprStatement->mExpression);
  640. }
  641. // void Visit(BfIfStatement* ifStmt) override
  642. // {
  643. // mModule->DoIfStatement(ifStmt,
  644. // mHasAppendAllocVisitor.HasAppendAlloc(ifStmt->mTrueStatement),
  645. // mHasAppendAllocVisitor.HasAppendAlloc(ifStmt->mFalseStatement));
  646. // }
  647. void Visit(BfBlock* block) override
  648. {
  649. if (!mHasAppendAllocVisitor.HasAppendAlloc(block))
  650. return;
  651. int appendAllocIdx = -1;
  652. for (int childIdx = block->mChildArr.mSize - 1; childIdx >= 0; childIdx--)
  653. {
  654. auto child = block->mChildArr.mVals[childIdx];
  655. if (mHasAppendAllocVisitor.HasAppendAlloc(child))
  656. {
  657. for (int emitIdx = 0; emitIdx <= childIdx; emitIdx++)
  658. {
  659. auto emitChild = block->mChildArr.mVals[emitIdx];
  660. mModule->UpdateSrcPos(emitChild);
  661. VisitChild(emitChild);
  662. if ((mFailed) && (!mIsFirstConstPass))
  663. break;
  664. }
  665. break;
  666. }
  667. }
  668. }
  669. };
  670. //////////////////////////////////////////////////////////////////////////
  671. BfModule* gLastCreatedModule = NULL;
  672. BfModule::BfModule(BfContext* context, const StringImpl& moduleName)
  673. {
  674. BfLogSys(context->mSystem, "BfModule::BFModule %p %s\n", this, moduleName.c_str());
  675. gLastCreatedModule = this;
  676. mContext = context;
  677. mModuleName = moduleName;
  678. if (!moduleName.empty())
  679. mContext->mUsedModuleNames.Add(ToUpper(moduleName));
  680. mAddedToCount = false;
  681. mParentModule = NULL;
  682. mNextAltModule = NULL;
  683. mBfIRBuilder = NULL;
  684. mWantsIRIgnoreWrites = false;
  685. mModuleOptions = NULL;
  686. mLastUsedRevision = -1;
  687. mUsedSlotCount = -1;
  688. mIsReified = true;
  689. mReifyQueued = false;
  690. mIsSpecialModule = false;
  691. mIsScratchModule = false;
  692. mIsSpecializedMethodModuleRoot = false; // There may be mNextAltModules extending from this
  693. mHadBuildError = false;
  694. mHadBuildWarning = false;
  695. mIgnoreErrors = false;
  696. mIgnoreWarnings = false;
  697. mHadIgnoredError = false;
  698. mReportErrors = true;
  699. mIsInsideAutoComplete = false;
  700. mIsDeleting = false;
  701. mSkipInnerLookup = false;
  702. mIsHotModule = false;
  703. mSetIllegalSrcPosition = false;
  704. mNoResolveGenericParams = false;
  705. mWroteToLib = false;
  706. mContext = context;
  707. mCompiler = context->mCompiler;
  708. mSystem = mCompiler->mSystem;
  709. mProject = NULL;
  710. mCurMethodState = NULL;
  711. mAttributeState = NULL;
  712. mCurLocalMethodId = 0;
  713. mParentNodeEntry = NULL;
  714. mRevision = -1;
  715. mRebuildIdx = 0;
  716. mLastModuleWrittenRevision = 0;
  717. mIsModuleMutable = false;
  718. mExtensionCount = 0;
  719. mIncompleteMethodCount = 0;
  720. mOnDemandMethodCount = 0;
  721. mHasGenericMethods = false;
  722. mCurMethodInstance = NULL;
  723. mCurTypeInstance = NULL;
  724. mAwaitingInitFinish = false;
  725. mAwaitingFinish = false;
  726. mHasFullDebugInfo = false;
  727. mHadHotObjectWrites = false;
  728. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  729. mBuiltInFuncs[i] = BfIRFunction();
  730. BfLogSysM("Creating module %p: %s Reified: %d ResolveOnly: %d\n", this, mModuleName.c_str(), mIsReified, mCompiler->mIsResolveOnly);
  731. }
  732. void BfReportMemory();
  733. BfModule::~BfModule()
  734. {
  735. BfLogSysM("Deleting module %p: %s \n", this, mModuleName.c_str());
  736. if (!mIsDeleting)
  737. RemoveModuleData();
  738. }
  739. void BfModule::RemoveModuleData()
  740. {
  741. BF_ASSERT(!mIsDeleting);
  742. if (!mModuleName.empty())
  743. {
  744. // Note: module names not necessarily unique
  745. mContext->mUsedModuleNames.Remove(ToUpper(mModuleName));
  746. }
  747. CleanupFileInstances();
  748. delete mBfIRBuilder;
  749. mBfIRBuilder = NULL;
  750. //delete mCpu;
  751. for (auto prevModule : mPrevIRBuilders)
  752. delete prevModule;
  753. mPrevIRBuilders.Clear();
  754. for (auto& pairVal : mDeferredMethodCallData)
  755. delete pairVal.mValue;
  756. mDeferredMethodCallData.Clear();
  757. mDeferredMethodIds.Clear();
  758. for (auto& specModulePair : mSpecializedMethodModules)
  759. delete specModulePair.mValue;
  760. mSpecializedMethodModules.Clear();
  761. if (mNextAltModule != NULL)
  762. delete mNextAltModule;
  763. mNextAltModule = NULL;
  764. if (mModuleOptions != NULL)
  765. delete mModuleOptions;
  766. mModuleOptions = NULL;
  767. BfReportMemory();
  768. }
  769. void BfModule::Init(bool isFullRebuild)
  770. {
  771. mContext->mFinishedModuleWorkList.Remove(this);
  772. if ((mCompiler->mIsResolveOnly) && (this != mContext->mUnreifiedModule))
  773. BF_ASSERT(mIsReified);
  774. if (!mIsScratchModule)
  775. {
  776. mCompiler->mStats.mModulesStarted++;
  777. if (mIsReified)
  778. mCompiler->mStats.mReifiedModuleCount++;
  779. mAddedToCount = true;
  780. }
  781. mIsHotModule = (mProject != NULL) && (mCompiler->mOptions.mHotProject != NULL) && (mCompiler->mOptions.mHotProject->ContainsReference(mProject));
  782. mFuncReferences.Clear();
  783. mClassVDataRefs.Clear();
  784. mClassVDataExtRefs.Clear();
  785. //mTypeDataRefs.Clear();
  786. mDbgRawAllocDataRefs.Clear();
  787. CleanupFileInstances();
  788. mStaticFieldRefs.Clear();
  789. //mInterfaceSlotRefs.Clear();
  790. // If we are just doing an extension then the ownede types aren't rebuilt.
  791. // If we set mRevision then QueueMethodSpecializations wouldn't actually queue up required specializations
  792. // and we'd end up with link errors if the original module uniquely referred to any generic methods
  793. if (isFullRebuild)
  794. mRevision = mCompiler->mRevision;
  795. BF_ASSERT(mCurTypeInstance == NULL);
  796. mIsModuleMutable = true;
  797. BF_ASSERT((mBfIRBuilder == NULL) || (mCompiler->mIsResolveOnly));
  798. #ifdef _DEBUG
  799. EnsureIRBuilder(mCompiler->mLastAutocompleteModule == this);
  800. #else
  801. EnsureIRBuilder(false);
  802. #endif
  803. mCurMethodState = NULL;
  804. mAwaitingInitFinish = true;
  805. mOnDemandMethodCount = 0;
  806. mAwaitingFinish = false;
  807. mHasForceLinkMarker = false;
  808. mUsedSlotCount = -1;
  809. }
  810. bool BfModule::WantsFinishModule()
  811. {
  812. return (mIncompleteMethodCount == 0) && (mOnDemandMethodCount == 0) && (!mHasGenericMethods) && (!mIsScratchModule) && (mExtensionCount == 0) && (mParentModule == NULL);
  813. }
  814. void BfModule::FinishInit()
  815. {
  816. BF_ASSERT(mAwaitingInitFinish);
  817. auto moduleOptions = GetModuleOptions();
  818. mBfIRBuilder->Start(mModuleName, mCompiler->mSystem->mPtrSize, IsOptimized());
  819. #ifdef BF_PLATFORM_WINDOWS
  820. if (mCompiler->mOptions.mToolsetType == BfToolsetType_GNU)
  821. {
  822. if (mCompiler->mOptions.mMachineType == BfMachineType_x86)
  823. mBfIRBuilder->Module_SetTargetTriple("i686-pc-windows-gnu");
  824. else
  825. mBfIRBuilder->Module_SetTargetTriple("x86_64-pc-windows-gnu");
  826. }
  827. else //if (mCompiler->mOptions.mToolsetType == BfToolsetType_Microsoft)
  828. {
  829. if (mCompiler->mOptions.mMachineType == BfMachineType_x86)
  830. mBfIRBuilder->Module_SetTargetTriple("i686-pc-windows-msvc");
  831. else
  832. mBfIRBuilder->Module_SetTargetTriple("x86_64-pc-windows-msvc");
  833. }
  834. #elif defined BF_PLATFORM_LINUX
  835. if (mCompiler->mOptions.mMachineType == BfMachineType_x86)
  836. mBfIRBuilder->Module_SetTargetTriple("i686-unknown-linux-gnu");
  837. else
  838. mBfIRBuilder->Module_SetTargetTriple("x86_64-unknown-linux-gnu");
  839. #else
  840. // Leave it default
  841. mBfIRBuilder->Module_SetTargetTriple("");
  842. #endif
  843. mBfIRBuilder->SetBackend(IsTargetingBeefBackend());
  844. if (moduleOptions.mOptLevel == BfOptLevel_OgPlus)
  845. {
  846. // Og+ requires debug info
  847. moduleOptions.mEmitDebugInfo = 1;
  848. }
  849. mHasFullDebugInfo = moduleOptions.mEmitDebugInfo == 1;
  850. // We need to create DIBuilder for mIsSpecialModule so we have it around when we need it
  851. // if ((!mCompiler->mIsResolveOnly) && ((mIsScratchModule) || (moduleOptions.mEmitDebugInfo != 0)))
  852. // {
  853. // BF_ASSERT((!mBfIRBuilder->mIgnoreWrites) || (mIsScratchModule) || (!mIsReified));
  854. // mBfIRBuilder->DbgInit();
  855. // }
  856. // else
  857. // mHasFullDebugInfo = false;
  858. if ((!mCompiler->mIsResolveOnly) && (!mIsScratchModule) && (moduleOptions.mEmitDebugInfo != 0) && (mIsReified))
  859. {
  860. mBfIRBuilder->DbgInit();
  861. }
  862. else
  863. mHasFullDebugInfo = false;
  864. if ((mBfIRBuilder->DbgHasInfo()) && (mModuleName != "") &&
  865. ((moduleOptions.mEmitDebugInfo != 0)))
  866. {
  867. if (mCompiler->mOptions.IsCodeView())
  868. {
  869. mBfIRBuilder->Module_AddModuleFlag("CodeView", 1);
  870. }
  871. else
  872. {
  873. mBfIRBuilder->Module_AddModuleFlag("Dwarf Version", 4);
  874. }
  875. mBfIRBuilder->Module_AddModuleFlag("Debug Info Version", 3);
  876. mDICompileUnit = mBfIRBuilder->DbgCreateCompileUnit(llvm::dwarf::DW_LANG_C_plus_plus, mModuleName, ".", "Beef Compiler 0.42", /*moduleOptions.mOptLevel > 0*/false, "", 0, !mHasFullDebugInfo);
  877. }
  878. mAwaitingInitFinish = false;
  879. }
  880. void BfModule::ReifyModule()
  881. {
  882. BF_ASSERT((mCompiler->mCompileState != BfCompiler::CompileState_Unreified) && (mCompiler->mCompileState != BfCompiler::CompileState_VData));
  883. BfLogSysM("ReifyModule %@ %s\n", this, mModuleName.c_str());
  884. BF_ASSERT((this != mContext->mScratchModule) && (this != mContext->mUnreifiedModule));
  885. mIsReified = true;
  886. mReifyQueued = false;
  887. StartNewRevision(RebuildKind_SkipOnDemandTypes, true);
  888. mCompiler->mStats.mModulesReified++;
  889. }
  890. void BfModule::UnreifyModule()
  891. {
  892. BfLogSysM("UnreifyModule %p %s\n", this, mModuleName.c_str());
  893. BF_ASSERT((this != mContext->mScratchModule) && (this != mContext->mUnreifiedModule));
  894. mIsReified = false;
  895. mReifyQueued = false;
  896. StartNewRevision(RebuildKind_None, true);
  897. mCompiler->mStats.mModulesUnreified++;
  898. }
  899. void BfModule::CleanupFileInstances()
  900. {
  901. for (auto& itr : mNamedFileInstanceMap)
  902. {
  903. BfLogSysM("FileInstance deleted: %p\n", itr.mValue);
  904. delete itr.mValue;
  905. }
  906. mCurFilePosition.mFileInstance = NULL;//
  907. mFileInstanceMap.Clear();
  908. mNamedFileInstanceMap.Clear();
  909. }
  910. void BfModule::Cleanup()
  911. {
  912. CleanupFileInstances();
  913. }
  914. void BfModule::PrepareForIRWriting(BfTypeInstance* typeInst)
  915. {
  916. if (HasCompiledOutput())
  917. {
  918. // It's possible that the target's code hasn't changed but we're requesting a new generic method specialization
  919. if ((!mIsModuleMutable) && (!typeInst->IsUnspecializedType()) && (!typeInst->mResolvingVarField))
  920. {
  921. StartExtension();
  922. }
  923. }
  924. else
  925. {
  926. EnsureIRBuilder();
  927. }
  928. }
  929. void BfModule::EnsureIRBuilder(bool dbgVerifyCodeGen)
  930. {
  931. BF_ASSERT(!mIsDeleting);
  932. if (mBfIRBuilder == NULL)
  933. {
  934. if ((!mIsScratchModule) && (!mAddedToCount))
  935. {
  936. mCompiler->mStats.mModulesStarted++;
  937. mAddedToCount = true;
  938. }
  939. BF_ASSERT(mStaticFieldRefs.GetCount() == 0);
  940. /*if (mCompiler->mIsResolveOnly)
  941. BF_ASSERT(mIsResolveOnly);*/
  942. mBfIRBuilder = new BfIRBuilder(this);
  943. BfLogSysM("Created mBfIRBuilder %p in %p %s Reified: %d\n", mBfIRBuilder, this, mModuleName.c_str(), mIsReified);
  944. if (mIsScratchModule)
  945. {
  946. mBfIRBuilder->mIgnoreWrites = true;
  947. BF_ASSERT(!dbgVerifyCodeGen);
  948. }
  949. #ifdef _DEBUG
  950. if (mCompiler->mIsResolveOnly)
  951. {
  952. // For "deep" verification testing
  953. /*if (!mIsSpecialModule)
  954. dbgVerifyCodeGen = true;*/
  955. // We only want to turn this off on smaller builds for testing
  956. mBfIRBuilder->mIgnoreWrites = true;
  957. if (dbgVerifyCodeGen)
  958. mBfIRBuilder->mIgnoreWrites = false;
  959. if (!mBfIRBuilder->mIgnoreWrites)
  960. {
  961. // The only purpose of not ignoring writes is so we can verify the codegen one instruction at a time
  962. mBfIRBuilder->mDbgVerifyCodeGen = true;
  963. }
  964. }
  965. else if (!mIsReified)
  966. {
  967. mBfIRBuilder->mIgnoreWrites = true;
  968. }
  969. else
  970. {
  971. // We almost always want this to be 'false' unless we need need to be able to inspect the generated LLVM
  972. // code as we walk the AST
  973. //mBfIRBuilder->mDbgVerifyCodeGen = true;
  974. if (
  975. (mModuleName == "Program")
  976. //|| (mModuleName == "System_Internal")
  977. //|| (mModuleName == "vdata")
  978. //|| (mModuleName == "Hey_Dude_Bro_TestClass")
  979. )
  980. mBfIRBuilder->mDbgVerifyCodeGen = true;
  981. // Just for testing!
  982. //mBfIRBuilder->mIgnoreWrites = true;
  983. }
  984. #else
  985. if (mCompiler->mIsResolveOnly)
  986. {
  987. // Always ignore writes in resolveOnly for release builds
  988. mBfIRBuilder->mIgnoreWrites = true;
  989. }
  990. else
  991. {
  992. // Just for memory testing! This breaks everything.
  993. //mBfIRBuilder->mIgnoreWrites = true;
  994. // For "deep" verification testing
  995. //mBfIRBuilder->mDbgVerifyCodeGen = true;
  996. }
  997. #endif
  998. mWantsIRIgnoreWrites = mBfIRBuilder->mIgnoreWrites;
  999. }
  1000. }
  1001. BfIRValue BfModule::CreateForceLinkMarker(BfModule* module, String* outName)
  1002. {
  1003. String name = "FORCELINKMOD_" + module->mModuleName;
  1004. if (outName != NULL)
  1005. *outName = name;
  1006. auto markerType = GetPrimitiveType(BfTypeCode_Int8);
  1007. return mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(markerType), true, BfIRLinkageType_External, (module == this) ? mBfIRBuilder->CreateConst(BfTypeCode_Int8, 0) : BfIRValue(), name);
  1008. }
  1009. void BfModule::StartNewRevision(RebuildKind rebuildKind, bool force)
  1010. {
  1011. BP_ZONE("BfModule::StartNewRevision");
  1012. // The project MAY be deleted because disabling a project can cause types to be deleted which
  1013. // causes other types rebuild BEFORE they get deleted, which is okay (though wasteful)
  1014. //BF_ASSERT((mProject == NULL) || (!mProject->mDisabled));
  1015. // Already on new revision?
  1016. if ((mRevision == mCompiler->mRevision) && (!force))
  1017. return;
  1018. mHadBuildError = false;
  1019. mHadBuildWarning = false;
  1020. mExtensionCount = 0;
  1021. mRevision = mCompiler->mRevision;
  1022. mRebuildIdx++;
  1023. ClearModuleData();
  1024. // Clear this here, not in ClearModuleData, so we preserve those references even after writing out module
  1025. if (rebuildKind != BfModule::RebuildKind_None) // Leave string pool refs for when we need to use things like [LinkName("")] methods bofore re-reification
  1026. mStringPoolRefs.Clear();
  1027. mDllImportEntries.Clear();
  1028. mImportFileNames.Clear();
  1029. for (auto& pairVal : mDeferredMethodCallData)
  1030. delete pairVal.mValue;
  1031. mDeferredMethodCallData.Clear();
  1032. mDeferredMethodIds.Clear();
  1033. mModuleRefs.Clear();
  1034. mOutFileNames.Clear();
  1035. mTypeDataRefs.Clear();
  1036. mInterfaceSlotRefs.Clear();
  1037. if (rebuildKind == BfModule::RebuildKind_None)
  1038. {
  1039. for (auto& specPair : mSpecializedMethodModules)
  1040. {
  1041. auto specModule = specPair.mValue;
  1042. if (specModule->mIsReified != mIsReified)
  1043. {
  1044. if (mIsReified)
  1045. specModule->ReifyModule();
  1046. else
  1047. specModule->UnreifyModule();
  1048. }
  1049. }
  1050. }
  1051. else
  1052. {
  1053. for (auto& specPair : mSpecializedMethodModules)
  1054. {
  1055. auto specModule = specPair.mValue;
  1056. delete specModule;
  1057. }
  1058. }
  1059. mSpecializedMethodModules.Clear();
  1060. delete mNextAltModule;
  1061. mNextAltModule = NULL;
  1062. BF_ASSERT(mModuleOptions == NULL);
  1063. BfLogSysM("Mod:%p StartNewRevision: %s Revision: %d\n", this, mModuleName.c_str(), mRevision);
  1064. bool needsTypePopulated = false;
  1065. int oldOnDemandCount = 0;
  1066. // We don't have to rebuild types in the unspecialized module because there is no
  1067. // data that's needed -- their method instances are all NULL and the module
  1068. // doesn't get included in the build
  1069. if (this != mContext->mScratchModule)
  1070. {
  1071. for (int typeIdx = 0; typeIdx < (int)mOwnedTypeInstances.size(); typeIdx++)
  1072. {
  1073. auto typeInst = mOwnedTypeInstances[typeIdx];
  1074. if (!typeInst->IsDeleting())
  1075. {
  1076. typeInst->mIsReified = mIsReified;
  1077. if (rebuildKind != BfModule::RebuildKind_None)
  1078. {
  1079. if (typeInst->IsOnDemand())
  1080. {
  1081. // Changing config should require on demand types to be recreated, but reifying a module shouldn't cause the type to be deleted
  1082. if (rebuildKind == BfModule::RebuildKind_All)
  1083. mContext->DeleteType(typeInst);
  1084. else
  1085. {
  1086. RebuildMethods(typeInst);
  1087. }
  1088. }
  1089. else
  1090. mContext->RebuildType(typeInst, false, false, false);
  1091. }
  1092. else
  1093. {
  1094. for (auto& methodGroup : typeInst->mMethodInstanceGroups)
  1095. if ((methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) ||
  1096. (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference))
  1097. {
  1098. oldOnDemandCount++;
  1099. }
  1100. }
  1101. if (typeInst->IsDeleting())
  1102. typeIdx--;
  1103. }
  1104. }
  1105. }
  1106. if (!mIsDeleting)
  1107. Init();
  1108. mOnDemandMethodCount += oldOnDemandCount;
  1109. }
  1110. void BfModule::StartExtension()
  1111. {
  1112. BF_ASSERT(!mIsModuleMutable);
  1113. BfLogSysM("Extension started of module %p\n", this);
  1114. mExtensionCount++;
  1115. if (mBfIRBuilder != NULL)
  1116. mPrevIRBuilders.push_back(mBfIRBuilder);
  1117. mBfIRBuilder = NULL;
  1118. mWantsIRIgnoreWrites = false;
  1119. mFuncReferences.Clear();
  1120. mClassVDataRefs.Clear();
  1121. mClassVDataExtRefs.Clear();
  1122. for (auto& kv : mTypeDataRefs)
  1123. kv.mValue = BfIRValue();
  1124. mDbgRawAllocDataRefs.Clear();
  1125. mStringCharPtrPool.Clear();
  1126. mStringObjectPool.Clear();
  1127. mStaticFieldRefs.Clear();
  1128. for (auto& kv : mInterfaceSlotRefs)
  1129. kv.mValue = BfIRValue();
  1130. mDeferredMethodCallData.Clear();
  1131. mDeferredMethodIds.Clear();
  1132. DisownMethods();
  1133. BfLogSysM("Mod:%p StartExtension: %s\n", this, mModuleName.c_str());
  1134. bool wasAwaitingInitFinish = mAwaitingInitFinish;
  1135. int prevOnDemandMethodCount = mOnDemandMethodCount;
  1136. Init(false);
  1137. if (!wasAwaitingInitFinish)
  1138. FinishInit();
  1139. mOnDemandMethodCount = prevOnDemandMethodCount;
  1140. }
  1141. void BfModule::GetConstClassValueParam(BfIRValue classVData, SizedArrayImpl<BfIRValue>& typeValueParams)
  1142. {
  1143. BfIRValue vDataValue;
  1144. if (mCompiler->mOptions.mObjectHasDebugFlags)
  1145. vDataValue = mBfIRBuilder->CreatePtrToInt(classVData, BfTypeCode_IntPtr);
  1146. else
  1147. vDataValue = mBfIRBuilder->CreateBitCast(classVData, mBfIRBuilder->MapType(mContext->mBfClassVDataPtrType));
  1148. typeValueParams.push_back(vDataValue);
  1149. if (mCompiler->mOptions.mObjectHasDebugFlags)
  1150. {
  1151. auto primType = GetPrimitiveType(BfTypeCode_IntPtr);
  1152. typeValueParams.push_back(GetDefaultValue(primType));
  1153. }
  1154. }
  1155. BfIRValue BfModule::GetConstValue(int64 val)
  1156. {
  1157. return mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)val);
  1158. }
  1159. BfIRValue BfModule::GetConstValue(int64 val, BfType* type)
  1160. {
  1161. BfType* checkType = type;
  1162. if (type->IsTypedPrimitive())
  1163. {
  1164. checkType = type->GetUnderlyingType();
  1165. }
  1166. if (checkType->IsPrimitiveType())
  1167. {
  1168. auto primType = (BfPrimitiveType*)checkType;
  1169. if (checkType->IsFloat())
  1170. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (double)val);
  1171. else
  1172. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (uint64)val);
  1173. }
  1174. return BfIRValue();
  1175. }
  1176. BfIRValue BfModule::GetConstValue8(int val)
  1177. {
  1178. return mBfIRBuilder->CreateConst(BfTypeCode_Int8, (uint64)val);
  1179. }
  1180. BfIRValue BfModule::GetConstValue32(int32 val)
  1181. {
  1182. return mBfIRBuilder->CreateConst(BfTypeCode_Int32, (uint64)val);
  1183. }
  1184. BfIRValue BfModule::GetConstValue64(int64 val)
  1185. {
  1186. return mBfIRBuilder->CreateConst(BfTypeCode_Int64, (uint64)val);
  1187. }
  1188. BfIRValue BfModule::GetDefaultValue(BfType* type)
  1189. {
  1190. PopulateType(type, BfPopulateType_Data);
  1191. mBfIRBuilder->PopulateType(type, BfIRPopulateType_Declaration);
  1192. if (type->IsTypedPrimitive())
  1193. {
  1194. auto underlyingType = type->GetUnderlyingType();
  1195. if (underlyingType == NULL)
  1196. return mBfIRBuilder->CreateConst(BfTypeCode_Int64, 0);
  1197. return GetDefaultValue(type->GetUnderlyingType());
  1198. }
  1199. if (type->IsPointer() || type->IsObjectOrInterface() || type->IsGenericParam() || type->IsVar() || type->IsRef() || type->IsNull() ||
  1200. type->IsRetTypeType() || type->IsConcreteInterfaceType())
  1201. return mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(type));
  1202. if ((type->IsIntegral()) || (type->IsBoolean()))
  1203. {
  1204. auto primType = (BfPrimitiveType*)type;
  1205. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (uint64)0);
  1206. }
  1207. if (type->IsFloat())
  1208. {
  1209. auto primType = (BfPrimitiveType*)type;
  1210. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, 0.0);
  1211. }
  1212. if (type->IsVoid())
  1213. return mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(type));
  1214. return mBfIRBuilder->CreateConstStructZero(mBfIRBuilder->MapType(type));
  1215. }
  1216. BfTypedValue BfModule::GetFakeTypedValue(BfType* type)
  1217. {
  1218. // This is a conservative "IsValueless", since it's not an error to use a fakeVal even if we don't need one
  1219. if (type->mSize == 0)
  1220. return BfTypedValue(BfIRValue(), type);
  1221. else
  1222. return BfTypedValue(mBfIRBuilder->GetFakeVal(), type);
  1223. }
  1224. BfTypedValue BfModule::GetDefaultTypedValue(BfType* type, bool allowRef, BfDefaultValueKind defaultValueKind)
  1225. {
  1226. PopulateType(type, BfPopulateType_Data);
  1227. mBfIRBuilder->PopulateType(type, type->IsValueType() ? BfIRPopulateType_Full : BfIRPopulateType_Declaration);
  1228. if (defaultValueKind == BfDefaultValueKind_Undef)
  1229. {
  1230. auto primType = type->ToPrimitiveType();
  1231. if (primType != NULL)
  1232. {
  1233. return BfTypedValue(mBfIRBuilder->GetUndefConstValue(primType->mTypeDef->mTypeCode), type);
  1234. }
  1235. return BfTypedValue(mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(type)), type);
  1236. }
  1237. BfTypedValue typedValue;
  1238. if ((defaultValueKind != BfDefaultValueKind_Const) && (!type->IsValuelessType()))
  1239. {
  1240. if (type->IsRef())
  1241. {
  1242. BfRefType* refType = (BfRefType*)type;
  1243. BfType* underlyingType = refType->GetUnderlyingType();
  1244. typedValue = BfTypedValue(CreateAlloca(underlyingType), underlyingType, BfTypedValueKind_Addr);
  1245. }
  1246. else
  1247. {
  1248. typedValue = BfTypedValue(CreateAlloca(type), type, BfTypedValueKind_Addr);
  1249. }
  1250. if (!mBfIRBuilder->mIgnoreWrites)
  1251. {
  1252. mBfIRBuilder->CreateMemSet(typedValue.mValue, GetConstValue(0, GetPrimitiveType(BfTypeCode_Int8)),
  1253. GetConstValue(type->mSize), type->mAlign);
  1254. }
  1255. if ((defaultValueKind == BfDefaultValueKind_Value) && (!type->IsRef()))
  1256. typedValue = LoadValue(typedValue);
  1257. return typedValue;
  1258. }
  1259. if ((type->IsRef()) && (!allowRef))
  1260. {
  1261. BfRefType* refType = (BfRefType*)type;
  1262. BfType* underlyingType = refType->GetUnderlyingType();
  1263. if (underlyingType->IsValuelessType())
  1264. typedValue = BfTypedValue(mBfIRBuilder->GetFakeVal(), underlyingType, true);
  1265. else
  1266. typedValue = BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(type)), underlyingType, true);
  1267. }
  1268. else
  1269. {
  1270. typedValue = BfTypedValue(GetDefaultValue(type), type, (defaultValueKind == BfDefaultValueKind_Addr) ? BfTypedValueKind_Addr : BfTypedValueKind_Value);
  1271. }
  1272. return typedValue;
  1273. }
  1274. BfIRValue BfModule::CreateStringCharPtr(const StringImpl& str, int stringId, bool define)
  1275. {
  1276. String stringDataName = StrFormat("__bfStrData%d", stringId);
  1277. BfIRType strCharType;
  1278. //
  1279. {
  1280. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mWantsIRIgnoreWrites);
  1281. strCharType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_Char8), (int)str.length() + 1);
  1282. }
  1283. BfIRValue strConstant;
  1284. if (define)
  1285. {
  1286. strConstant = mBfIRBuilder->CreateConstString(str);
  1287. }
  1288. BfIRValue gv = mBfIRBuilder->CreateGlobalVariable(strCharType,
  1289. true, BfIRLinkageType_External,
  1290. strConstant, stringDataName);
  1291. if (define)
  1292. mBfIRBuilder->GlobalVar_SetUnnamedAddr(gv, true);
  1293. return mBfIRBuilder->CreateInBoundsGEP(gv, 0, 0);
  1294. }
  1295. BfIRValue BfModule::CreateStringObjectValue(const StringImpl& str, int stringId, bool define)
  1296. {
  1297. auto stringTypeInst = ResolveTypeDef(mCompiler->mStringTypeDef, define ? BfPopulateType_Data : BfPopulateType_Declaration)->ToTypeInstance();
  1298. mBfIRBuilder->PopulateType(stringTypeInst);
  1299. auto classVDataGlobal = CreateClassVDataGlobal(stringTypeInst);
  1300. String stringObjName = StrFormat("__bfStrObj%d", stringId);
  1301. BfIRValue stringValData;
  1302. if (define)
  1303. {
  1304. BfIRValue stringCharsVal = CreateStringCharPtr(str, stringId, define);
  1305. mStringCharPtrPool[stringId] = stringCharsVal;
  1306. SizedArray<BfIRValue, 8> typeValueParams;
  1307. GetConstClassValueParam(classVDataGlobal, typeValueParams);
  1308. auto objData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(stringTypeInst->mBaseType, BfIRPopulateType_Full), typeValueParams);
  1309. auto lenByteCount = stringTypeInst->mFieldInstances[0].mResolvedType->mSize;
  1310. typeValueParams.clear();
  1311. typeValueParams.push_back(objData);
  1312. if (lenByteCount == 4)
  1313. {
  1314. typeValueParams.push_back(GetConstValue32((int)str.length())); // mLength
  1315. typeValueParams.push_back(GetConstValue32((int32)(0x40000000 + str.length() + 1))); // mAllocSizeAndFlags
  1316. }
  1317. else
  1318. {
  1319. typeValueParams.push_back(GetConstValue64(str.length())); // mLength
  1320. typeValueParams.push_back(GetConstValue64(0x4000000000000000LL + str.length() + 1)); // mAllocSizeAndFlags
  1321. }
  1322. typeValueParams.push_back(stringCharsVal); // mPtr
  1323. stringValData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(stringTypeInst, BfIRPopulateType_Full), typeValueParams);
  1324. }
  1325. auto stringValLiteral = mBfIRBuilder->CreateGlobalVariable(
  1326. mBfIRBuilder->MapTypeInst(stringTypeInst),
  1327. true,
  1328. BfIRLinkageType_External,
  1329. define ? stringValData : BfIRValue(),
  1330. stringObjName);
  1331. auto stringVal = mBfIRBuilder->CreateBitCast(stringValLiteral, mBfIRBuilder->MapType(stringTypeInst, BfIRPopulateType_Full));
  1332. return stringVal;
  1333. }
  1334. int BfModule::GetStringPoolIdx(BfIRValue constantStr, BfIRConstHolder* constHolder)
  1335. {
  1336. BF_ASSERT(constantStr.IsConst());
  1337. if (constHolder == NULL)
  1338. constHolder = mBfIRBuilder;
  1339. auto constant = constHolder->GetConstant(constantStr);
  1340. if (constant->mTypeCode == BfTypeCode_Int32)
  1341. {
  1342. return constant->mInt32;
  1343. }
  1344. while (constant->mConstType == BfConstType_BitCast)
  1345. {
  1346. auto constBitCast = (BfConstantBitCast*)constant;
  1347. constant = constHolder->GetConstantById(constBitCast->mTarget);
  1348. }
  1349. if (constant->mConstType == BfConstType_GEP32_2)
  1350. {
  1351. auto constGEP = (BfConstantGEP32_2*)constant;
  1352. constant = constHolder->GetConstantById(constGEP->mTarget);
  1353. }
  1354. if (constant->mConstType == BfConstType_GlobalVar)
  1355. {
  1356. auto constGV = (BfGlobalVar*)constant;
  1357. const char* strDataPrefix = "__bfStrData";
  1358. if (strncmp(constGV->mName, strDataPrefix, strlen(strDataPrefix)) == 0)
  1359. return atoi(constGV->mName + strlen(strDataPrefix));
  1360. const char* strObjPrefix = "__bfStrObj";
  1361. if (strncmp(constGV->mName, strObjPrefix, strlen(strObjPrefix)) == 0)
  1362. return atoi(constGV->mName + strlen(strObjPrefix));
  1363. }
  1364. return -1;
  1365. }
  1366. String* BfModule::GetStringPoolString(BfIRValue constantStr, BfIRConstHolder * constHolder)
  1367. {
  1368. int strId = GetStringPoolIdx(constantStr, constHolder);
  1369. if (strId != -1)
  1370. {
  1371. auto& entry = mContext->mStringObjectIdMap[strId];
  1372. return &entry.mString;
  1373. }
  1374. return NULL;
  1375. }
  1376. BfIRValue BfModule::GetStringCharPtr(int stringId)
  1377. {
  1378. BfIRValue* irValue = NULL;
  1379. if (!mStringCharPtrPool.TryAdd(stringId, NULL, &irValue))
  1380. return *irValue;
  1381. // If this wasn't in neither dictionary yet, add to mStringPoolRefs
  1382. if (!mStringObjectPool.ContainsKey(stringId))
  1383. mStringPoolRefs.Add(stringId);
  1384. const StringImpl& str = mContext->mStringObjectIdMap[stringId].mString;
  1385. BfIRValue strCharPtrConst = CreateStringCharPtr(str, stringId, false);
  1386. *irValue = strCharPtrConst;
  1387. return strCharPtrConst;
  1388. }
  1389. BfIRValue BfModule::GetStringCharPtr(BfIRValue strValue)
  1390. {
  1391. if (strValue.IsConst())
  1392. {
  1393. int stringId = GetStringPoolIdx(strValue);
  1394. BF_ASSERT(stringId != -1);
  1395. return GetStringCharPtr(stringId);
  1396. }
  1397. BfIRValue charPtrPtr = mBfIRBuilder->CreateInBoundsGEP(strValue, 0, 1);
  1398. BfIRValue charPtr = mBfIRBuilder->CreateLoad(charPtrPtr);
  1399. return charPtr;
  1400. }
  1401. BfIRValue BfModule::GetStringCharPtr(const StringImpl& str)
  1402. {
  1403. return GetStringCharPtr(GetStringObjectValue(str));
  1404. }
  1405. BfIRValue BfModule::GetStringObjectValue(int strId)
  1406. {
  1407. BfIRValue* objValue;
  1408. if (mStringObjectPool.TryGetValue(strId, &objValue))
  1409. return *objValue;
  1410. auto stringPoolEntry = mContext->mStringObjectIdMap[strId];
  1411. return GetStringObjectValue(stringPoolEntry.mString, true);
  1412. }
  1413. BfIRValue BfModule::GetStringObjectValue(const StringImpl& str, bool define)
  1414. {
  1415. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef, define ? BfPopulateType_Data : BfPopulateType_Declaration);
  1416. mBfIRBuilder->PopulateType(stringType);
  1417. int strId = mContext->GetStringLiteralId(str);
  1418. BfIRValue* irValuePtr = NULL;
  1419. if (!mStringObjectPool.TryAdd(strId, NULL, &irValuePtr))
  1420. return *irValuePtr;
  1421. // If this wasn't in neither dictionary yet, add to mStringPoolRefs
  1422. if (!mStringCharPtrPool.ContainsKey(strId))
  1423. mStringPoolRefs.Add(strId);
  1424. BfIRValue strObject = CreateStringObjectValue(str, strId, define);
  1425. *irValuePtr = strObject;
  1426. mStringPoolRefs.Add(strId);
  1427. return strObject;
  1428. }
  1429. BfIRValue BfModule::CreateGlobalConstValue(const StringImpl& name, BfIRValue constant, BfIRType type, bool external)
  1430. {
  1431. auto newConst = mBfIRBuilder->CreateGlobalVariable(
  1432. type,
  1433. true,
  1434. external ? BfIRLinkageType_External : BfIRLinkageType_Internal,
  1435. constant,
  1436. name.c_str());
  1437. return newConst;
  1438. }
  1439. void BfModule::NewScopeState(bool createLexicalBlock, bool flushValueScope)
  1440. {
  1441. auto curScope = mCurMethodState->mCurScope;
  1442. if (curScope->mLabelNode != NULL)
  1443. curScope->mLabelNode->ToString(curScope->mLabel);
  1444. if (!mCurMethodState->mCurScope->mLabel.IsEmpty())
  1445. {
  1446. auto checkScope = mCurMethodState->mCurScope->mPrevScope;
  1447. while (checkScope != NULL)
  1448. {
  1449. if (checkScope->mLabel == mCurMethodState->mCurScope->mLabel)
  1450. {
  1451. auto errorNode = Fail("Duplicate scope label", curScope->mLabelNode);
  1452. if (errorNode != NULL)
  1453. mCompiler->mPassInstance->MoreInfo("See previous scope label", checkScope->mLabelNode);
  1454. break;
  1455. }
  1456. checkScope = checkScope->mPrevScope;
  1457. }
  1458. }
  1459. auto prevScope = mCurMethodState->mCurScope->mPrevScope;
  1460. if ((flushValueScope) && (prevScope != NULL) && (prevScope->mValueScopeStart))
  1461. {
  1462. if (prevScope->mHadScopeValueRetain)
  1463. mBfIRBuilder->CreateValueScopeSoftEnd(prevScope->mValueScopeStart);
  1464. else
  1465. mBfIRBuilder->CreateValueScopeHardEnd(prevScope->mValueScopeStart);
  1466. }
  1467. mCurMethodState->mBlockNestLevel++;
  1468. if ((createLexicalBlock) && (mBfIRBuilder->DbgHasInfo()) && (mHasFullDebugInfo))
  1469. {
  1470. // DIScope could be NULL if we're in an unspecialized method (for example)
  1471. if (mCurMethodState->mCurScope->mDIScope)
  1472. mCurMethodState->mCurScope->mDIScope = mBfIRBuilder->DbgCreateLexicalBlock(mCurMethodState->mCurScope->mDIScope, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mCurFilePosition.mCurColumn);
  1473. }
  1474. mCurMethodState->mCurScope->mLocalVarStart = (int)mCurMethodState->mLocals.size();
  1475. mCurMethodState->mCurScope->mBlock = mBfIRBuilder->MaybeChainNewBlock((!mCurMethodState->mCurScope->mLabel.empty()) ? mCurMethodState->mCurScope->mLabel : "newScope");
  1476. }
  1477. void BfModule::RestoreScoreState_LocalVariables()
  1478. {
  1479. while (mCurMethodState->mCurScope->mLocalVarStart < (int)mCurMethodState->mLocals.size())
  1480. {
  1481. auto localVar = mCurMethodState->mLocals.back();
  1482. LocalVariableDone(localVar, false);
  1483. mCurMethodState->mLocals.pop_back();
  1484. if (localVar->mShadowedLocal != NULL)
  1485. {
  1486. BfLocalVarEntry* localVarEntryPtr;
  1487. if (mCurMethodState->mLocalVarSet.TryGet(BfLocalVarEntry(localVar), &localVarEntryPtr))
  1488. {
  1489. localVarEntryPtr->mLocalVar = localVar->mShadowedLocal;
  1490. }
  1491. }
  1492. else
  1493. {
  1494. mCurMethodState->mLocalVarSet.Remove(BfLocalVarEntry(localVar));
  1495. }
  1496. delete localVar;
  1497. }
  1498. }
  1499. void BfModule::RestoreScopeState()
  1500. {
  1501. BfScopeData* prevScopeData = mCurMethodState->mCurScope->mPrevScope;
  1502. mCurMethodState->mBlockNestLevel--;
  1503. if (!mCurMethodState->mCurScope->mAtEndBlocks.empty())
  1504. {
  1505. BfIRBlock afterEndBlock;
  1506. if (!mCurMethodState->mLeftBlockUncond)
  1507. {
  1508. afterEndBlock = mBfIRBuilder->CreateBlock("scopeAfterEnd");
  1509. mBfIRBuilder->CreateBr(afterEndBlock);
  1510. mBfIRBuilder->ClearDebugLocation_Last();
  1511. }
  1512. for (auto preExitBlock : mCurMethodState->mCurScope->mAtEndBlocks)
  1513. mBfIRBuilder->MoveBlockToEnd(preExitBlock);
  1514. if (afterEndBlock)
  1515. {
  1516. mBfIRBuilder->AddBlock(afterEndBlock);
  1517. mBfIRBuilder->SetInsertPoint(afterEndBlock);
  1518. }
  1519. }
  1520. if (!mCurMethodState->mLeftBlockUncond)
  1521. EmitDeferredScopeCalls(true, mCurMethodState->mCurScope);
  1522. RestoreScoreState_LocalVariables();
  1523. if (mCurMethodState->mCurScope->mValueScopeStart)
  1524. mBfIRBuilder->CreateValueScopeHardEnd(mCurMethodState->mCurScope->mValueScopeStart);
  1525. mCurMethodState->mCurScope = prevScopeData;
  1526. mCurMethodState->mTailScope = mCurMethodState->mCurScope;
  1527. }
  1528. BfIRValue BfModule::CreateAlloca(BfType* type, bool addLifetime, const char* name, BfIRValue arraySize)
  1529. {
  1530. if (mBfIRBuilder->mIgnoreWrites)
  1531. return mBfIRBuilder->GetFakeVal();
  1532. BF_ASSERT((*(int8*)&addLifetime == 1) || (*(int8*)&addLifetime == 0));
  1533. mBfIRBuilder->PopulateType(type);
  1534. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  1535. if (!mBfIRBuilder->mIgnoreWrites)
  1536. BF_ASSERT(!prevInsertBlock.IsFake());
  1537. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  1538. BfIRValue allocaInst;
  1539. if (arraySize)
  1540. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type), arraySize);
  1541. else
  1542. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type));
  1543. mBfIRBuilder->SetAllocaAlignment(allocaInst, type->mAlign);
  1544. mBfIRBuilder->ClearDebugLocation(allocaInst);
  1545. if (name != NULL)
  1546. mBfIRBuilder->SetName(allocaInst, name);
  1547. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  1548. if ((addLifetime) && (WantsLifetimes()))
  1549. {
  1550. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  1551. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  1552. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  1553. }
  1554. return allocaInst;
  1555. }
  1556. BfIRValue BfModule::CreateAllocaInst(BfTypeInstance* typeInst, bool addLifetime, const char* name)
  1557. {
  1558. if (mBfIRBuilder->mIgnoreWrites)
  1559. return mBfIRBuilder->GetFakeVal();
  1560. BF_ASSERT((*(int8*)&addLifetime == 1) || (*(int8*)&addLifetime == 0));
  1561. mBfIRBuilder->PopulateType(typeInst);
  1562. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  1563. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  1564. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapTypeInst(typeInst));
  1565. mBfIRBuilder->SetAllocaAlignment(allocaInst, typeInst->mInstAlign);
  1566. mBfIRBuilder->ClearDebugLocation(allocaInst);
  1567. if (name != NULL)
  1568. mBfIRBuilder->SetName(allocaInst, name);
  1569. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  1570. if ((addLifetime) && (WantsLifetimes()))
  1571. {
  1572. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  1573. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  1574. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  1575. }
  1576. return allocaInst;
  1577. }
  1578. void BfModule::AddStackAlloc(BfTypedValue val, BfAstNode* refNode, BfScopeData* scopeData, bool condAlloca, bool mayEscape)
  1579. {
  1580. //This was removed because we want the alloc to be added to the __deferred list if it's actually a "stack"
  1581. // 'stack' in a head scopeData is really the same as 'scopeData', so use the simpler scopeData handling
  1582. /*if (mCurMethodState->mInHeadScope)
  1583. isScopeAlloc = true;*/
  1584. if (scopeData == NULL)
  1585. return;
  1586. auto checkBaseType = val.mType->ToTypeInstance();
  1587. if ((checkBaseType != NULL) && (checkBaseType->IsObject()))
  1588. {
  1589. bool hadDtorCall = false;
  1590. while (checkBaseType != NULL)
  1591. {
  1592. if ((checkBaseType->mTypeDef->mDtorDef != NULL) /*&& (checkBaseType != mContext->mBfObjectType)*/)
  1593. {
  1594. bool isDynAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsDyn(scopeData));
  1595. auto dtorMethodInstance = GetMethodInstance(checkBaseType, checkBaseType->mTypeDef->mDtorDef, BfTypeVector());
  1596. BfIRValue useVal = val.mValue;
  1597. useVal = mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapTypeInstPtr(checkBaseType));
  1598. if (isDynAlloc)
  1599. {
  1600. //
  1601. }
  1602. else if (condAlloca)
  1603. {
  1604. BF_ASSERT(!IsTargetingBeefBackend());
  1605. BF_ASSERT(!isDynAlloc);
  1606. auto valPtr = CreateAlloca(checkBaseType);
  1607. mBfIRBuilder->CreateStore(useVal, valPtr);
  1608. useVal = valPtr;
  1609. }
  1610. SizedArray<BfIRValue, 1> llvmArgs;
  1611. llvmArgs.push_back(useVal);
  1612. auto deferredCall = AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1613. if (deferredCall != NULL)
  1614. {
  1615. deferredCall->mCastThis = (val.mType != checkBaseType) && (!isDynAlloc);
  1616. if (condAlloca)
  1617. deferredCall->mArgsNeedLoad = true;
  1618. }
  1619. hadDtorCall = true;
  1620. break;
  1621. }
  1622. checkBaseType = checkBaseType->mBaseType;
  1623. }
  1624. return;
  1625. }
  1626. //TODO: In the future we could be smarter about statically determining that our value hasn't escaped and eliding this
  1627. if (mayEscape)
  1628. {
  1629. // Is this worth it?
  1630. // if ((!IsOptimized()) && (val.mType->IsComposite()) && (!val.mType->IsValuelessType()) && (!mBfIRBuilder->mIgnoreWrites) && (!mCompiler->mIsResolveOnly))
  1631. // {
  1632. // auto nullPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  1633. // bool isDyn = mCurMethodState->mCurScope->IsDyn(scopeData);
  1634. // if (!isDyn)
  1635. // {
  1636. // int clearSize = val.mType->mSize;
  1637. // BfModuleMethodInstance dtorMethodInstance = GetInternalMethod("MemSet");
  1638. // BF_ASSERT(dtorMethodInstance.mMethodInstance != NULL);
  1639. // SizedArray<BfIRValue, 1> llvmArgs;
  1640. // llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(nullPtrType)));
  1641. // llvmArgs.push_back(GetConstValue8(0xDD));
  1642. // llvmArgs.push_back(GetConstValue(clearSize));
  1643. // llvmArgs.push_back(GetConstValue32(val.mType->mAlign));
  1644. // llvmArgs.push_back(mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 0));
  1645. // AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1646. // }
  1647. // else
  1648. // {
  1649. // const char* funcName = "SetDeleted1";
  1650. // if (val.mType->mSize >= 16)
  1651. // funcName = "SetDeleted16";
  1652. // else if (val.mType->mSize >= 8)
  1653. // funcName = "SetDeleted8";
  1654. // else if (val.mType->mSize >= 4)
  1655. // funcName = "SetDeleted4";
  1656. //
  1657. // BfModuleMethodInstance dtorMethodInstance = GetInternalMethod(funcName);
  1658. // BF_ASSERT(dtorMethodInstance.mMethodInstance != NULL);
  1659. // SizedArray<BfIRValue, 1> llvmArgs;
  1660. // llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(nullPtrType)));
  1661. // AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1662. // }
  1663. // }
  1664. }
  1665. }
  1666. bool BfModule::TryLocalVariableInit(BfLocalVariable* localVar)
  1667. {
  1668. auto startTypeInstance = localVar->mResolvedType->ToTypeInstance();
  1669. if ((startTypeInstance == NULL) || (!startTypeInstance->IsStruct()))
  1670. return false;
  1671. auto checkTypeInstance = startTypeInstance;
  1672. while (checkTypeInstance != NULL)
  1673. {
  1674. for (auto& fieldInstance : checkTypeInstance->mFieldInstances)
  1675. {
  1676. if (fieldInstance.mMergedDataIdx != -1)
  1677. {
  1678. int64 checkMask = (int64)1 << fieldInstance.mMergedDataIdx;
  1679. if ((localVar->mUnassignedFieldFlags & checkMask) != 0)
  1680. {
  1681. // For fields added in extensions, we automatically initialize those if necessary
  1682. auto fieldDef = fieldInstance.GetFieldDef();
  1683. if (!fieldDef->mDeclaringType->IsExtension())
  1684. return false;
  1685. if ((fieldInstance.mDataIdx != -1) && (!mBfIRBuilder->mIgnoreWrites) && (!mCompiler->mIsResolveOnly))
  1686. {
  1687. auto curInsertBlock = mBfIRBuilder->GetInsertBlock();
  1688. mBfIRBuilder->SaveDebugLocation();
  1689. if (localVar->IsParam())
  1690. mBfIRBuilder->SetInsertPointAtStart(mCurMethodState->mIRInitBlock);
  1691. else
  1692. {
  1693. BF_ASSERT(localVar->mDeclBlock);
  1694. mBfIRBuilder->SetInsertPointAtStart(localVar->mDeclBlock);
  1695. }
  1696. mBfIRBuilder->ClearDebugLocation();
  1697. BfIRValue curVal;
  1698. if (localVar->mIsThis)
  1699. curVal = mBfIRBuilder->GetArgument(0);
  1700. else
  1701. curVal = localVar->mAddr;
  1702. auto subTypeInstance = startTypeInstance;
  1703. while (subTypeInstance != checkTypeInstance)
  1704. {
  1705. curVal = mBfIRBuilder->CreateInBoundsGEP(curVal, 0, 0);
  1706. subTypeInstance = subTypeInstance->mBaseType;
  1707. }
  1708. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(curVal, 0, fieldInstance.mDataIdx);
  1709. auto defVal = GetDefaultValue(fieldInstance.mResolvedType);
  1710. auto storeInst = mBfIRBuilder->CreateStore(defVal, fieldPtr);
  1711. mBfIRBuilder->SetInsertPoint(curInsertBlock);
  1712. mBfIRBuilder->RestoreDebugLocation();
  1713. }
  1714. localVar->mUnassignedFieldFlags &= ~checkMask;
  1715. if (localVar->mUnassignedFieldFlags == 0)
  1716. localVar->mIsAssigned = true;
  1717. }
  1718. }
  1719. }
  1720. checkTypeInstance = checkTypeInstance->mBaseType;
  1721. }
  1722. return localVar->mIsAssigned;
  1723. }
  1724. void BfModule::LocalVariableDone(BfLocalVariable* localVar, bool isMethodExit)
  1725. {
  1726. //if (localVar->mAddr == NULL)
  1727. /*if ((localVar->mValue) && (!localVar->mAddr) && (IsTargetingBeefBackend()))
  1728. {
  1729. if ((!localVar->mValue.IsConst()) && (!localVar->mValue.IsArg()) && (!localVar->mValue.IsFake()))
  1730. {
  1731. if (mCurMethodInstance->mMethodDef->mName == "FuncA")
  1732. mBfIRBuilder->CreateLifetimeEnd(localVar->mValue);
  1733. }
  1734. }*/
  1735. BfAstNode* localNameNode = localVar->mNameNode;
  1736. if (localVar->mIsThis)
  1737. {
  1738. localNameNode = mCurMethodInstance->mMethodDef->GetRefNode();
  1739. }
  1740. if (localNameNode != NULL)
  1741. {
  1742. bool isOut = false;
  1743. if (localVar->mResolvedType->IsRef())
  1744. {
  1745. auto refType = (BfRefType*)localVar->mResolvedType;
  1746. isOut = refType->mRefKind == BfRefType::RefKind_Out;
  1747. }
  1748. if ((localVar->mReadFromId == -1) || (isOut) || ((localVar->mIsThis) && (mCurTypeInstance->IsStruct())))
  1749. {
  1750. if ((!localVar->mIsAssigned) & (localVar->IsParam()))
  1751. TryLocalVariableInit(localVar);
  1752. // We may skip processing of local methods, so we won't know if it bind to any of our local variables or not
  1753. bool deferFullAnalysis = mCurMethodState->GetRootMethodState()->mLocalMethodCache.size() != 0;
  1754. //bool deferFullAnalysis = true;
  1755. bool deferUsageWarning = deferFullAnalysis && mCompiler->IsAutocomplete();
  1756. if (!localVar->mIsAssigned)
  1757. {
  1758. if (deferUsageWarning)
  1759. {
  1760. // Ignore
  1761. }
  1762. else if (localVar->mIsThis)
  1763. {
  1764. bool foundFields = false;
  1765. auto checkTypeInstance = mCurTypeInstance;
  1766. while (checkTypeInstance != NULL)
  1767. {
  1768. for (auto& fieldInstance : checkTypeInstance->mFieldInstances)
  1769. {
  1770. if (fieldInstance.mMergedDataIdx != -1)
  1771. {
  1772. int checkMask = 1 << fieldInstance.mMergedDataIdx;
  1773. if ((localVar->mUnassignedFieldFlags & checkMask) != 0)
  1774. {
  1775. auto fieldDef = fieldInstance.GetFieldDef();
  1776. if (fieldDef->mProtection != BfProtection_Hidden)
  1777. {
  1778. if (checkTypeInstance == mCurTypeInstance)
  1779. {
  1780. Fail(StrFormat("Field '%s' must be fully assigned before control is returned to the caller",
  1781. fieldDef->mName.c_str()), localNameNode, deferFullAnalysis); // 0171
  1782. }
  1783. else
  1784. {
  1785. Fail(StrFormat("Field '%s.%s' must be fully assigned before control is returned to the caller",
  1786. TypeToString(checkTypeInstance).c_str(),
  1787. fieldDef->mName.c_str()), localNameNode, deferFullAnalysis); // 0171
  1788. }
  1789. }
  1790. foundFields = true;
  1791. }
  1792. }
  1793. }
  1794. checkTypeInstance = checkTypeInstance->mBaseType;
  1795. }
  1796. if (!foundFields)
  1797. {
  1798. if (mCurTypeInstance->mInstSize > 0)
  1799. Fail(StrFormat("The variable '%s' must be fully assigned to before control leaves the current method", localVar->mName.c_str()), localNameNode); // 0177
  1800. }
  1801. }
  1802. else if (localVar->IsParam())
  1803. Fail(StrFormat("The out parameter '%s' must be assigned to before control leaves the current method", localVar->mName.c_str()), localNameNode, deferFullAnalysis); // 0177
  1804. else if (!deferUsageWarning)
  1805. Warn(BfWarning_CS0168_VariableDeclaredButNeverUsed, StrFormat("The variable '%s' is declared but never used", localVar->mName.c_str()), localNameNode, deferFullAnalysis);
  1806. }
  1807. else if ((localVar->mReadFromId == -1) && (!localVar->IsParam()) && (!deferUsageWarning))
  1808. Warn(BfWarning_CS0168_VariableDeclaredButNeverUsed, StrFormat("The variable '%s' is assigned but its value is never used", localVar->mName.c_str()), localNameNode, deferFullAnalysis);
  1809. }
  1810. }
  1811. }
  1812. void BfModule::MarkDynStack(BfScopeData* scopeData)
  1813. {
  1814. auto checkScope = mCurMethodState->mCurScope;
  1815. while (true)
  1816. {
  1817. if (checkScope == scopeData)
  1818. break;
  1819. checkScope->mHadOuterDynStack = true;
  1820. checkScope = checkScope->mPrevScope;
  1821. }
  1822. }
  1823. void BfModule::SaveStackState(BfScopeData* scopeData)
  1824. {
  1825. // If we push a value on the stack that needs to survive until the end of scopeData, we need to make sure that no
  1826. // scopes within scopeData restore the stack
  1827. auto checkScope = mCurMethodState->mCurScope;
  1828. while (true)
  1829. {
  1830. if (checkScope == scopeData)
  1831. {
  1832. if ((!checkScope->mSavedStack) && (checkScope->mBlock) && (!checkScope->mIsScopeHead) && (!checkScope->mHadOuterDynStack))
  1833. {
  1834. if (mBfIRBuilder->mHasDebugInfo)
  1835. mBfIRBuilder->SaveDebugLocation();
  1836. auto prevPos = mBfIRBuilder->GetInsertBlock();
  1837. mBfIRBuilder->SetInsertPointAtStart(checkScope->mBlock);
  1838. checkScope->mSavedStack = mBfIRBuilder->CreateStackSave();
  1839. mBfIRBuilder->ClearDebugLocation(checkScope->mSavedStack);
  1840. mBfIRBuilder->SetInsertPoint(prevPos);
  1841. if (mBfIRBuilder->mHasDebugInfo)
  1842. mBfIRBuilder->RestoreDebugLocation();
  1843. }
  1844. break;
  1845. }
  1846. if (checkScope->mSavedStack)
  1847. {
  1848. for (auto usage : checkScope->mSavedStackUses)
  1849. mBfIRBuilder->EraseInstFromParent(usage);
  1850. checkScope->mSavedStackUses.Clear();
  1851. mBfIRBuilder->EraseInstFromParent(checkScope->mSavedStack);
  1852. checkScope->mSavedStack = BfIRValue();
  1853. }
  1854. checkScope = checkScope->mPrevScope;
  1855. }
  1856. }
  1857. BfIRValue BfModule::ValueScopeStart()
  1858. {
  1859. if (IsTargetingBeefBackend())
  1860. return mBfIRBuilder->CreateValueScopeStart();
  1861. return BfIRValue();
  1862. }
  1863. void BfModule::ValueScopeEnd(BfIRValue valueScopeStart)
  1864. {
  1865. if (valueScopeStart)
  1866. mBfIRBuilder->CreateValueScopeHardEnd(valueScopeStart);
  1867. }
  1868. BfFileInstance* BfModule::GetFileFromNode(BfAstNode* astNode)
  1869. {
  1870. auto bfParser = astNode->GetSourceData()->ToParserData();
  1871. if (bfParser == NULL)
  1872. return NULL;
  1873. BfFileInstance** fileInstancePtr = NULL;
  1874. if (!mFileInstanceMap.TryAdd(bfParser, NULL, &fileInstancePtr))
  1875. {
  1876. return *fileInstancePtr;
  1877. }
  1878. else
  1879. {
  1880. // It's possible two parsers have the same file name (ie: mNextRevision)
  1881. BfFileInstance** namedFileInstancePtr = NULL;
  1882. if (!mNamedFileInstanceMap.TryAdd(bfParser->mFileName, NULL, &namedFileInstancePtr))
  1883. {
  1884. auto bfFileInstance = *namedFileInstancePtr;
  1885. *fileInstancePtr = bfFileInstance;
  1886. return bfFileInstance;
  1887. }
  1888. int slashPos = (int)bfParser->mFileName.LastIndexOf(DIR_SEP_CHAR);
  1889. auto bfFileInstance = new BfFileInstance();
  1890. *fileInstancePtr = bfFileInstance;
  1891. *namedFileInstancePtr = bfFileInstance;
  1892. bfFileInstance->mPrevPosition.mFileInstance = bfFileInstance;
  1893. bfFileInstance->mParser = bfParser;
  1894. BfLogSysM("GetFileFromNode new file. Mod: %p FileInstance: %p Parser: %p\n", this, bfFileInstance, bfParser);
  1895. if ((mBfIRBuilder != NULL) && (mBfIRBuilder->DbgHasInfo()))
  1896. {
  1897. String fileName = bfParser->mFileName;
  1898. for (int i = 0; i < (int)fileName.length(); i++)
  1899. {
  1900. if (fileName[i] == DIR_SEP_CHAR_ALT)
  1901. fileName[i] = DIR_SEP_CHAR;
  1902. }
  1903. bfFileInstance->mDIFile = mBfIRBuilder->DbgCreateFile(fileName.Substring(slashPos + 1), fileName.Substring(0, slashPos));
  1904. }
  1905. return bfFileInstance;
  1906. }
  1907. }
  1908. void BfModule::UpdateSrcPos(BfAstNode* astNode, BfSrcPosFlags flags, int debugLocOffset)
  1909. {
  1910. // We set force to true when we MUST get the line position set (for navigation purposes, for example)
  1911. if (((mBfIRBuilder->mIgnoreWrites)) && ((flags & BfSrcPosFlag_Force) == 0))
  1912. return;
  1913. BF_ASSERT((!mAwaitingInitFinish) || (mBfIRBuilder->mIgnoreWrites));
  1914. if (astNode == NULL)
  1915. return;
  1916. auto bfParser = astNode->GetSourceData()->ToParserData();
  1917. if (bfParser == NULL)
  1918. return;
  1919. if ((mCurFilePosition.mFileInstance == NULL) || (mCurFilePosition.mFileInstance->mParser != bfParser))
  1920. {
  1921. if (mCurFilePosition.mFileInstance != NULL)
  1922. {
  1923. BF_ASSERT(mFileInstanceMap.GetCount() != 0);
  1924. mCurFilePosition.mFileInstance->mPrevPosition = mCurFilePosition;
  1925. }
  1926. auto bfFileInstance = GetFileFromNode(astNode);
  1927. if (bfFileInstance->mPrevPosition.mFileInstance != NULL)
  1928. {
  1929. mCurFilePosition = bfFileInstance->mPrevPosition;
  1930. }
  1931. else
  1932. {
  1933. mCurFilePosition.mFileInstance = bfFileInstance;
  1934. mCurFilePosition.mCurLine = 0;
  1935. mCurFilePosition.mCurSrcPos = 0;
  1936. }
  1937. }
  1938. int srcPos = astNode->GetSrcStart() + debugLocOffset;
  1939. BF_ASSERT(srcPos < bfParser->mSrcLength);
  1940. auto* jumpEntry = bfParser->mJumpTable + (srcPos / PARSER_JUMPTABLE_DIVIDE);
  1941. if (jumpEntry->mCharIdx > srcPos)
  1942. jumpEntry--;
  1943. mCurFilePosition.mCurLine = jumpEntry->mLineNum;
  1944. mCurFilePosition.mCurSrcPos = jumpEntry->mCharIdx;
  1945. mCurFilePosition.mCurColumn = 0;
  1946. while (mCurFilePosition.mCurSrcPos < srcPos)
  1947. {
  1948. if (bfParser->mSrc[mCurFilePosition.mCurSrcPos] == '\n')
  1949. {
  1950. mCurFilePosition.mCurLine++;
  1951. mCurFilePosition.mCurColumn = 0;
  1952. }
  1953. else
  1954. {
  1955. mCurFilePosition.mCurColumn++;
  1956. }
  1957. mCurFilePosition.mCurSrcPos++;
  1958. }
  1959. //TODO: if we bail on the "mCurMethodState == NULL" case then we don't get it set during type declarations
  1960. if (((flags & BfSrcPosFlag_NoSetDebugLoc) == 0) && (mBfIRBuilder->DbgHasInfo()) && (mCurMethodState != NULL))
  1961. {
  1962. int column = mCurFilePosition.mCurColumn + 1;
  1963. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend))
  1964. {
  1965. // Set to illegal position
  1966. column = 0;
  1967. }
  1968. if (mSetIllegalSrcPosition)
  1969. column = 0;
  1970. BfIRMDNode useDIScope = mCurMethodState->mCurScope->mDIScope;
  1971. auto wantDIFile = mCurFilePosition.mFileInstance->mDIFile;
  1972. if ((wantDIFile != mCurMethodState->mDIFile) && (mCurMethodState->mDIFile))
  1973. {
  1974. // This is from a different scope...
  1975. if (wantDIFile != mCurMethodState->mCurScope->mAltDIFile)
  1976. {
  1977. mCurMethodState->mCurScope->mAltDIFile = wantDIFile;
  1978. mCurMethodState->mCurScope->mAltDIScope = mBfIRBuilder->DbgCreateLexicalBlock(mCurMethodState->mCurScope->mDIScope, wantDIFile, mCurFilePosition.mCurLine + 1, column);
  1979. }
  1980. if (mCurMethodState->mCurScope->mAltDIScope) // This may not be set if mAltDIFile is set by a mixin
  1981. useDIScope = mCurMethodState->mCurScope->mAltDIScope;
  1982. }
  1983. else
  1984. {
  1985. if (mCurMethodState->mCurScope->mAltDIFile)
  1986. {
  1987. mCurMethodState->mCurScope->mAltDIFile = BfIRMDNode();
  1988. mCurMethodState->mCurScope->mAltDIScope = BfIRMDNode();
  1989. }
  1990. }
  1991. auto inlineAt = mCurMethodState->mCurScope->mDIInlinedAt;
  1992. if (mCurMethodState->mCrossingMixin)
  1993. inlineAt = BfIRMDNode();
  1994. mBfIRBuilder->SetCurrentDebugLocation(mCurFilePosition.mCurLine + 1, column, useDIScope, inlineAt);
  1995. if ((flags & BfSrcPosFlag_Expression) == 0)
  1996. mBfIRBuilder->CreateStatementStart();
  1997. }
  1998. }
  1999. void BfModule::UpdateExprSrcPos(BfAstNode* astNode, BfSrcPosFlags flags)
  2000. {
  2001. // We've turned off expr src pos (for now?)
  2002. //UpdateSrcPos(astNode, (BfSrcPosFlags)(flags | BfSrcPosFlag_Expression));
  2003. }
  2004. void BfModule::UseDefaultSrcPos(BfSrcPosFlags flags, int debugLocOffset)
  2005. {
  2006. UpdateSrcPos(mCompiler->mBfObjectTypeDef->mTypeDeclaration, flags, debugLocOffset);
  2007. }
  2008. void BfModule::SetIllegalSrcPos(BfSrcPosFlags flags)
  2009. {
  2010. if ((mBfIRBuilder->DbgHasInfo()) && (mCurMethodState != NULL))
  2011. {
  2012. if ((mCurMethodState->mCurScope->mDIInlinedAt) && (mCompiler->mOptions.IsCodeView()))
  2013. {
  2014. // Currently, CodeView does not record column positions so we can't use an illegal column position as an "invalid" marker
  2015. mBfIRBuilder->SetCurrentDebugLocation(0, 0, mCurMethodState->mCurScope->mDIScope, mCurMethodState->mCurScope->mDIInlinedAt);
  2016. }
  2017. else
  2018. {
  2019. // Set to whatever it previously was but at column zero, which we will know to be illegal
  2020. mBfIRBuilder->SetCurrentDebugLocation(mCurFilePosition.mCurLine + 1, 0, mCurMethodState->mCurScope->mDIScope, mCurMethodState->mCurScope->mDIInlinedAt);
  2021. }
  2022. if ((flags & BfSrcPosFlag_Expression) == 0)
  2023. mBfIRBuilder->CreateStatementStart();
  2024. }
  2025. }
  2026. void BfModule::SetIllegalExprSrcPos(BfSrcPosFlags flags)
  2027. {
  2028. // We've turned off expr src pos (for now?)
  2029. //SetIllegalSrcPos((BfSrcPosFlags)(flags | BfSrcPosFlag_Expression));
  2030. }
  2031. bool BfModule::CheckProtection(BfProtection protection, bool allowProtected, bool allowPrivate)
  2032. {
  2033. if ((protection == BfProtection_Public) ||
  2034. ((protection == BfProtection_Protected) && (allowProtected)) ||
  2035. ((protection == BfProtection_Private) && (allowPrivate)))
  2036. return true;
  2037. if ((mAttributeState != NULL) && (mAttributeState->mCustomAttributes != NULL) && (mAttributeState->mCustomAttributes->Contains(mCompiler->mFriendAttributeTypeDef)))
  2038. return true;
  2039. return false;
  2040. }
  2041. void BfModule::GetAccessAllowed(BfTypeInstance* checkType, bool &allowProtected, bool &allowPrivate)
  2042. {
  2043. allowPrivate = (checkType == mCurTypeInstance) || (IsInnerType(mCurTypeInstance, checkType));
  2044. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2045. {
  2046. auto mixinOwner = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  2047. allowPrivate |= (checkType == mixinOwner) || (IsInnerType(mixinOwner, checkType));
  2048. }
  2049. allowProtected = allowPrivate;
  2050. }
  2051. bool BfModule::CheckProtection(BfProtectionCheckFlags& flags, BfTypeInstance* memberOwner, BfProtection memberProtection, BfTypeInstance* lookupStartType)
  2052. {
  2053. if (memberProtection == BfProtection_Hidden)
  2054. return false;
  2055. if (memberProtection == BfProtection_Public)
  2056. return true;
  2057. if ((flags & BfProtectionCheckFlag_CheckedPrivate) == 0)
  2058. {
  2059. BfTypeInstance* curCheckType = mCurTypeInstance;
  2060. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2061. {
  2062. auto mixinOwner = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  2063. curCheckType = mixinOwner;
  2064. }
  2065. bool allowPrivate = (memberOwner->mTypeDef == curCheckType->mTypeDef) || (IsInnerType(curCheckType->mTypeDef, memberOwner->mTypeDef));
  2066. if (allowPrivate)
  2067. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_AllowPrivate | BfProtectionCheckFlag_CheckedPrivate);
  2068. else
  2069. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedPrivate);
  2070. }
  2071. if ((flags & BfProtectionCheckFlag_AllowPrivate) != 0)
  2072. return true;
  2073. if (memberProtection == BfProtection_Protected)
  2074. {
  2075. if ((flags & BfProtectionCheckFlag_CheckedProtected) == 0)
  2076. {
  2077. bool allowProtected = false;
  2078. auto memberOwnerTypeDef = memberOwner->mTypeDef;
  2079. auto curCheckType = mCurTypeInstance;
  2080. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2081. {
  2082. auto mixinOwner = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  2083. curCheckType = mixinOwner;
  2084. }
  2085. auto lookupCheckType = lookupStartType;
  2086. while (lookupCheckType->mInheritDepth >= curCheckType->mInheritDepth)
  2087. {
  2088. if (lookupCheckType == curCheckType)
  2089. {
  2090. allowProtected = true;
  2091. break;
  2092. }
  2093. if (lookupCheckType == memberOwner)
  2094. break;
  2095. lookupCheckType = lookupCheckType->mBaseType;
  2096. if (lookupCheckType == NULL)
  2097. break;
  2098. }
  2099. if (!allowProtected)
  2100. {
  2101. // It's possible our outer type is derived from 'memberOwner'
  2102. while (curCheckType->mTypeDef->mNestDepth > 0)
  2103. {
  2104. curCheckType = GetOuterType(curCheckType);
  2105. if (curCheckType == NULL)
  2106. break;
  2107. auto lookupCheckType = lookupStartType;
  2108. while (lookupCheckType->mInheritDepth >= curCheckType->mInheritDepth)
  2109. {
  2110. if (lookupCheckType == curCheckType)
  2111. {
  2112. allowProtected = true;
  2113. break;
  2114. }
  2115. if (lookupCheckType == memberOwner)
  2116. break;
  2117. lookupCheckType = lookupCheckType->mBaseType;
  2118. if (lookupCheckType == NULL)
  2119. break;
  2120. }
  2121. }
  2122. }
  2123. if (allowProtected)
  2124. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedProtected | BfProtectionCheckFlag_AllowProtected);
  2125. else
  2126. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedProtected);
  2127. }
  2128. if ((flags & BfProtectionCheckFlag_AllowProtected) != 0)
  2129. return true;
  2130. }
  2131. if ((mAttributeState != NULL) && (mAttributeState->mCustomAttributes != NULL) && (mAttributeState->mCustomAttributes->Contains(mCompiler->mFriendAttributeTypeDef)))
  2132. return true;
  2133. return false;
  2134. }
  2135. void BfModule::SetElementType(BfAstNode* astNode, BfSourceElementType elementType)
  2136. {
  2137. if ((mCompiler->mResolvePassData != NULL) &&
  2138. (mCompiler->mResolvePassData->mSourceClassifier != NULL) &&
  2139. (astNode->IsFromParser( mCompiler->mResolvePassData->mParser)))
  2140. {
  2141. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(astNode, elementType);
  2142. }
  2143. }
  2144. void BfModule::SetHadVarUsage()
  2145. {
  2146. mHadVarUsage = true;
  2147. mHadBuildError = true;
  2148. }
  2149. BfError* BfModule::Fail(const StringImpl& error, BfAstNode* refNode, bool isPersistent)
  2150. {
  2151. BP_ZONE("BfModule::Fail");
  2152. if (mIgnoreErrors)
  2153. {
  2154. mHadIgnoredError = true;
  2155. return NULL;
  2156. }
  2157. if (!mReportErrors)
  2158. {
  2159. mCompiler->mPassInstance->SilentFail();
  2160. return NULL;
  2161. }
  2162. if (refNode != NULL)
  2163. refNode = BfNodeToNonTemporary(refNode);
  2164. //BF_ASSERT(refNode != NULL);
  2165. if (mCurMethodInstance != NULL)
  2166. mCurMethodInstance->mHasFailed = true;
  2167. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsUnspecializedTypeVariation()))
  2168. return NULL;
  2169. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsUnspecializedVariation))
  2170. return NULL; // Ignore errors on unspecialized variations, they are always dups
  2171. if (!mHadBuildError)
  2172. mHadBuildError = true;
  2173. if (mParentModule != NULL)
  2174. mParentModule->mHadBuildError = true;
  2175. if (mCurTypeInstance != NULL)
  2176. AddFailType(mCurTypeInstance);
  2177. BfLogSysM("BfModule::Fail module %p type %p %s\n", this, mCurTypeInstance, error.c_str());
  2178. String errorString = error;
  2179. bool isWhileSpecializing = false;
  2180. bool isWhileSpecializingMethod = false;
  2181. if ((mIsSpecialModule) && (mModuleName == "vdata"))
  2182. errorString += StrFormat("\n while generating vdata for project '%s'", mProject->mName.c_str());
  2183. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend))
  2184. errorString += StrFormat("\n while generating append size calculating method");
  2185. else if (refNode == NULL)
  2186. {
  2187. if (mCurTypeInstance != NULL)
  2188. errorString += StrFormat("\n while compiling '%s'", TypeToString(mCurTypeInstance, BfTypeNameFlags_None).c_str());
  2189. else if (mProject != NULL)
  2190. errorString += StrFormat("\n while compiling project '%s'", mProject->mName.c_str());
  2191. }
  2192. if ((mCurTypeInstance != NULL) && (mCurMethodState != NULL))
  2193. {
  2194. auto checkMethodState = mCurMethodState;
  2195. while (checkMethodState != NULL)
  2196. {
  2197. auto methodInstance = checkMethodState->mMethodInstance;
  2198. if (methodInstance == NULL)
  2199. {
  2200. checkMethodState = checkMethodState->mPrevMethodState;
  2201. continue;
  2202. }
  2203. // Propogatea the fail all the way to the main method (assuming we're in a local method or lambda)
  2204. methodInstance->mHasFailed = true;
  2205. bool isSpecializedMethod = ((methodInstance != NULL) && (!methodInstance->mIsUnspecialized) && (methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mMethodGenericArguments.size() != 0));
  2206. if (isSpecializedMethod)
  2207. {
  2208. //auto unspecializedMethod = &mCurMethodInstance->mMethodInstanceGroup->mMethodSpecializationMap.begin()->second;
  2209. auto unspecializedMethod = methodInstance->mMethodInstanceGroup->mDefault;
  2210. if (unspecializedMethod->mHasFailed)
  2211. return NULL; // At least SOME error has already been reported
  2212. }
  2213. if (isSpecializedMethod)
  2214. {
  2215. errorString += StrFormat("\n while specializing method '%s'", MethodToString(methodInstance).c_str());
  2216. isWhileSpecializing = true;
  2217. isWhileSpecializingMethod = true;
  2218. }
  2219. else if ((methodInstance != NULL) && (methodInstance->mIsForeignMethodDef))
  2220. {
  2221. errorString += StrFormat("\n while implementing default interface method '%s'", MethodToString(methodInstance).c_str());
  2222. isWhileSpecializing = true;
  2223. isWhileSpecializingMethod = true;
  2224. }
  2225. else if ((mCurTypeInstance->IsGenericTypeInstance()) && (!mCurTypeInstance->IsUnspecializedType()))
  2226. {
  2227. errorString += StrFormat("\n while specializing type '%s'", TypeToString(mCurTypeInstance).c_str());
  2228. isWhileSpecializing = true;
  2229. }
  2230. checkMethodState = checkMethodState->mPrevMethodState;
  2231. }
  2232. // Keep in mind that all method specializations with generic type instances as its method generic params
  2233. // need to be deferred because the specified generic type instance might get deleted at the end of the
  2234. // compilation due to no longer having indirect references removed, and we have to ignore errors from
  2235. // those method specializations if that occurs
  2236. if (isWhileSpecializing)
  2237. {
  2238. BfError* bfError = mCompiler->mPassInstance->DeferFail(errorString, refNode);
  2239. if (bfError != NULL)
  2240. bfError->mIsWhileSpecializing = isWhileSpecializing;
  2241. return bfError;
  2242. }
  2243. }
  2244. if (!mHadBuildError)
  2245. mHadBuildError = true;
  2246. // Check mixins
  2247. {
  2248. auto checkMethodInstance = mCurMethodState;
  2249. while (checkMethodInstance != NULL)
  2250. {
  2251. auto rootMixinState = checkMethodInstance->GetRootMixinState();
  2252. if (rootMixinState != NULL)
  2253. {
  2254. BfError* bfError = mCompiler->mPassInstance->Fail(StrFormat("Failed to inject mixin '%s'", MethodToString(rootMixinState->mMixinMethodInstance).c_str()), rootMixinState->mSource);
  2255. mCompiler->mPassInstance->MoreInfo(errorString, refNode);
  2256. auto mixinState = checkMethodInstance->mMixinState;
  2257. while ((mixinState != NULL) && (mixinState->mPrevMixinState != NULL))
  2258. {
  2259. mCompiler->mPassInstance->MoreInfo(StrFormat("Injected from mixin '%s'", MethodToString(mixinState->mPrevMixinState->mMixinMethodInstance).c_str()), mixinState->mSource);
  2260. mixinState = mixinState->mPrevMixinState;
  2261. }
  2262. return bfError;
  2263. }
  2264. checkMethodInstance = checkMethodInstance->mPrevMethodState;
  2265. }
  2266. }
  2267. BfError* bfError = NULL;
  2268. if (refNode == NULL)
  2269. bfError = mCompiler->mPassInstance->Fail(errorString);
  2270. else
  2271. {
  2272. bfError = mCompiler->mPassInstance->Fail(errorString, refNode);
  2273. }
  2274. if (bfError != NULL)
  2275. {
  2276. bfError->mIsPersistent = isPersistent;
  2277. bfError->mIsWhileSpecializing = isWhileSpecializing;
  2278. if ((mCurMethodState != NULL) && (mCurMethodState->mDeferredCallEmitState != NULL) && (mCurMethodState->mDeferredCallEmitState->mCloseNode != NULL))
  2279. mCompiler->mPassInstance->MoreInfo("Error during deferred statement handling", mCurMethodState->mDeferredCallEmitState->mCloseNode);
  2280. }
  2281. return bfError;
  2282. }
  2283. BfError* BfModule::FailAfter(const StringImpl& error, BfAstNode* refNode)
  2284. {
  2285. if (mIgnoreErrors)
  2286. return NULL;
  2287. if (refNode != NULL)
  2288. refNode = BfNodeToNonTemporary(refNode);
  2289. mHadBuildError = true;
  2290. return mCompiler->mPassInstance->FailAfter(error, refNode);
  2291. }
  2292. BfError* BfModule::Warn(int warningNum, const StringImpl& warning, BfAstNode* refNode, bool isPersistent)
  2293. {
  2294. if (mIgnoreErrors || mIgnoreWarnings)
  2295. return NULL;
  2296. if (!mReportErrors)
  2297. {
  2298. mCompiler->mPassInstance->SilentFail();
  2299. return NULL;
  2300. }
  2301. BfAstNode* unwarnNode = refNode;
  2302. //
  2303. {
  2304. BfParentNodeEntry* parentNodeEntry = mParentNodeEntry;
  2305. while (parentNodeEntry != NULL)
  2306. {
  2307. if (auto block = BfNodeDynCast<BfBlock>(parentNodeEntry->mNode))
  2308. break;
  2309. unwarnNode = parentNodeEntry->mNode;
  2310. parentNodeEntry = parentNodeEntry->mPrev;
  2311. }
  2312. }
  2313. auto parser = unwarnNode->GetSourceData()->ToParserData();
  2314. if ((parser != NULL) && (parser->IsUnwarnedAt(unwarnNode)))
  2315. {
  2316. return NULL;
  2317. }
  2318. // Right now we're only warning on the unspecialized declarations, we may revisit this
  2319. if (mCurMethodInstance != NULL)
  2320. {
  2321. if (mCurMethodInstance->IsSpecializedGenericMethodOrType())
  2322. return NULL;
  2323. if (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend)
  2324. return NULL; // No ctorCalcAppend warnings
  2325. }
  2326. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsSpecializedType()))
  2327. return NULL;
  2328. if (refNode != NULL)
  2329. refNode = BfNodeToNonTemporary(refNode);
  2330. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2331. {
  2332. // We used to bubble up warnings into the mixin injection site, BUT
  2333. // we are now assuming any relevant warnings will be given at the declaration site
  2334. return NULL;
  2335. // AddFailType(mCurTypeInstance);
  2336. //
  2337. // BfError* bfError = mCompiler->mPassInstance->Warn(warningNum, "Warning while injecting mixin", mCurMethodState->mMixinState->GetRoot()->mSource);
  2338. // if (bfError == NULL)
  2339. // return NULL;
  2340. // mHadBuildWarning = true;
  2341. // return mCompiler->mPassInstance->MoreInfo(warning, refNode);
  2342. }
  2343. BfError* bfError = mCompiler->mPassInstance->WarnAt(warningNum, warning, refNode->GetSourceData(), refNode->GetSrcStart(), refNode->GetSrcLength());
  2344. if (bfError != NULL)
  2345. {
  2346. AddFailType(mCurTypeInstance);
  2347. mHadBuildWarning = true;
  2348. bfError->mIsPersistent = isPersistent;
  2349. if ((mCompiler->IsAutocomplete()) && (mCompiler->mResolvePassData->mAutoComplete->CheckFixit((refNode))))
  2350. {
  2351. BfParserData* parser = refNode->GetSourceData()->ToParserData();
  2352. if (parser != NULL)
  2353. {
  2354. int fileLoc = BfFixitFinder::FindLineStartBefore(refNode);
  2355. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("fixit", StrFormat("#unwarn\tunwarn|%s|%d|#unwarn|", parser->mFileName.c_str(), fileLoc).c_str()));
  2356. }
  2357. }
  2358. }
  2359. return bfError;
  2360. }
  2361. void BfModule::CheckRangeError(BfType* type, BfAstNode* refNode)
  2362. {
  2363. if (mBfIRBuilder->mOpFailed)
  2364. Fail(StrFormat("Result out of range for type '%s'", TypeToString(type).c_str()), refNode);
  2365. }
  2366. void BfModule::NotImpl(BfAstNode* astNode)
  2367. {
  2368. Fail("INTERNAL ERROR: Not implemented", astNode);
  2369. }
  2370. bool BfModule::CheckAccessMemberProtection(BfProtection protection, BfType* memberType)
  2371. {
  2372. bool allowPrivate = (memberType == mCurTypeInstance) || (IsInnerType(mCurTypeInstance, memberType));
  2373. if (!allowPrivate)
  2374. allowPrivate |= memberType->IsInterface();
  2375. bool allowProtected = allowPrivate;// allowPrivate || TypeIsSubTypeOf(mCurTypeInstance, memberType->ToTypeInstance());
  2376. if (!CheckProtection(protection, allowProtected, allowPrivate))
  2377. {
  2378. return false;
  2379. }
  2380. return true;
  2381. }
  2382. bool BfModule::CheckDefineMemberProtection(BfProtection protection, BfType* memberType)
  2383. {
  2384. // Use 'min' - exporting a 'public' from a 'private' class is really just 'private' still
  2385. protection = std::min(protection, mCurTypeInstance->mTypeDef->mProtection);
  2386. auto memberTypeInstance = memberType->ToTypeInstance();
  2387. if (memberTypeInstance == NULL)
  2388. {
  2389. auto underlyingType = memberType->GetUnderlyingType();
  2390. if (underlyingType != NULL)
  2391. return CheckDefineMemberProtection(protection, underlyingType);
  2392. return true;
  2393. }
  2394. if (memberTypeInstance->mTypeDef->mProtection < protection)
  2395. return false;
  2396. if (memberTypeInstance->IsGenericTypeInstance())
  2397. {
  2398. // When we're a generic struct, our data layout can depend on our generic parameters as well
  2399. auto genericTypeInstance = (BfGenericTypeInstance*) memberTypeInstance;
  2400. for (auto typeGenericArg : genericTypeInstance->mTypeGenericArguments)
  2401. {
  2402. if (!CheckDefineMemberProtection(protection, typeGenericArg))
  2403. return false;
  2404. }
  2405. }
  2406. return true;
  2407. }
  2408. void BfModule::AddDependency(BfType* usedType, BfType* usingType, BfDependencyMap::DependencyDependencyFlag flags)
  2409. {
  2410. if (usedType == usingType)
  2411. return;
  2412. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsAutocompleteMethod))
  2413. return;
  2414. if (usedType->IsSpecializedByAutoCompleteMethod())
  2415. return;
  2416. if ((mCurMethodState != NULL) && (mCurMethodState->mHotDataReferenceBuilder != NULL) && (usedType != mCurTypeInstance) &&
  2417. ((flags & (BfDependencyMap::DependencyFlag_ReadFields | BfDependencyMap::DependencyFlag_LocalUsage | BfDependencyMap::DependencyFlag_Allocates)) != 0))
  2418. {
  2419. bool addType = true;
  2420. auto checkType = usedType;
  2421. while (true)
  2422. {
  2423. if ((checkType->IsPointer()) || (checkType->IsRef()) || (checkType->IsSizedArray()))
  2424. checkType = checkType->GetUnderlyingType();
  2425. else if (checkType->IsArray())
  2426. {
  2427. checkType = ((BfGenericTypeInstance*)checkType)->mTypeGenericArguments[0];
  2428. }
  2429. else
  2430. break;
  2431. }
  2432. PopulateType(checkType, BfPopulateType_Data);
  2433. if (checkType->IsValuelessType())
  2434. addType = false;
  2435. else if (checkType->IsPrimitiveType())
  2436. addType = false;
  2437. else
  2438. {
  2439. auto checkTypeInst = checkType->ToTypeInstance();
  2440. if (checkTypeInst == NULL)
  2441. {
  2442. addType = false;
  2443. }
  2444. else
  2445. {
  2446. if (TypeIsSubTypeOf(mCurTypeInstance, checkTypeInst))
  2447. addType = false;
  2448. }
  2449. }
  2450. if (addType)
  2451. {
  2452. auto checkTypeInst = checkType->ToTypeInstance();
  2453. auto hotTypeVersion = checkTypeInst->mHotTypeData->GetLatestVersion();
  2454. BF_ASSERT(hotTypeVersion != NULL);
  2455. bool isAllocation = ((flags & BfDependencyMap::DependencyFlag_Allocates) != 0);
  2456. if (((flags & BfDependencyMap::DependencyFlag_LocalUsage) != 0) &&
  2457. (checkType->IsComposite()))
  2458. isAllocation = true;
  2459. if (isAllocation)
  2460. {
  2461. mCurMethodState->mHotDataReferenceBuilder->mAllocatedData.Add(hotTypeVersion);
  2462. }
  2463. else
  2464. mCurMethodState->mHotDataReferenceBuilder->mUsedData.Add(hotTypeVersion);
  2465. }
  2466. }
  2467. //BP_ZONE("BfModule::AddDependency");
  2468. /*if (usedType->IsMethodRef())
  2469. {
  2470. auto methodRefType = (BfMethodRefType*)usedType;
  2471. AddDependency(methodRefType->mMethodRef->GetOwner(), usingType, flags);
  2472. return;
  2473. }*/
  2474. // Why in the world were we doing this?
  2475. // This caused functions to get immediately deleted since they appear to have no references ever....
  2476. // if (usedType->IsFunction())
  2477. // {
  2478. // usedType = ResolveTypeDef(mCompiler->mFunctionTypeDef);
  2479. // }
  2480. if ((!mCompiler->mIsResolveOnly) && (mIsReified))
  2481. {
  2482. auto usingModule = usingType->GetModule();
  2483. BfModule* usedModule;
  2484. if (usedType->IsFunction())
  2485. {
  2486. auto typeInst = usedType->ToTypeInstance();
  2487. if (typeInst->mBaseType == NULL)
  2488. PopulateType(typeInst);
  2489. usedModule = typeInst->mBaseType->GetModule();
  2490. }
  2491. else
  2492. usedModule = usedType->GetModule();
  2493. if ((usingModule != NULL) && (!usingModule->mIsSpecialModule) &&
  2494. (usedModule != NULL) && (!usedModule->mIsSpecialModule))
  2495. {
  2496. usingModule->mModuleRefs.Add(usedModule);
  2497. }
  2498. }
  2499. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodInfoEx != NULL) && (flags != BfDependencyMap::DependencyFlag_MethodGenericArg))
  2500. {
  2501. // When we are specializing a method, usage of that specialized type is already handled with DependencyFlag_MethodGenericArg
  2502. for (auto genericArg : mCurMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  2503. if (genericArg == usedType)
  2504. return;
  2505. }
  2506. auto underlyingType = usedType->GetUnderlyingType();
  2507. if (underlyingType != NULL) // Not really a "GenericArg", but... same purpose.
  2508. AddDependency(underlyingType, usingType, BfDependencyMap::DependencyFlag_GenericArgRef);
  2509. BfDependedType* checkDType = usedType->ToDependedType();
  2510. if (checkDType == NULL)
  2511. return;
  2512. if ((usedType->mRebuildFlags & BfTypeRebuildFlag_AwaitingReference) != 0)
  2513. mContext->MarkAsReferenced(checkDType);
  2514. checkDType->mDependencyMap.AddUsedBy(usingType, flags);
  2515. if (checkDType->IsGenericTypeInstance())
  2516. {
  2517. auto genericTypeInstance = (BfGenericTypeInstance*) checkDType;
  2518. for (auto genericArg : genericTypeInstance->mTypeGenericArguments)
  2519. {
  2520. AddDependency(genericArg, usingType, BfDependencyMap::DependencyFlag_GenericArgRef);
  2521. }
  2522. }
  2523. }
  2524. void BfModule::AddCallDependency(BfMethodInstance* methodInstance, bool devirtualized)
  2525. {
  2526. if ((mCurMethodState != NULL) && (mCurMethodState->mHotDataReferenceBuilder != NULL))
  2527. {
  2528. if (methodInstance->mHotMethod == NULL)
  2529. CheckHotMethod(methodInstance, "");
  2530. BF_ASSERT(methodInstance->mHotMethod != NULL);
  2531. if (devirtualized)
  2532. mCurMethodState->mHotDataReferenceBuilder->mDevirtualizedCalledMethods.Add(methodInstance->mHotMethod);
  2533. else
  2534. mCurMethodState->mHotDataReferenceBuilder->mCalledMethods.Add(methodInstance->mHotMethod);
  2535. }
  2536. }
  2537. bool BfModule::IsAttribute(BfTypeInstance* typeInst)
  2538. {
  2539. auto checkTypeInst = typeInst;
  2540. while (checkTypeInst != NULL)
  2541. {
  2542. if (checkTypeInst->mTypeDef == mCompiler->mAttributeTypeDef)
  2543. return true;
  2544. checkTypeInst = checkTypeInst->mBaseType;
  2545. }
  2546. return false;
  2547. }
  2548. void BfModule::PopulateGlobalContainersList(const BfGlobalLookup& globalLookup)
  2549. {
  2550. if (mContext->mCurTypeState == NULL)
  2551. return;
  2552. BP_ZONE("PopulateGlobalContainersList");
  2553. BfTypeDef* userTypeDef = mContext->mCurTypeState->mCurTypeDef;
  2554. if (userTypeDef == NULL)
  2555. userTypeDef = mCurTypeInstance->mTypeDef;
  2556. if (mContext->mCurTypeState->mGlobalContainerCurUserTypeDef != userTypeDef)
  2557. {
  2558. mContext->mCurTypeState->mGlobalContainers.Clear();
  2559. for (int namespaceIdx = -1; namespaceIdx < (int)userTypeDef->mNamespaceSearch.size(); namespaceIdx++)
  2560. {
  2561. BfAtomComposite findStr;
  2562. if (namespaceIdx != -1)
  2563. findStr.Reference(userTypeDef->mNamespaceSearch[namespaceIdx]);
  2564. auto typeDefItr = mSystem->mTypeDefs.TryGet(findStr);
  2565. while (typeDefItr)
  2566. {
  2567. auto typeDef = *typeDefItr;
  2568. if ((typeDef->mFullName == findStr) && (typeDef->mIsCombinedPartial) && (typeDef->IsGlobalsContainer()))
  2569. {
  2570. if (typeDef->mProject->ContainsReference(typeDef->mProject))
  2571. {
  2572. BfGlobalContainerEntry globalEntry;
  2573. globalEntry.mTypeDef = typeDef;
  2574. globalEntry.mTypeInst = NULL;
  2575. typeDef->PopulateMemberSets();
  2576. mContext->mCurTypeState->mGlobalContainers.Add(globalEntry);
  2577. }
  2578. }
  2579. else if (!typeDef->mIsPartial)
  2580. {
  2581. //break;
  2582. }
  2583. typeDefItr.MoveToNextHashMatch();
  2584. }
  2585. }
  2586. mContext->mCurTypeState->mGlobalContainerCurUserTypeDef = userTypeDef;
  2587. }
  2588. // Only create actual typeInst when we have an applicable member. This helps in keeping unused globals from
  2589. // reifing types
  2590. for (auto& globalEntry : mContext->mCurTypeState->mGlobalContainers)
  2591. {
  2592. if (globalEntry.mTypeInst == NULL)
  2593. {
  2594. bool include = false;
  2595. if (globalLookup.mKind == BfGlobalLookup::Kind_All)
  2596. include = true;
  2597. else if (globalLookup.mKind == BfGlobalLookup::Kind_Field)
  2598. {
  2599. if (globalEntry.mTypeDef->mFieldSet.ContainsWith(globalLookup.mName))
  2600. include = true;
  2601. if (globalEntry.mTypeDef->mPropertySet.ContainsWith(globalLookup.mName))
  2602. include = true;
  2603. }
  2604. else if (globalLookup.mKind == BfGlobalLookup::Kind_Method)
  2605. {
  2606. if (globalEntry.mTypeDef->mMethodSet.ContainsWith(globalLookup.mName))
  2607. include = true;
  2608. }
  2609. if (include)
  2610. {
  2611. auto type = ResolveTypeDef(globalEntry.mTypeDef);
  2612. if (type != NULL)
  2613. globalEntry.mTypeInst = type->ToTypeInstance();
  2614. }
  2615. }
  2616. }
  2617. }
  2618. void PrintUsers(llvm::MDNode* md);
  2619. BfModuleOptions BfModule::GetModuleOptions()
  2620. {
  2621. if (mIsScratchModule)
  2622. return BfModuleOptions();
  2623. if (mModuleOptions != NULL)
  2624. return *mModuleOptions;
  2625. BfModuleOptions moduleOptions;
  2626. moduleOptions.mEmitDebugInfo = mCompiler->mOptions.mEmitDebugInfo ? 1 : mCompiler->mOptions.mEmitLineInfo ? 2 : 0;
  2627. if (mProject != NULL)
  2628. {
  2629. moduleOptions.mSIMDSetting = mProject->mCodeGenOptions.mSIMDSetting;
  2630. moduleOptions.mOptLevel = mProject->mCodeGenOptions.mOptLevel;
  2631. }
  2632. auto headModule = this;
  2633. while (headModule->mParentModule != NULL)
  2634. headModule = headModule->mParentModule;
  2635. BF_ASSERT((headModule->mOwnedTypeInstances.size() > 0) || (mModuleName == "vdata"));
  2636. if (headModule->mOwnedTypeInstances.size() > 0)
  2637. {
  2638. auto typeInst = headModule->mOwnedTypeInstances[0];
  2639. PopulateType(typeInst);
  2640. if (typeInst->mTypeOptionsIdx != -1)
  2641. {
  2642. auto typeOptions = mSystem->GetTypeOptions(typeInst->mTypeOptionsIdx);
  2643. moduleOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)moduleOptions.mSIMDSetting, typeOptions->mSIMDSetting);
  2644. moduleOptions.mEmitDebugInfo = BfTypeOptions::Apply(moduleOptions.mEmitDebugInfo, typeOptions->mEmitDebugInfo);
  2645. moduleOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)moduleOptions.mOptLevel, (int)typeOptions->mOptimizationLevel);
  2646. }
  2647. }
  2648. return moduleOptions;
  2649. }
  2650. BfCheckedKind BfModule::GetDefaultCheckedKind()
  2651. {
  2652. bool runtimeChecks = mCompiler->mOptions.mRuntimeChecks;
  2653. auto typeOptions = GetTypeOptions();
  2654. if (typeOptions != NULL)
  2655. runtimeChecks = BfTypeOptions::Apply(runtimeChecks, typeOptions->mRuntimeChecks);
  2656. return runtimeChecks ? BfCheckedKind_Checked : BfCheckedKind_Unchecked;
  2657. }
  2658. void BfModule::AddFailType(BfTypeInstance* typeInstance)
  2659. {
  2660. mContext->mFailTypes.Add(typeInstance);
  2661. }
  2662. void BfModule::CheckAddFailType()
  2663. {
  2664. //TODO: We removed this line, because failures in resolve-only generic method can occur in non-owning modules
  2665. // but we still need to add the owning type to the FailTypes list
  2666. //.. OLD:
  2667. // While we're inlining, it's possible that mCurTypeInstance belongs to another module, ignore it
  2668. /*if (mCurTypeInstance->mModule != this)
  2669. return;*/
  2670. // Using mHadBuildWarning to insert into mFailTypes is our core of our strategy for reasserting
  2671. // warnings on rebuilds where otherwise the warnings wouldn't be generated because no code was
  2672. // being recompiled. This forces types with warnings to be recompiled.
  2673. // We had this 'mIsResolveOnly' check for speed in resolveOnly, but we removed it so the IDE can be
  2674. // constantly warning-aware
  2675. if ((mHadBuildError) ||
  2676. (mHadBuildWarning /*&& !mCompiler->mIsResolveOnly*/))
  2677. {
  2678. //mContext->mFailTypes.Add(mCurTypeInstance);
  2679. }
  2680. }
  2681. void BfModule::MarkDerivedDirty(BfTypeInstance* typeInst)
  2682. {
  2683. if (!mCompiler->IsHotCompile())
  2684. return;
  2685. typeInst->mDirty = true;
  2686. for (auto& dep : typeInst->mDependencyMap)
  2687. {
  2688. auto depType = dep.mKey;
  2689. auto depFlags = dep.mValue.mFlags;
  2690. if ((depFlags & BfDependencyMap::DependencyFlag_DerivedFrom) != 0)
  2691. {
  2692. MarkDerivedDirty(depType->ToTypeInstance());
  2693. }
  2694. }
  2695. }
  2696. void BfModule::CreateStaticField(BfFieldInstance* fieldInstance, bool isThreadLocal)
  2697. {
  2698. auto fieldType = fieldInstance->GetResolvedType();
  2699. auto field = fieldInstance->GetFieldDef();
  2700. if (fieldType->IsVar())
  2701. return;
  2702. BfIRValue initValue;
  2703. if (field->mIsConst)
  2704. {
  2705. if (fieldType->IsPointer())
  2706. fieldType = fieldType->GetUnderlyingType();
  2707. }
  2708. if (!field->mIsExtern)
  2709. initValue = GetDefaultValue(fieldType);
  2710. if (fieldInstance->mOwner->IsUnspecializedType())
  2711. {
  2712. // Placeholder
  2713. auto ptrVal = CreatePointerType(fieldType);
  2714. mStaticFieldRefs[fieldInstance] = GetDefaultValue(ptrVal);
  2715. }
  2716. else
  2717. {
  2718. BfLogSysM("Creating static field Module:%p Type:%p\n", this, fieldType);
  2719. StringT<128> staticVarName;
  2720. BfMangler::Mangle(staticVarName, mCompiler->GetMangleKind(), fieldInstance);
  2721. if (!fieldType->IsValuelessType())
  2722. {
  2723. BfIRValue globalVar = mBfIRBuilder->CreateGlobalVariable(
  2724. mBfIRBuilder->MapType(fieldType, BfIRPopulateType_Eventually_Full),
  2725. false,
  2726. BfIRLinkageType_External,
  2727. initValue,
  2728. staticVarName,
  2729. isThreadLocal);
  2730. BF_ASSERT(globalVar);
  2731. mStaticFieldRefs[fieldInstance] = globalVar;
  2732. }
  2733. }
  2734. }
  2735. void BfModule::ResolveConstField(BfTypeInstance* typeInstance, BfFieldInstance* fieldInstance, BfFieldDef* fieldDef, bool forceResolve)
  2736. {
  2737. bool autoCompleteOnly = mCompiler->IsAutocomplete();
  2738. BfType* fieldType = NULL;
  2739. if (fieldInstance != NULL)
  2740. {
  2741. fieldType = fieldInstance->GetResolvedType();
  2742. if (fieldType == NULL)
  2743. fieldType = ResolveTypeRef(fieldDef->mTypeRef);
  2744. }
  2745. else
  2746. {
  2747. BF_ASSERT(mCompiler->IsAutocomplete());
  2748. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  2749. if ((typeInstance->IsEnum()) && (fieldDef->mTypeRef == NULL))
  2750. {
  2751. fieldType = typeInstance;
  2752. }
  2753. else
  2754. {
  2755. auto isLet = (fieldDef->mTypeRef != NULL) && (fieldDef->mTypeRef->IsExact<BfLetTypeReference>());
  2756. auto isVar = (fieldDef->mTypeRef != NULL) && (fieldDef->mTypeRef->IsExact<BfVarTypeReference>());
  2757. if (isLet || isVar)
  2758. fieldType = GetPrimitiveType(BfTypeCode_Var);
  2759. else
  2760. fieldType = ResolveTypeRef(fieldDef->mTypeRef);
  2761. if (fieldType == NULL)
  2762. fieldType = mContext->mBfObjectType;
  2763. }
  2764. }
  2765. if ((fieldInstance != NULL) && (fieldInstance->mConstIdx != -1) && (!forceResolve))
  2766. return;
  2767. if (mContext->mFieldResolveReentrys.size() > 1)
  2768. {
  2769. if (mContext->mFieldResolveReentrys.IndexOf(fieldInstance, 1) != -1)
  2770. {
  2771. String failStr = "Circular data reference detected between the following fields:";
  2772. for (int i = 1; i < (int)mContext->mFieldResolveReentrys.size(); i++)
  2773. {
  2774. if (i > 1)
  2775. failStr += ",";
  2776. failStr += "\n '" + TypeToString(typeInstance) + "." + mContext->mFieldResolveReentrys[i]->GetFieldDef()->mName + "'";
  2777. }
  2778. BfError* err = Fail(failStr, fieldDef->mFieldDeclaration);
  2779. if (err)
  2780. err->mIsPersistent = true;
  2781. return;
  2782. }
  2783. }
  2784. mContext->mFieldResolveReentrys.push_back(fieldInstance);
  2785. AutoPopBack<decltype (mContext->mFieldResolveReentrys)> popTypeResolveReentry(&mContext->mFieldResolveReentrys);
  2786. if (fieldInstance == NULL)
  2787. popTypeResolveReentry.Pop();
  2788. auto typeDef = typeInstance->mTypeDef;
  2789. BfIRValue constValue;
  2790. if (fieldDef->mIsExtern)
  2791. {
  2792. if (!fieldDef->mTypeRef->IsA<BfPointerTypeRef>())
  2793. {
  2794. Fail("Extern consts must be pointer types", fieldDef->mFieldDeclaration->mTypeRef);
  2795. }
  2796. if (fieldDef->mInitializer != NULL)
  2797. {
  2798. Fail("Extern consts cannot have initializers", fieldDef->mFieldDeclaration->mNameNode);
  2799. }
  2800. }
  2801. else if (fieldDef->mInitializer == NULL)
  2802. {
  2803. if (fieldDef->IsEnumCaseEntry())
  2804. {
  2805. if (typeInstance->IsTypedPrimitive())
  2806. {
  2807. BfFieldInstance* prevFieldInstance = NULL;
  2808. for (int i = fieldDef->mIdx - 1; i >= 0; i--)
  2809. {
  2810. BfFieldInstance* checkFieldInst = &typeInstance->mFieldInstances[i];
  2811. if (checkFieldInst->GetFieldDef()->IsEnumCaseEntry())
  2812. {
  2813. prevFieldInstance = checkFieldInst;
  2814. break;
  2815. }
  2816. }
  2817. if (prevFieldInstance == NULL)
  2818. constValue = GetConstValue(0, typeInstance);
  2819. else
  2820. {
  2821. ResolveConstField(typeInstance, prevFieldInstance, prevFieldInstance->GetFieldDef());
  2822. if (prevFieldInstance->mConstIdx == -1)
  2823. {
  2824. if (!mCompiler->IsAutocomplete())
  2825. AssertErrorState();
  2826. constValue = GetConstValue(0, typeInstance);
  2827. }
  2828. else
  2829. {
  2830. auto prevConstant = ConstantToCurrent(typeInstance->mConstHolder->GetConstantById(prevFieldInstance->mConstIdx), typeInstance->mConstHolder, typeInstance);
  2831. constValue = mBfIRBuilder->CreateAdd(prevConstant, GetConstValue(1, typeInstance));
  2832. }
  2833. }
  2834. }
  2835. }
  2836. else
  2837. {
  2838. Fail("Const requires initializer", fieldDef->mFieldDeclaration->mNameNode);
  2839. }
  2840. }
  2841. else
  2842. {
  2843. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  2844. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  2845. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL);
  2846. BfConstResolver constResolver(this);
  2847. BfMethodState methodState;
  2848. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  2849. methodState.mTempKind = BfMethodState::TempKind_Static;
  2850. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  2851. if (fieldType->IsVar())
  2852. {
  2853. auto initValue = GetFieldInitializerValue(fieldInstance, fieldDef->mInitializer, fieldDef, fieldType);
  2854. if (!initValue)
  2855. {
  2856. AssertErrorState();
  2857. initValue = GetDefaultTypedValue(mContext->mBfObjectType);
  2858. }
  2859. if (fieldInstance != NULL)
  2860. {
  2861. fieldInstance->mResolvedType = initValue.mType;
  2862. }
  2863. constValue = initValue.mValue;
  2864. }
  2865. else
  2866. {
  2867. auto uncastedInitValue = GetFieldInitializerValue(fieldInstance, fieldDef->mInitializer, fieldDef, fieldType);
  2868. constValue = uncastedInitValue.mValue;
  2869. }
  2870. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  2871. }
  2872. if (fieldInstance != NULL)
  2873. {
  2874. fieldType = fieldInstance->GetResolvedType();
  2875. if ((fieldType == NULL) || (fieldType->IsVar()))
  2876. {
  2877. AssertErrorState();
  2878. // Default const type is 'int'
  2879. BfTypedValue initValue = GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr));
  2880. if (fieldInstance != NULL)
  2881. {
  2882. fieldInstance->mResolvedType = initValue.mType;
  2883. }
  2884. constValue = initValue.mValue;
  2885. }
  2886. if ((constValue) && (fieldInstance->mConstIdx == -1))
  2887. {
  2888. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  2889. CurrentAddToConstHolder(constValue);
  2890. fieldInstance->mConstIdx = constValue.mId;
  2891. }
  2892. }
  2893. }
  2894. BfType* BfModule::ResolveVarFieldType(BfTypeInstance* typeInstance, BfFieldInstance* fieldInstance, BfFieldDef* field)
  2895. {
  2896. bool isDeclType = BfNodeDynCastExact<BfDeclTypeRef>(field->mFieldDeclaration->mTypeRef) != NULL;
  2897. auto fieldType = fieldInstance->GetResolvedType();
  2898. if ((field->mIsConst) && (!isDeclType))
  2899. {
  2900. ResolveConstField(typeInstance, fieldInstance, field);
  2901. return fieldInstance->GetResolvedType();
  2902. }
  2903. bool staticOnly = (field->mIsStatic) && (!isDeclType);
  2904. if (!fieldInstance->mIsInferredType)
  2905. return fieldType;
  2906. if (!fieldType->IsVar())
  2907. return fieldType;
  2908. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  2909. BfTypeState typeState(mCurTypeInstance, mContext->mCurTypeState);
  2910. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState, mContext->mCurTypeState->mTypeInstance != typeInstance);
  2911. auto typeDef = typeInstance->mTypeDef;
  2912. if ((!field->mIsStatic) && (typeDef->mIsStatic))
  2913. {
  2914. AssertErrorState();
  2915. SetHadVarUsage();
  2916. return GetPrimitiveType(BfTypeCode_Var);
  2917. }
  2918. bool hadInferenceCycle = false;
  2919. if (mContext->mFieldResolveReentrys.size() > 1)
  2920. {
  2921. if (mContext->mFieldResolveReentrys.IndexOf(fieldInstance, 1) != -1)
  2922. {
  2923. for (int i = 1; i < (int)mContext->mFieldResolveReentrys.size(); i++)
  2924. {
  2925. auto fieldInst = mContext->mFieldResolveReentrys[i];
  2926. auto fieldDef = fieldInst->GetFieldDef();
  2927. auto fieldOwner = fieldInst->mOwner;
  2928. auto fieldModule = fieldOwner->mModule;
  2929. SetAndRestoreValue<bool> prevIgnoreError(fieldModule->mIgnoreErrors, false);
  2930. fieldModule->Fail(StrFormat("Field '%s.%s' creates a type inference cycle", TypeToString(fieldOwner).c_str(), fieldDef->mName.c_str()), fieldDef->mTypeRef, true);
  2931. }
  2932. SetHadVarUsage();
  2933. return GetPrimitiveType(BfTypeCode_Var);
  2934. }
  2935. }
  2936. mContext->mFieldResolveReentrys.push_back(fieldInstance);
  2937. AutoPopBack<decltype (mContext->mFieldResolveReentrys)> popTypeResolveReentry(&mContext->mFieldResolveReentrys);
  2938. SetAndRestoreValue<bool> prevResolvingVar(typeInstance->mResolvingVarField, true);
  2939. SetAndRestoreValue<bool> prevCtxResolvingVar(mContext->mResolvingVarField, true);
  2940. if ((field->mInitializer == NULL) && (!isDeclType))
  2941. {
  2942. if ((field->mTypeRef->IsA<BfVarTypeReference>()) || (field->mTypeRef->IsA<BfLetTypeReference>()))
  2943. Fail("Implicitly-typed fields must be initialized", field->GetRefNode());
  2944. SetHadVarUsage();
  2945. return GetPrimitiveType(BfTypeCode_Var);
  2946. }
  2947. BfType* resolvedType = NULL;
  2948. if (!hadInferenceCycle)
  2949. {
  2950. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  2951. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL/*ctorMethod.mMethodInstance*/);
  2952. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  2953. BfMethodState methodState;
  2954. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  2955. methodState.mTempKind = staticOnly ? BfMethodState::TempKind_Static : BfMethodState::TempKind_NonStatic;
  2956. if (!staticOnly)
  2957. {
  2958. //BfLocalVariable localVar;
  2959. //methodState.mLocals.push_back(localVar);
  2960. }
  2961. if (isDeclType)
  2962. {
  2963. auto fieldDef = fieldInstance->GetFieldDef();
  2964. resolvedType = ResolveTypeRef(fieldDef->mTypeRef, BfPopulateType_Identity);
  2965. }
  2966. else
  2967. {
  2968. BfTypedValue valueFromExpr;
  2969. valueFromExpr = GetFieldInitializerValue(fieldInstance);
  2970. FixIntUnknown(valueFromExpr);
  2971. resolvedType = valueFromExpr.mType;
  2972. }
  2973. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  2974. }
  2975. if (resolvedType == NULL)
  2976. return GetPrimitiveType(BfTypeCode_Var);
  2977. fieldInstance->SetResolvedType(resolvedType);
  2978. if (field->mIsStatic)
  2979. {
  2980. }
  2981. else if (fieldInstance->mDataIdx <= 0)
  2982. {
  2983. }
  2984. else
  2985. {
  2986. BF_ASSERT(typeInstance->IsIncomplete());
  2987. }
  2988. return resolvedType;
  2989. }
  2990. void BfModule::MarkFieldInitialized(BfFieldInstance* fieldInstance)
  2991. {
  2992. BF_ASSERT(fieldInstance->mOwner == mCurTypeInstance);
  2993. auto fieldType = fieldInstance->GetResolvedType();
  2994. if ((fieldInstance->mMergedDataIdx != -1) && (mCurMethodState != NULL))
  2995. {
  2996. int fieldDataCount = 1;
  2997. if (fieldType->IsStruct())
  2998. {
  2999. auto structTypeInst = fieldType->ToTypeInstance();
  3000. fieldDataCount = structTypeInst->mMergedFieldDataCount;
  3001. }
  3002. //TODO: Under what circumstances could 'thisVariable' be NULL?
  3003. auto thisVariable = GetThisVariable();
  3004. if (thisVariable != NULL)
  3005. {
  3006. for (int i = 0; i < fieldDataCount; i++)
  3007. mCurMethodState->LocalDefined(thisVariable, fieldInstance->mMergedDataIdx + i);
  3008. }
  3009. }
  3010. }
  3011. bool BfModule::IsThreadLocal(BfFieldInstance * fieldInstance)
  3012. {
  3013. if (fieldInstance->mCustomAttributes == NULL)
  3014. return false;
  3015. auto fieldDef = fieldInstance->GetFieldDef();
  3016. if (!fieldDef->mIsStatic)
  3017. return false;
  3018. bool isThreadLocal = false;
  3019. if (fieldInstance->mCustomAttributes != NULL)
  3020. {
  3021. for (auto customAttr : fieldInstance->mCustomAttributes->mAttributes)
  3022. {
  3023. if (customAttr.mType->ToTypeInstance()->mTypeDef == mCompiler->mThreadStaticAttributeTypeDef)
  3024. return true;
  3025. }
  3026. }
  3027. return false;
  3028. }
  3029. BfTypedValue BfModule::GetFieldInitializerValue(BfFieldInstance* fieldInstance, BfExpression* initializer, BfFieldDef* fieldDef, BfType* fieldType)
  3030. {
  3031. if (fieldDef == NULL)
  3032. fieldDef = fieldInstance->GetFieldDef();
  3033. if (fieldType == NULL)
  3034. fieldType = fieldInstance->GetResolvedType();
  3035. if (initializer == NULL)
  3036. {
  3037. if (fieldDef == NULL)
  3038. return BfTypedValue();
  3039. initializer = fieldDef->mInitializer;
  3040. }
  3041. BfTypedValue result;
  3042. if (initializer == NULL)
  3043. {
  3044. result = GetDefaultTypedValue(fieldInstance->mResolvedType);
  3045. }
  3046. else
  3047. {
  3048. if ((mCompiler->mIsResolveOnly) && (mCompiler->mResolvePassData->mSourceClassifier != NULL) && (initializer->IsFromParser(mCompiler->mResolvePassData->mParser)))
  3049. {
  3050. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(initializer, BfSourceElementType_Normal);
  3051. mCompiler->mResolvePassData->mSourceClassifier->VisitChildNoRef(initializer);
  3052. }
  3053. if ((mCurTypeInstance->IsPayloadEnum()) && (fieldDef->IsEnumCaseEntry()))
  3054. {
  3055. Fail("Enums with payloads cannot have explicitly-defined discriminators", initializer);
  3056. BfConstResolver constResolver(this);
  3057. constResolver.Resolve(initializer);
  3058. return GetDefaultTypedValue(fieldType);
  3059. }
  3060. else if (fieldDef->mIsConst)
  3061. {
  3062. BfTypeState typeState;
  3063. typeState.mCurTypeDef = fieldDef->mDeclaringType;
  3064. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  3065. BfConstResolver constResolver(this);
  3066. if (fieldType->IsVar())
  3067. return constResolver.Resolve(initializer);
  3068. else
  3069. return constResolver.Resolve(initializer, fieldType);
  3070. }
  3071. if (fieldType->IsVar())
  3072. result = CreateValueFromExpression(initializer, NULL, (BfEvalExprFlags)(BfEvalExprFlags_NoValueAddr | BfEvalExprFlags_FieldInitializer));
  3073. else
  3074. result = CreateValueFromExpression(initializer, fieldType, (BfEvalExprFlags)(BfEvalExprFlags_NoValueAddr | BfEvalExprFlags_FieldInitializer));
  3075. }
  3076. if (fieldInstance != NULL)
  3077. MarkFieldInitialized(fieldInstance);
  3078. return result;
  3079. }
  3080. void BfModule::CheckInterfaceMethod(BfMethodInstance* methodInstance)
  3081. {
  3082. }
  3083. void BfModule::FindSubTypes(BfTypeInstance* classType, SizedArrayImpl<int>* outVals, SizedArrayImpl<BfTypeInstance*>* exChecks, bool isInterfacePass)
  3084. {
  3085. PopulateType(classType);
  3086. if (isInterfacePass)
  3087. {
  3088. for (auto ifaceInst : classType->mInterfaces)
  3089. {
  3090. if (exChecks->Contains(ifaceInst.mInterfaceType))
  3091. continue;
  3092. if (outVals->Contains(ifaceInst.mInterfaceType->mTypeId))
  3093. continue;
  3094. if (ifaceInst.mDeclaringType->IsExtension())
  3095. {
  3096. bool needsExCheck = false;
  3097. if (ifaceInst.mDeclaringType->mProject != classType->mTypeDef->mProject)
  3098. {
  3099. exChecks->push_back(ifaceInst.mInterfaceType);
  3100. continue;
  3101. }
  3102. }
  3103. outVals->push_back(ifaceInst.mInterfaceType->mTypeId);
  3104. }
  3105. }
  3106. else
  3107. {
  3108. outVals->push_back(classType->mTypeId);
  3109. }
  3110. if (classType->mBaseType != NULL)
  3111. {
  3112. FindSubTypes(classType->mBaseType, outVals, exChecks, isInterfacePass);
  3113. }
  3114. }
  3115. void BfModule::CreateDynamicCastMethod()
  3116. {
  3117. auto objType = mContext->mBfObjectType;
  3118. if ((mCompiler->mIsResolveOnly) || (!mIsReified))
  3119. {
  3120. // The main reason to punt on this method for ResolveOnly is because types can be created
  3121. // and destroyed quickly during autocomplete and the typeId creep can generate lots of
  3122. // entries in the LLVM ConstantInt pool, primarily from the FindSubTypes call. We can
  3123. // remove this punt when we recycle typeId's
  3124. mBfIRBuilder->CreateRet(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(objType)));
  3125. mCurMethodState->mHadReturn = true;
  3126. return;
  3127. }
  3128. bool isInterfacePass = mCurMethodInstance->mMethodDef->mName == BF_METHODNAME_DYNAMICCAST_INTERFACE;
  3129. auto func = mCurMethodState->mIRFunction;
  3130. auto thisValue = mBfIRBuilder->GetArgument(0);
  3131. auto typeIdValue = mBfIRBuilder->GetArgument(1);
  3132. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  3133. auto int32Type = GetPrimitiveType(BfTypeCode_Int32);
  3134. typeIdValue = CastToValue(NULL, BfTypedValue(typeIdValue, intPtrType), int32Type, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_SilentFail));
  3135. auto thisObject = mBfIRBuilder->CreateBitCast(thisValue, mBfIRBuilder->MapType(objType));
  3136. auto trueBB = mBfIRBuilder->CreateBlock("check.true");
  3137. //auto falseBB = mBfIRBuilder->CreateBlock("check.false");
  3138. auto exitBB = mBfIRBuilder->CreateBlock("exit");
  3139. SizedArray<int, 8> typeMatches;
  3140. SizedArray<BfTypeInstance*, 8> exChecks;
  3141. FindSubTypes(mCurTypeInstance, &typeMatches, &exChecks, isInterfacePass);
  3142. if ((mCurTypeInstance->IsGenericTypeInstance()) && (!mCurTypeInstance->IsUnspecializedType()))
  3143. {
  3144. // Add 'unbound' type id to cast list so things like "List<int> is List<>" work
  3145. auto genericTypeInst = mCurTypeInstance->mTypeDef;
  3146. BfTypeVector genericArgs;
  3147. for (int i = 0; i < (int) genericTypeInst->mGenericParamDefs.size(); i++)
  3148. genericArgs.push_back(GetGenericParamType(BfGenericParamKind_Type, i));
  3149. auto unboundType = ResolveTypeDef(mCurTypeInstance->mTypeDef, genericArgs, BfPopulateType_Declaration);
  3150. typeMatches.push_back(unboundType->mTypeId);
  3151. }
  3152. if (mCurTypeInstance->IsBoxed())
  3153. {
  3154. BfBoxedType* boxedType = (BfBoxedType*)mCurTypeInstance;
  3155. BfTypeInstance* innerType = boxedType->mElementType;
  3156. FindSubTypes(innerType, &typeMatches, &exChecks, isInterfacePass);
  3157. if (innerType->IsTypedPrimitive())
  3158. {
  3159. auto underlyingType = innerType->GetUnderlyingType();
  3160. typeMatches.push_back(underlyingType->mTypeId);
  3161. }
  3162. auto innerTypeInst = innerType->ToTypeInstance();
  3163. if ((innerTypeInst->mTypeDef == mCompiler->mSizedArrayTypeDef) ||
  3164. (innerTypeInst->mTypeDef == mCompiler->mPointerTTypeDef) ||
  3165. (innerTypeInst->mTypeDef == mCompiler->mMethodRefTypeDef))
  3166. {
  3167. PopulateType(innerTypeInst);
  3168. //TODO: What case was this supposed to handle?
  3169. //typeMatches.push_back(innerTypeInst->mFieldInstances[0].mResolvedType->mTypeId);
  3170. }
  3171. }
  3172. auto curBlock = mBfIRBuilder->GetInsertBlock();
  3173. BfIRValue vDataPtr;
  3174. if (!exChecks.empty())
  3175. {
  3176. BfType* intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  3177. auto ptrPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(intPtrType)));
  3178. auto vDataPtrPtr = mBfIRBuilder->CreateBitCast(thisValue, ptrPtrType);
  3179. vDataPtr = FixClassVData(mBfIRBuilder->CreateLoad(vDataPtrPtr/*, "vtable"*/));
  3180. }
  3181. auto switchStatement = mBfIRBuilder->CreateSwitch(typeIdValue, exitBB, (int)typeMatches.size() + (int)exChecks.size());
  3182. for (auto typeMatch : typeMatches)
  3183. mBfIRBuilder->AddSwitchCase(switchStatement, GetConstValue32(typeMatch), trueBB);
  3184. Array<BfIRValue> incomingFalses;
  3185. for (auto ifaceTypeInst : exChecks)
  3186. {
  3187. BfIRBlock nextBB = mBfIRBuilder->CreateBlock("exCheck", true);
  3188. mBfIRBuilder->AddSwitchCase(switchStatement, GetConstValue32(ifaceTypeInst->mTypeId), nextBB);
  3189. mBfIRBuilder->SetInsertPoint(nextBB);
  3190. BfIRValue slotOfs = GetInterfaceSlotNum(ifaceTypeInst);
  3191. auto ifacePtrPtr = mBfIRBuilder->CreateInBoundsGEP(vDataPtr, slotOfs/*, "iface"*/);
  3192. auto ifacePtr = mBfIRBuilder->CreateLoad(ifacePtrPtr);
  3193. auto cmpResult = mBfIRBuilder->CreateCmpNE(ifacePtr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0));
  3194. mBfIRBuilder->CreateCondBr(cmpResult, trueBB, exitBB);
  3195. incomingFalses.push_back(nextBB);
  3196. }
  3197. mBfIRBuilder->AddBlock(trueBB);
  3198. mBfIRBuilder->SetInsertPoint(trueBB);
  3199. mBfIRBuilder->CreateBr(exitBB);
  3200. mBfIRBuilder->AddBlock(exitBB);
  3201. mBfIRBuilder->SetInsertPoint(exitBB);
  3202. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapTypeInstPtr(objType), 2);
  3203. mBfIRBuilder->AddPhiIncoming(phi, thisObject, trueBB);
  3204. auto nullValue = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(objType));
  3205. for (auto incomingFalseBlock : incomingFalses)
  3206. mBfIRBuilder->AddPhiIncoming(phi, nullValue, incomingFalseBlock);
  3207. mBfIRBuilder->AddPhiIncoming(phi, nullValue, curBlock);
  3208. mBfIRBuilder->CreateRet(phi);
  3209. mCurMethodState->mHadReturn = true;
  3210. }
  3211. void BfModule::EmitEquals(BfTypedValue leftValue, BfTypedValue rightValue, BfIRBlock exitBB)
  3212. {
  3213. BfExprEvaluator exprEvaluator(this);
  3214. exprEvaluator.mExpectingType = mCurMethodInstance->mReturnType;
  3215. exprEvaluator.PerformBinaryOperation((BfAstNode*)NULL, (BfAstNode*)NULL, BfBinaryOp_Equality, NULL, BfBinOpFlag_None, leftValue, rightValue);
  3216. BfTypedValue result = exprEvaluator.GetResult();
  3217. if (result)
  3218. {
  3219. auto nextBB = mBfIRBuilder->CreateBlock("next");
  3220. mBfIRBuilder->CreateCondBr(result.mValue, nextBB, exitBB);
  3221. mBfIRBuilder->AddBlock(nextBB);
  3222. mBfIRBuilder->SetInsertPoint(nextBB);
  3223. }
  3224. }
  3225. void BfModule::CreateFakeCallerMethod(const String& funcName)
  3226. {
  3227. BF_ASSERT(mCurMethodInstance->mIRFunction);
  3228. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  3229. SizedArray<BfIRType, 4> paramTypes;
  3230. BfIRFunctionType funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  3231. BfIRFunction func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_Internal, "FORCELINK_" + funcName);
  3232. mBfIRBuilder->SetActiveFunction(func);
  3233. auto entryBlock = mBfIRBuilder->CreateBlock("main", true);
  3234. mBfIRBuilder->SetInsertPoint(entryBlock);
  3235. SizedArray<BfIRValue, 8> args;
  3236. BfExprEvaluator exprEvaluator(this);
  3237. if (mCurMethodInstance->HasThis())
  3238. {
  3239. auto thisValue = GetDefaultTypedValue(mCurMethodInstance->GetOwner(), true);
  3240. exprEvaluator.PushThis(NULL, thisValue, mCurMethodInstance, args);
  3241. }
  3242. for (int paramIdx = 0; paramIdx < mCurMethodInstance->GetParamCount(); paramIdx++)
  3243. {
  3244. auto paramType = mCurMethodInstance->GetParamType(paramIdx);
  3245. if (paramType->IsValuelessType())
  3246. continue;
  3247. exprEvaluator.PushArg(GetDefaultTypedValue(paramType, true), args);
  3248. }
  3249. mBfIRBuilder->CreateCall(mCurMethodInstance->mIRFunction, args);
  3250. mBfIRBuilder->CreateRetVoid();
  3251. }
  3252. void BfModule::CreateValueTypeEqualsMethod()
  3253. {
  3254. if (mCurMethodInstance->mIsUnspecialized)
  3255. return;
  3256. if (mCurTypeInstance->IsTypedPrimitive())
  3257. return;
  3258. if (mBfIRBuilder->mIgnoreWrites)
  3259. return;
  3260. BF_ASSERT(!mCurTypeInstance->IsBoxed());
  3261. auto compareType = mCurMethodInstance->mParams[0].mResolvedType;
  3262. bool isValid = true;
  3263. auto compareDType = compareType->ToDependedType();
  3264. BfTypeInstance* compareTypeInst = compareType->ToTypeInstance();
  3265. if (compareTypeInst != NULL)
  3266. {
  3267. if (compareType->IsPrimitiveType())
  3268. compareTypeInst = GetWrappedStructType(compareType);
  3269. if ((compareTypeInst == NULL) || (!compareTypeInst->IsValueType()))
  3270. {
  3271. isValid = false;
  3272. }
  3273. mBfIRBuilder->PopulateType(compareTypeInst);
  3274. }
  3275. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  3276. if (!isValid)
  3277. {
  3278. ClearLifetimeEnds();
  3279. mBfIRBuilder->CreateRet(GetDefaultValue(boolType));
  3280. return;
  3281. }
  3282. AddDependency(compareDType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  3283. auto refNode = mCurTypeInstance->mTypeDef->GetRefNode();
  3284. if (refNode == NULL)
  3285. refNode = mCompiler->mValueTypeTypeDef->GetRefNode();
  3286. UpdateSrcPos(refNode);
  3287. SetIllegalSrcPos();
  3288. auto resultVal = CreateAlloca(boolType);
  3289. mBfIRBuilder->CreateStore(GetConstValue(0, boolType), resultVal);
  3290. auto exitBB = mBfIRBuilder->CreateBlock("exit");
  3291. if (compareType->IsSizedArray())
  3292. {
  3293. auto sizedArrayType = (BfSizedArrayType*)compareType;
  3294. if (sizedArrayType->mElementCount > 6)
  3295. {
  3296. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  3297. auto itr = CreateAlloca(intPtrType);
  3298. mBfIRBuilder->CreateStore(GetDefaultValue(intPtrType), itr);
  3299. auto loopBB = mBfIRBuilder->CreateBlock("loop", true);
  3300. auto bodyBB = mBfIRBuilder->CreateBlock("body", true);
  3301. auto doneBB = mBfIRBuilder->CreateBlock("done", true);
  3302. mBfIRBuilder->CreateBr(loopBB);
  3303. mBfIRBuilder->SetInsertPoint(loopBB);
  3304. auto loadedItr = mBfIRBuilder->CreateLoad(itr);
  3305. auto cmpRes = mBfIRBuilder->CreateCmpGTE(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)sizedArrayType->mElementCount), true);
  3306. mBfIRBuilder->CreateCondBr(cmpRes, doneBB, bodyBB);
  3307. mBfIRBuilder->SetInsertPoint(bodyBB);
  3308. BfTypedValue leftValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, GetDefaultValue(intPtrType), loadedItr), sizedArrayType->mElementType, BfTypedValueKind_Addr);
  3309. BfTypedValue rightValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[1]->mValue, GetDefaultValue(intPtrType), loadedItr), sizedArrayType->mElementType, BfTypedValueKind_Addr);
  3310. EmitEquals(leftValue, rightValue, exitBB);
  3311. auto incValue = mBfIRBuilder->CreateAdd(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  3312. mBfIRBuilder->CreateStore(incValue, itr);
  3313. mBfIRBuilder->CreateBr(loopBB);
  3314. mBfIRBuilder->SetInsertPoint(doneBB);
  3315. }
  3316. else
  3317. {
  3318. for (int dataIdx = 0; dataIdx < sizedArrayType->mElementCount; dataIdx++)
  3319. {
  3320. BfTypedValue leftValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, dataIdx), sizedArrayType->mElementType, BfTypedValueKind_Addr);
  3321. BfTypedValue rightValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[1]->mValue, 0, dataIdx), sizedArrayType->mElementType, BfTypedValueKind_Addr);
  3322. EmitEquals(leftValue, rightValue, exitBB);
  3323. }
  3324. }
  3325. }
  3326. else if (compareType->IsMethodRef())
  3327. {
  3328. auto methodRefType = (BfMethodRefType*)compareType;
  3329. BfMethodInstance* methodInstance = methodRefType->mMethodRef;
  3330. BfExprEvaluator exprEvaluator(this);
  3331. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  3332. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  3333. // We only need to compare the 'this' capture. The rationale is that it's impossible to capture any other non-matching
  3334. // values for the same method reference -- they will always refer back to the same local variables.
  3335. int dataIdx = methodRefType->GetDataIdxFromParamIdx(-1);
  3336. if (dataIdx != -1)
  3337. {
  3338. bool failed = false;
  3339. BfTypedValue leftValue = exprEvaluator.DoImplicitArgCapture(NULL, methodInstance, methodRefType->GetParamIdxFromDataIdx(dataIdx), failed, BfImplicitParamKind_General, leftTypedVal);
  3340. BfTypedValue rightValue = exprEvaluator.DoImplicitArgCapture(NULL, methodInstance, methodRefType->GetParamIdxFromDataIdx(dataIdx), failed, BfImplicitParamKind_General, rightTypedVal);
  3341. BF_ASSERT(!failed);
  3342. EmitEquals(leftValue, rightValue, exitBB);
  3343. }
  3344. }
  3345. else if (compareTypeInst->IsEnum())
  3346. {
  3347. //auto intType = GetPrimitiveType(BfTypeCode_Int32);
  3348. BfExprEvaluator exprEvaluator(this);
  3349. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  3350. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  3351. auto dscrType = compareTypeInst->GetDiscriminatorType();
  3352. BfTypedValue leftValue = ExtractValue(leftTypedVal, NULL, 2);
  3353. leftValue = LoadValue(leftValue);
  3354. BfTypedValue rightValue = ExtractValue(rightTypedVal, NULL, 2);
  3355. rightValue = LoadValue(rightValue);
  3356. BfTypedValue leftPayload = ExtractValue(leftTypedVal, NULL, 1);
  3357. BfTypedValue rightPayload = ExtractValue(rightTypedVal, NULL, 1);
  3358. EmitEquals(leftValue, rightValue, exitBB);
  3359. int enumCount = 0;
  3360. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  3361. {
  3362. BfFieldInstance* fieldInstance = &fieldRef;
  3363. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  3364. if ((fieldDef != NULL) && (fieldDef->IsEnumCaseEntry()))
  3365. {
  3366. enumCount = -fieldInstance->mDataIdx;
  3367. }
  3368. }
  3369. if (enumCount > 0)
  3370. {
  3371. BfIRBlock matchedBlock = mBfIRBuilder->CreateBlock("matched");
  3372. auto switchVal = mBfIRBuilder->CreateSwitch(leftValue.mValue, exitBB, enumCount);
  3373. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  3374. {
  3375. BfFieldInstance* fieldInstance = &fieldRef;
  3376. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  3377. if ((fieldDef != NULL) && (fieldDef->IsEnumCaseEntry()))
  3378. {
  3379. int enumIdx = -fieldInstance->mDataIdx - 1;
  3380. if (fieldInstance->mResolvedType->mSize == 0)
  3381. {
  3382. mBfIRBuilder->AddSwitchCase(switchVal, mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, enumIdx), matchedBlock);
  3383. }
  3384. else
  3385. {
  3386. auto caseBlock = mBfIRBuilder->CreateBlock("case", true);
  3387. mBfIRBuilder->SetInsertPoint(caseBlock);
  3388. auto tuplePtr = CreatePointerType(fieldInstance->mResolvedType);
  3389. BfTypedValue leftTuple;
  3390. BfTypedValue rightTuple;
  3391. if (leftPayload.IsAddr())
  3392. {
  3393. leftTuple = BfTypedValue(mBfIRBuilder->CreateBitCast(leftPayload.mValue, mBfIRBuilder->MapType(tuplePtr)), fieldInstance->mResolvedType, true);
  3394. rightTuple = BfTypedValue(mBfIRBuilder->CreateBitCast(rightPayload.mValue, mBfIRBuilder->MapType(tuplePtr)), fieldInstance->mResolvedType, true);
  3395. }
  3396. else
  3397. {
  3398. leftTuple = Cast(NULL, leftPayload, fieldInstance->mResolvedType, BfCastFlags_Force);
  3399. rightTuple = Cast(NULL, rightPayload, fieldInstance->mResolvedType, BfCastFlags_Force);
  3400. }
  3401. EmitEquals(leftTuple, rightTuple, exitBB);
  3402. mBfIRBuilder->CreateBr(matchedBlock);
  3403. mBfIRBuilder->AddSwitchCase(switchVal, mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, enumIdx), caseBlock);
  3404. }
  3405. }
  3406. }
  3407. mBfIRBuilder->AddBlock(matchedBlock);
  3408. mBfIRBuilder->SetInsertPoint(matchedBlock);
  3409. }
  3410. }
  3411. else if (compareTypeInst->IsUnion())
  3412. {
  3413. auto innerType = compareTypeInst->GetUnionInnerType();
  3414. if (!innerType->IsValuelessType())
  3415. {
  3416. BfExprEvaluator exprEvaluator(this);
  3417. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  3418. BfTypedValue leftUnionTypedVal = ExtractValue(leftTypedVal, NULL, 1);
  3419. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  3420. BfTypedValue rightUnionTypedVal = ExtractValue(rightTypedVal, NULL, 1);
  3421. EmitEquals(leftUnionTypedVal, rightUnionTypedVal, exitBB);
  3422. }
  3423. }
  3424. else
  3425. {
  3426. BfExprEvaluator exprEvaluator(this);
  3427. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  3428. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  3429. bool hadComparison = false;
  3430. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  3431. {
  3432. BfFieldInstance* fieldInstance = &fieldRef;
  3433. if (fieldInstance->mDataOffset == -1)
  3434. continue;
  3435. if (fieldInstance->mResolvedType->IsValuelessType())
  3436. continue;
  3437. BfTypedValue leftValue = ExtractValue(leftTypedVal, fieldInstance, fieldInstance->mDataIdx);
  3438. BfTypedValue rightValue = ExtractValue(rightTypedVal, fieldInstance, fieldInstance->mDataIdx);
  3439. if (!fieldInstance->mResolvedType->IsComposite())
  3440. {
  3441. leftValue = LoadValue(leftValue);
  3442. rightValue = LoadValue(rightValue);
  3443. }
  3444. EmitEquals(leftValue, rightValue, exitBB);
  3445. }
  3446. auto baseTypeInst = compareTypeInst->mBaseType;
  3447. if ((baseTypeInst != NULL) && (baseTypeInst->mTypeDef != mCompiler->mValueTypeTypeDef))
  3448. {
  3449. BfTypedValue leftOrigValue(mCurMethodState->mLocals[0]->mValue, compareTypeInst, true);
  3450. BfTypedValue rightOrigValue(mCurMethodState->mLocals[1]->mValue, compareTypeInst, true);
  3451. BfTypedValue leftValue = Cast(NULL, leftOrigValue, baseTypeInst);
  3452. BfTypedValue rightValue = Cast(NULL, rightOrigValue, baseTypeInst);
  3453. EmitEquals(leftValue, rightValue, exitBB);
  3454. }
  3455. }
  3456. mBfIRBuilder->CreateStore(GetConstValue(1, boolType), resultVal);
  3457. mBfIRBuilder->CreateBr(exitBB);
  3458. mBfIRBuilder->AddBlock(exitBB);
  3459. mBfIRBuilder->SetInsertPoint(exitBB);
  3460. auto loadedResult = mBfIRBuilder->CreateLoad(resultVal);
  3461. ClearLifetimeEnds();
  3462. mBfIRBuilder->CreateRet(loadedResult);
  3463. mCurMethodState->mHadReturn = true;
  3464. }
  3465. BfIRValue BfModule::CreateClassVDataGlobal(BfTypeInstance* typeInstance, int* outNumElements, String* outMangledName)
  3466. {
  3467. if (mBfIRBuilder->mIgnoreWrites)
  3468. return mBfIRBuilder->GetFakeVal();
  3469. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  3470. BfType* classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  3471. BfIRValue* globalVariablePtr = NULL;
  3472. mClassVDataRefs.TryGetValue(typeInstance, &globalVariablePtr);
  3473. int numElements = 1;
  3474. if ((outNumElements != NULL) || (globalVariablePtr == NULL))
  3475. {
  3476. numElements += mCompiler->mMaxInterfaceSlots;
  3477. auto maxIFaceVirtIdx = 0;
  3478. if (!typeInstance->IsInterface())
  3479. {
  3480. int dynCastDataElems = 1 + mCompiler->mMaxInterfaceSlots;
  3481. numElements += ((dynCastDataElems * 4) + mSystem->mPtrSize - 1) / mSystem->mPtrSize;
  3482. numElements += typeInstance->GetOrigVTableSize();
  3483. int ifaceMethodLen = typeInstance->GetIFaceVMethodSize();
  3484. if (typeInstance->mHotTypeData != NULL)
  3485. {
  3486. if (typeInstance->mHotTypeData->mOrigInterfaceMethodsLength != -1)
  3487. ifaceMethodLen = typeInstance->mHotTypeData->mOrigInterfaceMethodsLength;
  3488. }
  3489. numElements += ifaceMethodLen;
  3490. }
  3491. if (outNumElements != NULL)
  3492. *outNumElements = numElements;
  3493. }
  3494. StringT<128> classVDataName;
  3495. String memberName = "sBfClassVData";
  3496. if ((typeInstance->mHotTypeData != NULL) && ((typeInstance->mHotTypeData->mHadDataChange) || (typeInstance->mHotTypeData->mPendingDataChange)))
  3497. {
  3498. auto curVersion = typeInstance->mHotTypeData->GetLatestVersion();
  3499. memberName += "_";
  3500. memberName += BfTypeUtils::HashEncode64(curVersion->mDataHash.mLow);
  3501. memberName += BfTypeUtils::HashEncode64(curVersion->mDataHash.mHigh);
  3502. }
  3503. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), typeInstance, memberName, classVDataType);
  3504. if (outMangledName != NULL)
  3505. *outMangledName = classVDataName;
  3506. /*if (itr != mClassVDataRefs.end())
  3507. {
  3508. globalVariable = itr->second;
  3509. }*/
  3510. BfIRValue globalVariable;
  3511. if (globalVariablePtr != NULL)
  3512. {
  3513. globalVariable = *globalVariablePtr;
  3514. }
  3515. else
  3516. {
  3517. BfLogSysM("Creating VData %s\n", classVDataName.c_str());
  3518. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), numElements);
  3519. globalVariable = mBfIRBuilder->CreateGlobalVariable(
  3520. arrayType,
  3521. true,
  3522. BfIRLinkageType_External,
  3523. BfIRValue(),
  3524. classVDataName);
  3525. mClassVDataRefs[typeInstance] = globalVariable;
  3526. }
  3527. return globalVariable;
  3528. }
  3529. BfIRValue BfModule::GetClassVDataPtr(BfTypeInstance* typeInstance)
  3530. {
  3531. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  3532. return mBfIRBuilder->CreateBitCast(CreateClassVDataGlobal(typeInstance), mBfIRBuilder->MapType(CreatePointerType(classVDataType)));
  3533. }
  3534. BfIRValue BfModule::CreateClassVDataExtGlobal(BfTypeInstance* declTypeInst, BfTypeInstance* implTypeInst, int startVirtIdx)
  3535. {
  3536. if (mBfIRBuilder->mIgnoreWrites)
  3537. return mBfIRBuilder->GetFakeVal();
  3538. int numElements = declTypeInst->GetSelfVTableSize() - declTypeInst->GetOrigSelfVTableSize();
  3539. BF_ASSERT(numElements >= 0);
  3540. if (numElements <= 0)
  3541. return BfIRValue();
  3542. BF_ASSERT(implTypeInst->mVirtualMethodTable[startVirtIdx].mDeclaringMethod.mMethodNum == -1);
  3543. BF_ASSERT(implTypeInst->mVirtualMethodTable[startVirtIdx].mDeclaringMethod.mTypeInstance == declTypeInst);
  3544. if (declTypeInst->mInheritDepth == implTypeInst->mInheritDepth)
  3545. BF_ASSERT(declTypeInst == implTypeInst);
  3546. else
  3547. BF_ASSERT(implTypeInst->mInheritDepth > declTypeInst->mInheritDepth);
  3548. if (declTypeInst != implTypeInst)
  3549. {
  3550. BfTypeInstance* highestImpl = declTypeInst;
  3551. for (int virtIdx = startVirtIdx + 1; virtIdx < (int)declTypeInst->mVirtualMethodTable.size(); virtIdx++)
  3552. {
  3553. if (implTypeInst->mVirtualMethodTable[virtIdx].mDeclaringMethod.mMethodNum == -1)
  3554. break; // Start of an ext entry for another type
  3555. auto checkImplTypeInst = implTypeInst->mVirtualMethodTable[virtIdx].mImplementingMethod.mTypeInstance;
  3556. if ((checkImplTypeInst != NULL) && (checkImplTypeInst->mInheritDepth > highestImpl->mInheritDepth))
  3557. highestImpl = checkImplTypeInst;
  3558. }
  3559. if (highestImpl != implTypeInst)
  3560. return CreateClassVDataExtGlobal(declTypeInst, highestImpl, startVirtIdx);
  3561. }
  3562. BfVDataExtEntry mapEntry;
  3563. mapEntry.mDeclTypeInst = declTypeInst;
  3564. mapEntry.mImplTypeInst = implTypeInst;
  3565. BfIRValue* irValuePtr = NULL;
  3566. if (mClassVDataExtRefs.TryGetValue(mapEntry, &irValuePtr))
  3567. return *irValuePtr;
  3568. PopulateType(declTypeInst, BfPopulateType_DataAndMethods);
  3569. PopulateType(implTypeInst, BfPopulateType_DataAndMethods);
  3570. StringT<128> classVDataName;
  3571. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), implTypeInst, "bf_hs_replace_VDataExt");
  3572. if (declTypeInst != implTypeInst)
  3573. {
  3574. classVDataName += StrFormat("_%d", implTypeInst->mInheritDepth - declTypeInst->mInheritDepth);
  3575. }
  3576. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  3577. auto voidPtrIRType = mBfIRBuilder->MapType(voidPtrType);
  3578. SizedArray<BfIRValue, 32> vData;
  3579. auto voidPtrNull = GetDefaultValue(voidPtrType);
  3580. for (int virtIdx = startVirtIdx + declTypeInst->GetOrigSelfVTableSize(); virtIdx < (int)declTypeInst->mVirtualMethodTable.size(); virtIdx++)
  3581. {
  3582. if (implTypeInst->mVirtualMethodTable[virtIdx].mDeclaringMethod.mMethodNum == -1)
  3583. break; // Start of an ext entry for another type
  3584. BfIRValue vValue;
  3585. auto& entry = implTypeInst->mVirtualMethodTable[virtIdx];
  3586. BfMethodInstance* declaringMethodInstance = (BfMethodInstance*)entry.mDeclaringMethod;
  3587. if ((declaringMethodInstance != NULL) && (declaringMethodInstance->mMethodInstanceGroup->IsImplemented()) && (declaringMethodInstance->mIsReified))
  3588. {
  3589. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].IsImplemented());
  3590. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].mDefault->mIsReified);
  3591. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  3592. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  3593. {
  3594. BF_ASSERT(implTypeInst->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject));
  3595. auto moduleMethodInst = GetMethodInstanceAtIdx(methodInstance->mMethodInstanceGroup->mOwner, methodInstance->mMethodInstanceGroup->mMethodIdx);
  3596. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  3597. vValue = funcPtr;
  3598. }
  3599. }
  3600. if (!vValue)
  3601. vValue = voidPtrNull;
  3602. vData.Add(vValue);
  3603. }
  3604. BF_ASSERT((int)vData.size() == numElements);
  3605. BfLogSysM("Creating VDataExt %s\n", classVDataName.c_str());
  3606. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), numElements);
  3607. auto globalVariable = mBfIRBuilder->CreateGlobalVariable(arrayType, true,
  3608. BfIRLinkageType_External, BfIRValue(), classVDataName);
  3609. BfIRType extVTableType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)vData.size());
  3610. BfIRValue extVTableConst = mBfIRBuilder->CreateConstArray(extVTableType, vData);
  3611. mBfIRBuilder->GlobalVar_SetInitializer(globalVariable, extVTableConst);
  3612. mClassVDataExtRefs[mapEntry] = globalVariable;
  3613. return globalVariable;
  3614. }
  3615. BfIRValue BfModule::CreateTypeDataRef(BfType* type)
  3616. {
  3617. if (mBfIRBuilder->mIgnoreWrites)
  3618. {
  3619. return mBfIRBuilder->CreateTypeOf(type);
  3620. }
  3621. BfIRValue globalVariable;
  3622. BfIRValue* globalVariablePtr = NULL;
  3623. if (mTypeDataRefs.TryGetValue(type, &globalVariablePtr))
  3624. {
  3625. globalVariable = *globalVariablePtr;
  3626. if (globalVariable)
  3627. return globalVariable;
  3628. }
  3629. auto typeTypeDef = ResolveTypeDef(mCompiler->mTypeTypeDef);
  3630. auto typeTypeInst = typeTypeDef->ToTypeInstance();
  3631. auto typeInstance = type->ToTypeInstance();
  3632. StringT<128> typeDataName;
  3633. if (typeInstance != NULL)
  3634. {
  3635. BfMangler::MangleStaticFieldName(typeDataName, mCompiler->GetMangleKind(), typeInstance, "sBfTypeData");
  3636. }
  3637. else
  3638. {
  3639. typeDataName += "sBfTypeData.";
  3640. BfMangler::Mangle(typeDataName, mCompiler->GetMangleKind(), type);
  3641. }
  3642. BfLogSysM("Creating TypeData %s\n", typeDataName.c_str());
  3643. globalVariable = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(typeTypeInst, BfIRPopulateType_Full), true, BfIRLinkageType_External, BfIRValue(), typeDataName);
  3644. mTypeDataRefs[type] = globalVariable;
  3645. return globalVariable;
  3646. }
  3647. BfIRValue BfModule::CreateTypeData(BfType* type, Dictionary<int, int>& usedStringIdMap, bool forceReflectFields, bool needsTypeData, bool needsTypeNames, bool needsVData)
  3648. {
  3649. if ((mCompiler->IsHotCompile()) && (!type->mDirty))
  3650. return BfIRValue();
  3651. BfIRValue* irValuePtr = NULL;
  3652. if (mTypeDataRefs.TryGetValue(type, &irValuePtr))
  3653. {
  3654. return *irValuePtr;
  3655. }
  3656. BfTypeInstance* typeInstance = type->ToTypeInstance();
  3657. BfType* typeInstanceType = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef);
  3658. mBfIRBuilder->PopulateType(typeInstanceType, BfIRPopulateType_Full_ForceDefinition);
  3659. if (typeInstanceType == NULL)
  3660. {
  3661. AssertErrorState();
  3662. return BfIRValue();
  3663. }
  3664. BfIRValue typeTypeData;
  3665. int typeFlags = 0;
  3666. if (needsTypeData)
  3667. {
  3668. BfTypeInstance* typeInstanceTypeInstance = typeInstanceType->ToTypeInstance();
  3669. BfTypeInstance* typeDataSource = NULL;
  3670. if (typeInstance != NULL)
  3671. {
  3672. if (typeInstance->IsUnspecializedType())
  3673. {
  3674. typeDataSource = ResolveTypeDef(mCompiler->mReflectUnspecializedGenericType)->ToTypeInstance();
  3675. typeFlags |= BfTypeFlags_UnspecializedGeneric;
  3676. }
  3677. else if (typeInstance->IsArray())
  3678. {
  3679. typeDataSource = ResolveTypeDef(mCompiler->mReflectArrayType)->ToTypeInstance();
  3680. typeFlags |= BfTypeFlags_Array;
  3681. }
  3682. else if (typeInstance->IsGenericTypeInstance())
  3683. {
  3684. typeDataSource = ResolveTypeDef(mCompiler->mReflectSpecializedGenericType)->ToTypeInstance();
  3685. typeFlags |= BfTypeFlags_SpecializedGeneric;
  3686. }
  3687. else
  3688. typeDataSource = typeInstanceTypeInstance;
  3689. }
  3690. else if (type->IsPointer())
  3691. typeDataSource = ResolveTypeDef(mCompiler->mReflectPointerType)->ToTypeInstance();
  3692. else if (type->IsSizedArray())
  3693. typeDataSource = ResolveTypeDef(mCompiler->mReflectSizedArrayType)->ToTypeInstance();
  3694. else
  3695. typeDataSource = mContext->mBfTypeType;
  3696. if ((!mTypeDataRefs.ContainsKey(typeDataSource)) && (typeDataSource != type))
  3697. {
  3698. CreateTypeData(typeDataSource, usedStringIdMap, false, true, needsTypeNames, true);
  3699. }
  3700. typeTypeData = CreateClassVDataGlobal(typeDataSource);
  3701. }
  3702. else
  3703. typeTypeData = CreateClassVDataGlobal(typeInstanceType->ToTypeInstance());
  3704. BfType* longType = GetPrimitiveType(BfTypeCode_Int64);
  3705. BfType* intType = GetPrimitiveType(BfTypeCode_Int32);
  3706. BfType* shortType = GetPrimitiveType(BfTypeCode_Int16);
  3707. BfType* byteType = GetPrimitiveType(BfTypeCode_Int8);
  3708. BfType* typeIdType = intType;
  3709. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  3710. auto voidPtrIRType = mBfIRBuilder->MapType(voidPtrType);
  3711. auto voidPtrPtrIRType = mBfIRBuilder->GetPointerTo(voidPtrIRType);
  3712. auto voidPtrNull = GetDefaultValue(voidPtrType);
  3713. SizedArray<BfIRValue, 4> typeValueParams;
  3714. GetConstClassValueParam(typeTypeData, typeValueParams);
  3715. BfIRValue objectData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(mContext->mBfObjectType, BfIRPopulateType_Full), typeValueParams);
  3716. StringT<128> typeDataName;
  3717. if ((typeInstance != NULL) && (!typeInstance->IsTypeAlias()))
  3718. {
  3719. BfMangler::MangleStaticFieldName(typeDataName, mCompiler->GetMangleKind(), typeInstance, "sBfTypeData");
  3720. if (typeInstance->mTypeDef->IsGlobalsContainer())
  3721. typeDataName += "@" + typeInstance->mTypeDef->mProject->mName;
  3722. }
  3723. else
  3724. {
  3725. typeDataName += "sBfTypeData.";
  3726. BfMangler::Mangle(typeDataName, mCompiler->GetMangleKind(), type);
  3727. }
  3728. int typeCode = BfTypeCode_None;
  3729. if (typeInstance != NULL)
  3730. {
  3731. typeCode = typeInstance->mTypeDef->mTypeCode;
  3732. }
  3733. else if (type->IsPrimitiveType())
  3734. {
  3735. BfPrimitiveType* primType = (BfPrimitiveType*)type;
  3736. typeCode = primType->mTypeDef->mTypeCode;
  3737. }
  3738. else if (type->IsPointer())
  3739. {
  3740. typeCode = BfTypeCode_Pointer;
  3741. typeFlags |= BfTypeFlags_Pointer;
  3742. }
  3743. if (type->IsObject())
  3744. {
  3745. typeFlags |= BfTypeFlags_Object;
  3746. BfMethodInstance* methodInstance = typeInstance->mVirtualMethodTable[mCompiler->GetVTableMethodOffset() + 0].mImplementingMethod;
  3747. if (methodInstance->GetOwner() != mContext->mBfObjectType)
  3748. typeFlags |= BfTypeFlags_HasDestructor;
  3749. }
  3750. if (type->IsStruct())
  3751. typeFlags |= BfTypeFlags_Struct;
  3752. if (type->IsBoxed())
  3753. {
  3754. typeFlags |= BfTypeFlags_Boxed;
  3755. if (((BfBoxedType*)type)->IsBoxedStructPtr())
  3756. typeFlags |= BfTypeFlags_Pointer;
  3757. }
  3758. if (type->IsPrimitiveType())
  3759. typeFlags |= BfTypeFlags_Primitive;
  3760. if (type->IsTypedPrimitive())
  3761. typeFlags |= BfTypeFlags_TypedPrimitive;
  3762. if (type->IsTuple())
  3763. typeFlags |= BfTypeFlags_Tuple;
  3764. if (type->IsNullable())
  3765. typeFlags |= BfTypeFlags_Nullable;
  3766. if (type->IsSizedArray())
  3767. typeFlags |= BfTypeFlags_SizedArray;
  3768. if (type->IsSplattable())
  3769. typeFlags |= BfTypeFlags_Splattable;
  3770. if (type->IsUnion())
  3771. typeFlags |= BfTypeFlags_Union;
  3772. if (type->IsDelegate())
  3773. typeFlags |= BfTypeFlags_Delegate;
  3774. if (type->WantsGCMarking())
  3775. typeFlags |= BfTypeFlags_WantsMarking;
  3776. int memberDataOffset = 0;
  3777. if (typeInstance != NULL)
  3778. {
  3779. for (auto& fieldInstance : typeInstance->mFieldInstances)
  3780. {
  3781. if (fieldInstance.mDataOffset != -1)
  3782. {
  3783. memberDataOffset = fieldInstance.mDataOffset;
  3784. break;
  3785. }
  3786. }
  3787. }
  3788. SizedArray<BfIRValue, 8> typeDataParams =
  3789. {
  3790. objectData,
  3791. GetConstValue(type->mSize, intType), // mSize
  3792. GetConstValue(type->mTypeId, typeIdType), // mTypeId
  3793. GetConstValue(typeFlags, intType), // mTypeFlags
  3794. GetConstValue(memberDataOffset, intType), // mMemberDataOffset
  3795. GetConstValue(typeCode, byteType), // mTypeCode
  3796. GetConstValue(type->mAlign, byteType),
  3797. };
  3798. auto typeData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(mContext->mBfTypeType, BfIRPopulateType_Full), typeDataParams);
  3799. if (typeInstance == NULL)
  3800. {
  3801. BfIRValue typeDataVar;
  3802. if (needsTypeData)
  3803. {
  3804. if (type->IsPointer())
  3805. {
  3806. auto pointerType = (BfPointerType*)type;
  3807. SizedArray<BfIRValue, 3> pointerTypeDataParms =
  3808. {
  3809. typeData,
  3810. GetConstValue(pointerType->mElementType->mTypeId, typeIdType),
  3811. };
  3812. auto reflectPointerType = ResolveTypeDef(mCompiler->mReflectPointerType)->ToTypeInstance();
  3813. auto pointerTypeData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectPointerType, BfIRPopulateType_Full), pointerTypeDataParms);
  3814. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectPointerType), true,
  3815. BfIRLinkageType_External, pointerTypeData, typeDataName);
  3816. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  3817. }
  3818. else if (type->IsSizedArray())
  3819. {
  3820. auto sizedArrayType = (BfSizedArrayType*)type;
  3821. SizedArray<BfIRValue, 3> sizedArrayTypeDataParms =
  3822. {
  3823. typeData,
  3824. GetConstValue(sizedArrayType->mElementType->mTypeId, typeIdType),
  3825. GetConstValue(sizedArrayType->mElementCount, intType)
  3826. };
  3827. auto reflectSizedArrayType = ResolveTypeDef(mCompiler->mReflectSizedArrayType)->ToTypeInstance();
  3828. auto sizedArrayTypeData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectSizedArrayType, BfIRPopulateType_Full), sizedArrayTypeDataParms);
  3829. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectSizedArrayType), true,
  3830. BfIRLinkageType_External, sizedArrayTypeData, typeDataName);
  3831. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  3832. }
  3833. else
  3834. {
  3835. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(mContext->mBfTypeType), true,
  3836. BfIRLinkageType_External, typeData, typeDataName);
  3837. }
  3838. }
  3839. else
  3840. typeDataVar = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(mContext->mBfTypeType));
  3841. mTypeDataRefs[typeInstance] = typeDataVar;
  3842. return typeDataVar;
  3843. }
  3844. // Reserve position
  3845. mTypeDataRefs[typeInstance] = BfIRValue();
  3846. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  3847. BfTypeDef* typeDef = typeInstance->mTypeDef;
  3848. StringT<128> mangledName;
  3849. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), typeInstance);
  3850. for (int methodIdx = 0; methodIdx < (int)typeDef->mMethods.size(); methodIdx++)
  3851. {
  3852. auto methodDef = typeDef->mMethods[methodIdx];
  3853. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  3854. if (methodInstance == NULL)
  3855. continue;
  3856. if (typeInstance->IsUnspecializedType())
  3857. continue;
  3858. if (!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, mProject))
  3859. {
  3860. if (methodInstance->mChainType == BfMethodChainType_ChainMember)
  3861. {
  3862. BF_ASSERT(!methodInstance->GetOwner()->IsUnspecializedType());
  3863. // We need to create an empty thunk for this chained method
  3864. BfIRFunction func = CreateFunctionFrom(methodInstance, false, methodInstance->mAlwaysInline);
  3865. mBfIRBuilder->SetActiveFunction(func);
  3866. auto block = mBfIRBuilder->CreateBlock("entry", true);
  3867. mBfIRBuilder->SetInsertPoint(block);
  3868. mBfIRBuilder->CreateRetVoid();
  3869. mBfIRBuilder->SetActiveFunction(BfIRFunction());
  3870. }
  3871. }
  3872. }
  3873. SizedArray<BfIRValue, 32> vData;
  3874. BfIRValue classVDataVar;
  3875. String classVDataName;
  3876. if (typeInstance->mSlotNum >= 0)
  3877. {
  3878. // For interfaces we ONLY emit the slot num
  3879. int virtSlotIdx = typeInstance->mSlotNum + 1 + mCompiler->GetDynCastVDataCount();
  3880. StringT<128> slotVarName;
  3881. BfMangler::MangleStaticFieldName(slotVarName, mCompiler->GetMangleKind(), typeInstance, "sBfSlotOfs");
  3882. auto intType = GetPrimitiveType(BfTypeCode_Int32);
  3883. auto slotNumVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(intType), true, BfIRLinkageType_External,
  3884. GetConstValue32(virtSlotIdx), slotVarName);
  3885. }
  3886. else if ((typeInstance->IsObject()) && (!typeInstance->IsUnspecializedType()) && (needsVData))
  3887. {
  3888. int dynCastDataElems = 0;
  3889. int numElements = 1;
  3890. int vDataOfs = 1; // The number of intptrs before the iface slot map
  3891. numElements += mCompiler->mMaxInterfaceSlots;
  3892. if (!typeInstance->IsInterface())
  3893. {
  3894. dynCastDataElems = 1 + mCompiler->mMaxInterfaceSlots;
  3895. numElements += mCompiler->GetDynCastVDataCount();
  3896. numElements += typeInstance->mVirtualMethodTableSize;
  3897. }
  3898. int expectNumElements = 0;
  3899. if (!typeDef->mIsStatic)
  3900. {
  3901. classVDataVar = CreateClassVDataGlobal(typeInstance, &expectNumElements, &classVDataName);
  3902. }
  3903. vData.push_back(BfIRValue()); // Type*
  3904. SizedArray<BfIRValue, 1> extVTableData;
  3905. SizedArrayImpl<BfIRValue>* vFuncDataExt = &extVTableData;
  3906. if (!typeInstance->IsInterface())
  3907. {
  3908. Array<int32> dynCastData;
  3909. if (typeInstance->IsBoxed())
  3910. {
  3911. auto underlyingType = typeInstance->GetUnderlyingType()->ToTypeInstance();
  3912. dynCastData.Add(underlyingType->mInheritanceId);
  3913. }
  3914. else
  3915. dynCastData.Add(typeInstance->mInheritanceId);
  3916. for (int i = 0; i < mCompiler->mMaxInterfaceSlots; i++)
  3917. dynCastData.Add(0);
  3918. dynCastData.Add(0);
  3919. auto checkTypeInst = typeInstance;
  3920. while (checkTypeInst != NULL)
  3921. {
  3922. for (auto&& interfaceEntry : checkTypeInst->mInterfaces)
  3923. {
  3924. if (interfaceEntry.mInterfaceType->mSlotNum >= 0)
  3925. {
  3926. if (dynCastData[interfaceEntry.mInterfaceType->mSlotNum + 1] == 0)
  3927. dynCastData[interfaceEntry.mInterfaceType->mSlotNum + 1] = interfaceEntry.mInterfaceType->mTypeId;
  3928. }
  3929. }
  3930. checkTypeInst = checkTypeInst->GetImplBaseType();
  3931. }
  3932. if (mSystem->mPtrSize == 8)
  3933. {
  3934. int intPtrCount = (dynCastDataElems + 1) / 2;
  3935. vDataOfs += intPtrCount;
  3936. uint64* intPtrData = (uint64*)&dynCastData[0];
  3937. for (int i = 0; i < intPtrCount; i++)
  3938. {
  3939. uint64 val = intPtrData[i];
  3940. if (val == 0)
  3941. {
  3942. vData.push_back(voidPtrNull);
  3943. }
  3944. else
  3945. {
  3946. auto intPtrVal = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, val);
  3947. vData.push_back(mBfIRBuilder->CreateBitCast(intPtrVal, voidPtrIRType));
  3948. }
  3949. }
  3950. }
  3951. else
  3952. {
  3953. int intPtrCount = dynCastDataElems;
  3954. vDataOfs += intPtrCount;
  3955. uint32* intPtrData = (uint32*)&dynCastData[0];
  3956. for (int i = 0; i < intPtrCount; i++)
  3957. {
  3958. uint32 val = intPtrData[i];
  3959. if (val == 0)
  3960. {
  3961. vData.push_back(voidPtrNull);
  3962. }
  3963. else
  3964. {
  3965. auto intPtrVal = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (int)val);
  3966. vData.push_back(mBfIRBuilder->CreateBitCast(intPtrVal, voidPtrIRType));
  3967. }
  3968. }
  3969. }
  3970. }
  3971. for (int iSlotIdx = 0; iSlotIdx < mCompiler->mMaxInterfaceSlots; iSlotIdx++)
  3972. vData.push_back(voidPtrNull);
  3973. struct _InterfaceMatchEntry
  3974. {
  3975. BfTypeInterfaceEntry* mEntry;
  3976. BfTypeInstance* mEntrySource;
  3977. Array<BfTypeInterfaceEntry*> mAmbiguousEntries;
  3978. };
  3979. int highestIFaceVirtIdx = 0;
  3980. Dictionary<BfTypeInstance*, _InterfaceMatchEntry> interfaceMap;
  3981. auto checkTypeInst = typeInstance;
  3982. bool forceInterfaceSet = false;
  3983. while (checkTypeInst != NULL)
  3984. {
  3985. for (auto&& interfaceEntry : checkTypeInst->mInterfaces)
  3986. {
  3987. highestIFaceVirtIdx = BF_MAX(highestIFaceVirtIdx, interfaceEntry.mStartVirtualIdx + interfaceEntry.mInterfaceType->mVirtualMethodTableSize);
  3988. if (!typeInstance->IsTypeMemberAccessible(interfaceEntry.mDeclaringType, mProject))
  3989. continue;
  3990. _InterfaceMatchEntry* matchEntry = NULL;
  3991. if (interfaceMap.TryGetValue(interfaceEntry.mInterfaceType, &matchEntry))
  3992. {
  3993. auto prevEntry = matchEntry->mEntry;
  3994. bool isBetter = TypeIsSubTypeOf(checkTypeInst, matchEntry->mEntrySource);
  3995. bool isWorse = TypeIsSubTypeOf(matchEntry->mEntrySource, checkTypeInst);
  3996. if (forceInterfaceSet)
  3997. {
  3998. isBetter = true;
  3999. isWorse = false;
  4000. }
  4001. if (isBetter == isWorse)
  4002. CompareDeclTypes(interfaceEntry.mDeclaringType, prevEntry->mDeclaringType, isBetter, isWorse);
  4003. if (isBetter == isWorse)
  4004. {
  4005. if (matchEntry->mAmbiguousEntries.empty())
  4006. matchEntry->mAmbiguousEntries.push_back(prevEntry);
  4007. matchEntry->mAmbiguousEntries.push_back(&interfaceEntry);
  4008. continue;
  4009. }
  4010. else if (isBetter)
  4011. {
  4012. matchEntry->mEntry = &interfaceEntry;
  4013. matchEntry->mEntrySource = checkTypeInst;
  4014. matchEntry->mAmbiguousEntries.Clear();
  4015. }
  4016. else
  4017. continue;
  4018. }
  4019. else
  4020. {
  4021. _InterfaceMatchEntry matchEntry;
  4022. matchEntry.mEntry = &interfaceEntry;
  4023. matchEntry.mEntrySource = checkTypeInst;
  4024. interfaceMap[interfaceEntry.mInterfaceType] = matchEntry;
  4025. }
  4026. }
  4027. checkTypeInst = checkTypeInst->GetImplBaseType();
  4028. }
  4029. for (auto interfacePair : interfaceMap)
  4030. {
  4031. auto& interfaceMatchEntry = interfacePair.mValue;
  4032. if (!interfaceMatchEntry.mAmbiguousEntries.empty())
  4033. {
  4034. 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());
  4035. if (error != NULL)
  4036. {
  4037. for (auto ambiguiousEntry : interfaceMatchEntry.mAmbiguousEntries)
  4038. mCompiler->mPassInstance->MoreInfo("See other declaration", ambiguiousEntry->mDeclaringType->GetRefNode());
  4039. }
  4040. }
  4041. }
  4042. if ((!typeInstance->IsInterface()) && (typeInstance->mVirtualMethodTableSize > 0) && (needsVData))
  4043. {
  4044. int startTabIdx = (int)vData.size();
  4045. SizedArray<BfTypeInstance*, 8> origVirtTypeStack;
  4046. BfTypeInstance* checkTypeInst = typeInstance;
  4047. while (checkTypeInst != NULL)
  4048. {
  4049. origVirtTypeStack.push_back(checkTypeInst);
  4050. checkTypeInst = checkTypeInst->GetImplBaseType();
  4051. }
  4052. Array<BfVirtualMethodEntry> origVTable;
  4053. int origVirtIdx = 0;
  4054. if (typeInstance->mTypeDef->mIsCombinedPartial)
  4055. {
  4056. HashSet<String> reslotNames;
  4057. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  4058. {
  4059. auto& entry = typeInstance->mVirtualMethodTable[virtIdx];
  4060. if (entry.mDeclaringMethod.mMethodNum == -1)
  4061. continue;
  4062. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  4063. if ((methodInstance == NULL) || (!typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject)))
  4064. {
  4065. if (origVTable.empty())
  4066. origVTable = typeInstance->mVirtualMethodTable;
  4067. BfMethodInstance* declMethodInstance = entry.mDeclaringMethod;
  4068. if (typeInstance->IsTypeMemberAccessible(declMethodInstance->mMethodDef->mDeclaringType, mProject))
  4069. {
  4070. // Prepare to reslot...
  4071. entry.mImplementingMethod = entry.mDeclaringMethod;
  4072. reslotNames.Add(declMethodInstance->mMethodDef->mName);
  4073. }
  4074. else
  4075. {
  4076. // Decl isn't accessible, null out entry
  4077. entry.mImplementingMethod = BfMethodRef();
  4078. }
  4079. }
  4080. }
  4081. if (!reslotNames.IsEmpty())
  4082. {
  4083. BfAmbiguityContext ambiguityContext;
  4084. ambiguityContext.mTypeInstance = typeInstance;
  4085. ambiguityContext.mModule = this;
  4086. ambiguityContext.mIsProjectSpecific = true;
  4087. ambiguityContext.mIsReslotting = true;
  4088. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  4089. for (auto& methodGroup : typeInstance->mMethodInstanceGroups)
  4090. {
  4091. auto methodInstance = methodGroup.mDefault;
  4092. if ((methodInstance == NULL) || (!methodInstance->mMethodDef->mIsOverride))
  4093. continue;
  4094. if (!reslotNames.Contains(methodInstance->mMethodDef->mName))
  4095. continue;
  4096. if (!typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject))
  4097. continue;
  4098. if ((methodInstance->mChainType != BfMethodChainType_None) && (methodInstance->mChainType != BfMethodChainType_ChainHead))
  4099. continue;
  4100. SlotVirtualMethod(methodInstance, &ambiguityContext);
  4101. }
  4102. ambiguityContext.Finish();
  4103. }
  4104. }
  4105. bool isInExts = false;
  4106. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  4107. {
  4108. BfIRValue vValue = voidPtrNull;
  4109. auto& entry = typeInstance->mVirtualMethodTable[virtIdx];
  4110. BfModuleMethodInstance moduleMethodInst;
  4111. if (entry.mDeclaringMethod.mMethodNum == -1)
  4112. {
  4113. // mMethodNum of -1 indicates a vExt slot rather than an actual method reference
  4114. isInExts = true;
  4115. BfIRValue vExt = CreateClassVDataExtGlobal(entry.mDeclaringMethod.mTypeInstance, typeInstance, virtIdx);
  4116. if (vExt)
  4117. vValue = mBfIRBuilder->CreateBitCast(vExt, voidPtrIRType);
  4118. }
  4119. else
  4120. {
  4121. BfMethodInstance* declaringMethodInstance = (BfMethodInstance*)entry.mDeclaringMethod;
  4122. if ((declaringMethodInstance != NULL) && (declaringMethodInstance->mMethodInstanceGroup->IsImplemented()) && (declaringMethodInstance->mIsReified))
  4123. {
  4124. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].IsImplemented());
  4125. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].mDefault->mIsReified);
  4126. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  4127. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  4128. {
  4129. BF_ASSERT(typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject));
  4130. moduleMethodInst = GetMethodInstanceAtIdx(methodInstance->mMethodInstanceGroup->mOwner, methodInstance->mMethodInstanceGroup->mMethodIdx);
  4131. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  4132. vValue = funcPtr;
  4133. }
  4134. }
  4135. }
  4136. while (origVirtTypeStack.size() != 0)
  4137. {
  4138. BfTypeInstance* useTypeInst = origVirtTypeStack[origVirtTypeStack.size() - 1];
  4139. if (virtIdx >= useTypeInst->mVirtualMethodTableSize)
  4140. {
  4141. // Moved past current base vtable size
  4142. origVirtTypeStack.pop_back();
  4143. continue;
  4144. }
  4145. if (origVirtIdx < useTypeInst->GetOrigVTableSize())
  4146. {
  4147. // We are within the original vtable size
  4148. int idx = startTabIdx + origVirtIdx;
  4149. origVirtIdx++;
  4150. vData.push_back(vValue);
  4151. }
  4152. else
  4153. {
  4154. // This is a new entry, it only gets added to the ext
  4155. BF_ASSERT(isInExts);
  4156. }
  4157. break;
  4158. }
  4159. }
  4160. if (!origVTable.empty())
  4161. typeInstance->mVirtualMethodTable = origVTable;
  4162. }
  4163. int ifaceMethodExtStart = (int)typeInstance->GetIFaceVMethodSize();
  4164. if (typeInstance->mHotTypeData != NULL)
  4165. {
  4166. if (typeInstance->mHotTypeData->mOrigInterfaceMethodsLength != -1)
  4167. ifaceMethodExtStart = typeInstance->mHotTypeData->mOrigInterfaceMethodsLength;
  4168. }
  4169. SizedArray<BfIRValue, 32> ifaceMethodExtData;
  4170. int iFaceMethodStartIdx = (int)vData.size();
  4171. vData.resize(iFaceMethodStartIdx + ifaceMethodExtStart);
  4172. for (int i = iFaceMethodStartIdx; i < iFaceMethodStartIdx + ifaceMethodExtStart; i++)
  4173. vData[i] = voidPtrNull;
  4174. if (expectNumElements != 0)
  4175. BF_ASSERT(expectNumElements == vData.size());
  4176. //BF_ASSERT(vData.size() == expectNumElements);
  4177. // for (int i = 0; i < (int)typeInstance->mInterfaceMethodTable.size() - ifaceMethodExtStart; i++)
  4178. // ifaceMethodExtData.Add(voidPtrNull);
  4179. int ifaceEntryIdx = iFaceMethodStartIdx;
  4180. for (auto& interfacePair : interfaceMap)
  4181. {
  4182. auto interfaceEntry = interfacePair.mValue.mEntry;
  4183. bool makeEmpty = false;
  4184. if (!typeInstance->IsTypeMemberAccessible(interfaceEntry->mDeclaringType, mProject))
  4185. makeEmpty = true;
  4186. int endVirtualIdx = interfaceEntry->mStartVirtualIdx + interfaceEntry->mInterfaceType->mVirtualMethodTableSize;
  4187. bool useExt = endVirtualIdx > ifaceMethodExtStart;
  4188. for (int methodIdx = 0; methodIdx < (int)interfaceEntry->mInterfaceType->mMethodInstanceGroups.size(); methodIdx++)
  4189. {
  4190. BfIRValue pushValue;
  4191. BfMethodInstance* ifaceMethodInstance = interfaceEntry->mInterfaceType->mMethodInstanceGroups[methodIdx].mDefault;
  4192. if ((ifaceMethodInstance == NULL) || (ifaceMethodInstance->mVirtualTableIdx == -1))
  4193. continue;
  4194. if ((!ifaceMethodInstance->mIsReified) || (!ifaceMethodInstance->mMethodInstanceGroup->IsImplemented()))
  4195. continue;
  4196. if (makeEmpty)
  4197. {
  4198. pushValue = voidPtrNull;
  4199. }
  4200. else
  4201. {
  4202. auto& methodRef = typeInstance->mInterfaceMethodTable[interfaceEntry->mStartInterfaceTableIdx + methodIdx].mMethodRef;
  4203. auto methodInstance = (BfMethodInstance*)methodRef;
  4204. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  4205. {
  4206. BF_ASSERT(methodInstance->mIsReified);
  4207. // This doesn't work because we may have FOREIGN methods from implicit interface methods
  4208. //auto moduleMethodInst = GetMethodInstanceAtIdx(methodRef.mTypeInstance, methodRef.mMethodNum);
  4209. auto moduleMethodInst = ReferenceExternalMethodInstance(methodInstance);
  4210. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  4211. pushValue = funcPtr;
  4212. }
  4213. else
  4214. {
  4215. pushValue = voidPtrNull;
  4216. }
  4217. }
  4218. int idx = interfaceEntry->mStartVirtualIdx + ifaceMethodInstance->mVirtualTableIdx;
  4219. if (idx < ifaceMethodExtStart)
  4220. {
  4221. BF_ASSERT(iFaceMethodStartIdx + idx < (int)vData.size());
  4222. vData[iFaceMethodStartIdx + idx] = pushValue;
  4223. }
  4224. else
  4225. {
  4226. BF_ASSERT(useExt);
  4227. int extIdx = idx - ifaceMethodExtStart;
  4228. while (extIdx >= ifaceMethodExtData.size())
  4229. ifaceMethodExtData.Add(voidPtrNull);
  4230. ifaceMethodExtData[extIdx] = pushValue;
  4231. }
  4232. }
  4233. }
  4234. if (typeInstance->IsBoxed())
  4235. {
  4236. BfBoxedType* boxedType = (BfBoxedType*)typeInstance;
  4237. if (boxedType->IsBoxedStructPtr())
  4238. {
  4239. // Force override of GetHashCode so we use the pointer address as the hash code
  4240. checkTypeInst = CreateBoxedType(ResolveTypeDef(mCompiler->mPointerTypeDef));
  4241. // Force override of GetHashCode so we use the pointer address as the hash code
  4242. for (auto& checkIFace : checkTypeInst->mInterfaces)
  4243. {
  4244. for (int methodIdx = 0; methodIdx < (int)checkIFace.mInterfaceType->mMethodInstanceGroups.size(); methodIdx++)
  4245. {
  4246. BfIRValue pushValue;
  4247. BfMethodInstance* ifaceMethodInstance = checkIFace.mInterfaceType->mMethodInstanceGroups[methodIdx].mDefault;
  4248. if ((ifaceMethodInstance == NULL) || (ifaceMethodInstance->mVirtualTableIdx == -1))
  4249. continue;
  4250. if ((!ifaceMethodInstance->mIsReified) || (!ifaceMethodInstance->mMethodInstanceGroup->IsImplemented()))
  4251. continue;
  4252. auto& methodRef = checkTypeInst->mInterfaceMethodTable[checkIFace.mStartInterfaceTableIdx + methodIdx].mMethodRef;
  4253. auto methodInstance = (BfMethodInstance*)methodRef;
  4254. BF_ASSERT(methodInstance->mIsReified);
  4255. // This doesn't work because we may have FOREIGN methods from implicit interface methods
  4256. //auto moduleMethodInst = GetMethodInstanceAtIdx(methodRef.mTypeInstance, methodRef.mMethodNum);
  4257. auto moduleMethodInst = ReferenceExternalMethodInstance(methodInstance);
  4258. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  4259. int idx = checkIFace.mStartVirtualIdx + ifaceMethodInstance->mVirtualTableIdx;
  4260. vData[iFaceMethodStartIdx + idx] = funcPtr;
  4261. }
  4262. }
  4263. }
  4264. }
  4265. if ((needsVData) && (!typeInstance->mTypeDef->mIsStatic))
  4266. {
  4267. BfIRValue ifaceMethodExtVar;
  4268. if (!ifaceMethodExtData.IsEmpty())
  4269. {
  4270. StringT<128> classVDataName;
  4271. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), typeInstance, "bf_hs_replace_IFaceExt");
  4272. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), (int)ifaceMethodExtData.size());
  4273. ifaceMethodExtVar = mBfIRBuilder->CreateGlobalVariable(arrayType, true,
  4274. BfIRLinkageType_External, BfIRValue(), classVDataName);
  4275. BfIRType extVTableType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)ifaceMethodExtData.size());
  4276. BfIRValue extVTableConst = mBfIRBuilder->CreateConstArray(extVTableType, ifaceMethodExtData);
  4277. mBfIRBuilder->GlobalVar_SetInitializer(ifaceMethodExtVar, extVTableConst);
  4278. }
  4279. for (auto& ifaceInstPair : interfaceMap)
  4280. {
  4281. auto interfaceEntry = ifaceInstPair.mValue.mEntry;
  4282. int slotNum = interfaceEntry->mInterfaceType->mSlotNum;
  4283. if (slotNum >= 0)
  4284. {
  4285. BfIRValue vtablePtr;
  4286. int idx = interfaceEntry->mStartVirtualIdx;
  4287. int endVirtualIdx = interfaceEntry->mStartVirtualIdx + interfaceEntry->mInterfaceType->mVirtualMethodTableSize;
  4288. if (endVirtualIdx > ifaceMethodExtStart)
  4289. vtablePtr = mBfIRBuilder->CreateInBoundsGEP(ifaceMethodExtVar, 0, interfaceEntry->mStartVirtualIdx - ifaceMethodExtStart);
  4290. else
  4291. vtablePtr = mBfIRBuilder->CreateInBoundsGEP(classVDataVar, 0, iFaceMethodStartIdx + interfaceEntry->mStartVirtualIdx);
  4292. int slotVirtIdx = slotNum + vDataOfs;
  4293. if (vData[slotVirtIdx] == voidPtrNull)
  4294. {
  4295. vData[slotVirtIdx] = mBfIRBuilder->CreateBitCast(vtablePtr, voidPtrIRType);
  4296. }
  4297. else
  4298. {
  4299. if (mCompiler->IsHotCompile())
  4300. Fail("Interface slot collision error. Restart program or undo interface changes.", typeDef->GetRefNode());
  4301. else
  4302. Fail("Interface slot collision error", typeDef->GetRefNode());
  4303. }
  4304. }
  4305. }
  4306. }
  4307. }
  4308. BfIRValue typeNameConst;
  4309. BfIRValue namespaceConst;
  4310. if (needsTypeNames)
  4311. {
  4312. typeNameConst = GetStringObjectValue(typeDef->mName->mString, true);
  4313. namespaceConst = GetStringObjectValue(typeDef->mNamespace.ToString(), true);
  4314. }
  4315. else
  4316. {
  4317. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  4318. typeNameConst = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(stringType));
  4319. namespaceConst = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(stringType));
  4320. }
  4321. int baseTypeId = 0;
  4322. if (typeInstance->mBaseType != NULL)
  4323. {
  4324. baseTypeId = typeInstance->mBaseType->mTypeId;
  4325. }
  4326. SizedArray<BfIRValue, 16> customAttrs;
  4327. BfTypeInstance* attributeType = mContext->mUnreifiedModule->ResolveTypeDef(mCompiler->mAttributeTypeDef)->ToTypeInstance();
  4328. BfIRValue castedClassVData;
  4329. if (classVDataVar)
  4330. castedClassVData = mBfIRBuilder->CreateBitCast(classVDataVar, mBfIRBuilder->MapType(mContext->mBfClassVDataPtrType));
  4331. else
  4332. castedClassVData = GetDefaultValue(mContext->mBfClassVDataPtrType);
  4333. bool freflectIncludeTypeData = false;
  4334. bool reflectIncludeAllFields = false;
  4335. bool reflectIncludeAllMethods = false;
  4336. if (TypeIsSubTypeOf(typeInstance, attributeType))
  4337. {
  4338. reflectIncludeAllFields = true;
  4339. reflectIncludeAllMethods = true;
  4340. }
  4341. enum ReflectKind
  4342. {
  4343. ReflectKind_None = 0,
  4344. ReflectKind_Type = 1,
  4345. ReflectKind_NonStaticFields = 2,
  4346. ReflectKind_StaticFields = 4,
  4347. ReflectKind_DefaultConstructor = 8,
  4348. ReflectKind_Constructors = 0x10,
  4349. ReflectKind_StaticMethods = 0x20,
  4350. ReflectKind_Methods = 0x40,
  4351. ReflectKind_User = 0x80,
  4352. ReflectKind_All = 0x7F,
  4353. ReflectKind_ApplyToInnerTypes = 0x80
  4354. };
  4355. ReflectKind reflectKind = ReflectKind_Type;
  4356. auto _GetReflectUser = [&](BfTypeInstance* attrType)
  4357. {
  4358. ReflectKind reflectKind = ReflectKind_None;
  4359. if (attrType->mCustomAttributes != NULL)
  4360. {
  4361. for (auto& customAttr : attrType->mCustomAttributes->mAttributes)
  4362. {
  4363. if (customAttr.mType->mTypeDef->mName->ToString() == "AttributeUsageAttribute")
  4364. {
  4365. for (auto& prop : customAttr.mSetProperties)
  4366. {
  4367. auto propDef = prop.mPropertyRef.mTypeInstance->mTypeDef->mProperties[prop.mPropertyRef.mPropIdx];
  4368. if (propDef->mName == "ReflectUser")
  4369. {
  4370. if (prop.mParam.mValue.IsConst())
  4371. {
  4372. auto constant = attrType->mConstHolder->GetConstant(prop.mParam.mValue);
  4373. reflectKind = (ReflectKind)(reflectKind | (ReflectKind)constant->mInt32);
  4374. }
  4375. }
  4376. }
  4377. // Check for Flags arg
  4378. if (customAttr.mCtorArgs.size() < 2)
  4379. continue;
  4380. auto constant = attrType->mConstHolder->GetConstant(customAttr.mCtorArgs[1]);
  4381. if (constant == NULL)
  4382. continue;
  4383. if (constant->mTypeCode == BfTypeCode_Boolean)
  4384. continue;
  4385. if ((constant->mInt8 & BfCustomAttributeFlags_ReflectAttribute) != 0)
  4386. reflectKind = (ReflectKind)(reflectKind | ReflectKind_User);
  4387. }
  4388. }
  4389. }
  4390. return reflectKind;
  4391. };
  4392. auto _GetReflectUserFromDirective = [&](BfAttributeDirective* attributesDirective, BfAttributeTargets attrTarget)
  4393. {
  4394. ReflectKind reflectKind = ReflectKind_None;
  4395. auto customAttrs = GetCustomAttributes(attributesDirective, attrTarget);
  4396. if (customAttrs != NULL)
  4397. {
  4398. for (auto& attr : customAttrs->mAttributes)
  4399. {
  4400. reflectKind = (ReflectKind)(reflectKind | _GetReflectUser(attr.mType));
  4401. }
  4402. }
  4403. return reflectKind;
  4404. };
  4405. //
  4406. {
  4407. auto checkTypeInstance = typeInstance;
  4408. while (checkTypeInstance != NULL)
  4409. {
  4410. if (checkTypeInstance->mCustomAttributes != NULL)
  4411. {
  4412. auto checkReflectKind = ReflectKind_None;
  4413. for (auto& customAttr : checkTypeInstance->mCustomAttributes->mAttributes)
  4414. {
  4415. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  4416. {
  4417. if (customAttr.mCtorArgs.size() > 0)
  4418. {
  4419. auto constant = checkTypeInstance->mConstHolder->GetConstant(customAttr.mCtorArgs[0]);
  4420. checkReflectKind = (ReflectKind)((int)checkReflectKind | constant->mInt32);
  4421. }
  4422. else
  4423. {
  4424. checkReflectKind = ReflectKind_All;
  4425. }
  4426. }
  4427. else
  4428. {
  4429. auto userReflectKind = _GetReflectUser(customAttr.mType);
  4430. checkReflectKind = (ReflectKind)(checkReflectKind | userReflectKind);
  4431. }
  4432. }
  4433. if ((checkTypeInstance == typeInstance) ||
  4434. ((checkReflectKind & ReflectKind_ApplyToInnerTypes) != 0))
  4435. {
  4436. reflectKind = (ReflectKind)(reflectKind | checkReflectKind);
  4437. }
  4438. }
  4439. checkTypeInstance = GetOuterType(checkTypeInstance);
  4440. }
  4441. }
  4442. // Fields
  4443. BfType* reflectFieldDataType = ResolveTypeDef(mCompiler->mReflectFieldDataDef);
  4444. BfIRValue emptyValueType = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance()->mBaseType), SizedArray<BfIRValue, 1>());
  4445. auto _HandleCustomAttrs = [&](BfCustomAttributes* customAttributes)
  4446. {
  4447. if (customAttributes == NULL)
  4448. return -1;
  4449. Array<BfCustomAttribute*> reflectAttributes;
  4450. for (auto& attr : customAttributes->mAttributes)
  4451. {
  4452. bool wantAttribute = false;
  4453. if (attr.mType->mCustomAttributes != NULL)
  4454. {
  4455. auto usageAttribute = attr.mType->mCustomAttributes->Get(mCompiler->mAttributeUsageAttributeTypeDef);
  4456. if (usageAttribute != NULL)
  4457. {
  4458. // Check for Flags arg
  4459. if (usageAttribute->mCtorArgs.size() < 2)
  4460. continue;
  4461. auto constant = attr.mType->mConstHolder->GetConstant(usageAttribute->mCtorArgs[1]);
  4462. if (constant == NULL)
  4463. continue;
  4464. if (constant->mTypeCode == BfTypeCode_Boolean)
  4465. continue;
  4466. if ((constant->mInt8 & BfCustomAttributeFlags_ReflectAttribute) != 0)
  4467. wantAttribute = true;
  4468. }
  4469. }
  4470. if ((wantAttribute) && (attr.mType->mIsReified))
  4471. {
  4472. reflectAttributes.Add(&attr);
  4473. }
  4474. }
  4475. if (reflectAttributes.size() == 0)
  4476. return -1;
  4477. #define PUSH_INT8(val) data.push_back((uint8)val)
  4478. #define PUSH_INT16(val) { data.push_back(val & 0xFF); data.push_back((val >> 8) & 0xFF); }
  4479. #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); }
  4480. #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); \
  4481. data.push_back((val >> 32) & 0xFF); data.push_back((val >> 40) & 0xFF); data.push_back((val >> 48) & 0xFF); data.push_back((val >> 56) & 0xFF); }
  4482. SizedArray<uint8, 16> data;
  4483. int customAttrIdx = (int)customAttrs.size();
  4484. data.push_back((uint8)reflectAttributes.size());
  4485. for (auto attr : reflectAttributes)
  4486. {
  4487. // Size prefix
  4488. int sizeIdx = (int)data.size();
  4489. PUSH_INT16(0); // mSize
  4490. PUSH_INT32(attr->mType->mTypeId); // mType
  4491. PUSH_INT16(attr->mCtor->mIdx);
  4492. auto ctorMethodInstance = GetRawMethodInstanceAtIdx(attr->mType, attr->mCtor->mIdx);
  4493. int argIdx = 0;
  4494. for (auto arg : attr->mCtorArgs)
  4495. {
  4496. auto constant = typeInstance->mConstHolder->GetConstant(arg);
  4497. bool handled = false;
  4498. if (constant != NULL)
  4499. {
  4500. auto argType = ctorMethodInstance->GetParamType(argIdx);
  4501. if (argType->IsObject())
  4502. {
  4503. BF_ASSERT(argType->ToTypeInstance()->mTypeDef == mCompiler->mStringTypeDef);
  4504. int stringId = constant->mInt32;
  4505. int* orderedIdPtr;
  4506. if (usedStringIdMap.TryAdd(stringId, NULL, &orderedIdPtr))
  4507. {
  4508. *orderedIdPtr = (int)usedStringIdMap.size() - 1;
  4509. }
  4510. GetStringObjectValue(stringId);
  4511. PUSH_INT8(0xFF); // String
  4512. PUSH_INT32(*orderedIdPtr);
  4513. continue;
  4514. }
  4515. PUSH_INT8(constant->mTypeCode);
  4516. if ((constant->mTypeCode == BfTypeCode_Int64) ||
  4517. (constant->mTypeCode == BfTypeCode_UInt64) ||
  4518. (constant->mTypeCode == BfTypeCode_Double))
  4519. {
  4520. PUSH_INT64(constant->mInt64);
  4521. }
  4522. else if ((constant->mTypeCode == BfTypeCode_Int32) ||
  4523. (constant->mTypeCode == BfTypeCode_UInt32))
  4524. {
  4525. PUSH_INT32(constant->mInt32);
  4526. }
  4527. else if (constant->mTypeCode == BfTypeCode_Single)
  4528. {
  4529. float val = (float)constant->mDouble;
  4530. PUSH_INT32(*(int*)&val);
  4531. }
  4532. else if ((constant->mTypeCode == BfTypeCode_Int16) ||
  4533. (constant->mTypeCode == BfTypeCode_UInt16))
  4534. {
  4535. PUSH_INT16(constant->mInt16);
  4536. }
  4537. else if ((constant->mTypeCode == BfTypeCode_Int8) ||
  4538. (constant->mTypeCode == BfTypeCode_UInt8))
  4539. {
  4540. PUSH_INT8(constant->mInt8);
  4541. }
  4542. else if (constant->mTypeCode == BfTypeCode_Object)
  4543. {
  4544. BF_FATAL("Unhandled");
  4545. }
  4546. else
  4547. {
  4548. BF_FATAL("Unhandled");
  4549. }
  4550. }
  4551. else if (!handled)
  4552. {
  4553. BF_FATAL("Unhandled");
  4554. }
  4555. argIdx++;
  4556. }
  4557. int size = (int)data.size() - sizeIdx;
  4558. *((uint16*)&data[sizeIdx]) = size;
  4559. }
  4560. #undef PUSH_INT8
  4561. #undef PUSH_INT16
  4562. #undef PUSH_INT32
  4563. SizedArray<BfIRValue, 16> dataValues;
  4564. for (uint8 val : data)
  4565. dataValues.push_back(GetConstValue8(val));
  4566. auto dataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(byteType), (int)data.size());
  4567. auto customAttrConst = mBfIRBuilder->CreateConstArray(dataArrayType, dataValues);
  4568. BfIRValue customAttrArray = mBfIRBuilder->CreateGlobalVariable(dataArrayType, true, BfIRLinkageType_Internal,
  4569. customAttrConst, typeDataName + StrFormat(".customAttr%d", customAttrIdx));
  4570. BfIRValue customAttrArrayPtr = mBfIRBuilder->CreateBitCast(customAttrArray, voidPtrIRType);
  4571. customAttrs.push_back(customAttrArrayPtr);
  4572. return customAttrIdx;
  4573. };
  4574. int typeCustomAttrIdx = _HandleCustomAttrs(typeInstance->mCustomAttributes);
  4575. SizedArray<int, 16> reflectFieldIndices;
  4576. for (int pass = 0; pass < 2; pass++)
  4577. {
  4578. bool skippedField = false;
  4579. reflectFieldIndices.clear();
  4580. for (int fieldIdx = 0; fieldIdx < (int)typeInstance->mFieldInstances.size(); fieldIdx++)
  4581. {
  4582. BfFieldInstance* fieldInstance = &typeInstance->mFieldInstances[fieldIdx];
  4583. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  4584. if (fieldDef == NULL)
  4585. continue;
  4586. auto fieldReflectKind = (ReflectKind)(reflectKind & ~ReflectKind_User);
  4587. bool includeField = reflectIncludeAllFields;
  4588. if (fieldInstance->mCustomAttributes != NULL)
  4589. {
  4590. for (auto& customAttr : fieldInstance->mCustomAttributes->mAttributes)
  4591. {
  4592. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  4593. {
  4594. includeField = true;
  4595. }
  4596. else
  4597. {
  4598. auto userReflectKind = _GetReflectUser(customAttr.mType);
  4599. fieldReflectKind = (ReflectKind)(fieldReflectKind | userReflectKind);
  4600. }
  4601. }
  4602. }
  4603. if ((fieldReflectKind & ReflectKind_User) != 0)
  4604. includeField = true;
  4605. if ((!fieldDef->mIsStatic) && ((fieldReflectKind & ReflectKind_NonStaticFields) != 0))
  4606. includeField = true;
  4607. if ((fieldDef->mIsStatic) && ((fieldReflectKind & ReflectKind_StaticFields) != 0))
  4608. includeField = true;
  4609. includeField |= forceReflectFields;
  4610. if (!includeField)
  4611. {
  4612. skippedField = true;
  4613. continue;
  4614. }
  4615. reflectFieldIndices.Add(fieldIdx);
  4616. }
  4617. // For a splattable type, we need to either include all fields or zero fields. This is to allow us to correctly splat
  4618. // params for reflected method calls even if we don't have reflection field info for the splatted type. This is
  4619. // possible because we write out a SplatData structure containing just TypeIds in that case
  4620. if (pass == 0)
  4621. {
  4622. if (!typeInstance->IsSplattable())
  4623. break;
  4624. if (!skippedField)
  4625. break;
  4626. if (reflectFieldIndices.size() == 0)
  4627. break;
  4628. }
  4629. }
  4630. SizedArray<BfIRValue, 16> fieldTypes;
  4631. enum FieldFlags
  4632. {
  4633. FieldFlags_Protected = 3,
  4634. FieldFlags_Public = 6,
  4635. FieldFlags_Static = 0x10,
  4636. FieldFlags_Const = 0x40,
  4637. FieldFlags_SpecialName = 0x80,
  4638. FieldFlags_EnumPayload = 0x100,
  4639. FieldFlags_EnumDiscriminator = 0x200
  4640. };
  4641. if ((typeInstance->IsPayloadEnum()) && (!typeInstance->IsBoxed()))
  4642. {
  4643. BfType* payloadType = typeInstance->GetUnionInnerType();
  4644. if (!payloadType->IsValuelessType())
  4645. {
  4646. BfIRValue payloadNameConst = GetStringObjectValue("$payload", true);
  4647. SizedArray<BfIRValue, 8> payloadFieldVals =
  4648. {
  4649. emptyValueType,
  4650. payloadNameConst, // mName
  4651. GetConstValue(0, longType), // mConstValue
  4652. GetConstValue(0, intType), // mDataOffset
  4653. GetConstValue(payloadType->mTypeId, typeIdType), // mFieldTypeId
  4654. GetConstValue(FieldFlags_SpecialName | FieldFlags_EnumPayload, shortType), // mFlags
  4655. GetConstValue(-1, intType), // mCustomAttributesIdx
  4656. };
  4657. auto payloadFieldData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance(), BfIRPopulateType_Full), payloadFieldVals);
  4658. fieldTypes.push_back(payloadFieldData);
  4659. }
  4660. BfType* dscrType = typeInstance->GetDiscriminatorType();
  4661. BfIRValue dscrNameConst = GetStringObjectValue("$discriminator", true);
  4662. SizedArray<BfIRValue, 8> dscrFieldVals =
  4663. {
  4664. emptyValueType,
  4665. dscrNameConst, // mName
  4666. GetConstValue(0, longType), // mConstValue
  4667. GetConstValue(BF_ALIGN(payloadType->mSize, dscrType->mAlign), intType), // mDataOffset
  4668. GetConstValue(dscrType->mTypeId, typeIdType), // mFieldTypeId
  4669. GetConstValue(FieldFlags_SpecialName | FieldFlags_EnumDiscriminator, shortType), // mFlags
  4670. GetConstValue(-1, intType), // mCustomAttributesIdx
  4671. };
  4672. auto dscrFieldData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance(), BfIRPopulateType_Full), dscrFieldVals);
  4673. fieldTypes.push_back(dscrFieldData);
  4674. }
  4675. for (auto fieldIdx : reflectFieldIndices)
  4676. {
  4677. if (!needsTypeData)
  4678. break;
  4679. BfFieldInstance* fieldInstance = &typeInstance->mFieldInstances[fieldIdx];
  4680. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  4681. BfIRValue fieldNameConst = GetStringObjectValue(fieldDef->mName, true);
  4682. int typeId = 0;
  4683. auto fieldType = fieldInstance->GetResolvedType();
  4684. if (fieldType->IsGenericParam())
  4685. {
  4686. //TODO:
  4687. }
  4688. else
  4689. typeId = fieldType->mTypeId;
  4690. FieldFlags fieldFlags = (FieldFlags)0;
  4691. if (fieldDef->mProtection == BfProtection_Protected)
  4692. fieldFlags = (FieldFlags)(fieldFlags | FieldFlags_Protected);
  4693. if (fieldDef->mProtection == BfProtection_Public)
  4694. fieldFlags = (FieldFlags)(fieldFlags | FieldFlags_Public);
  4695. if (fieldDef->mIsStatic)
  4696. fieldFlags = (FieldFlags)(fieldFlags | FieldFlags_Static);
  4697. if (fieldDef->mIsConst)
  4698. fieldFlags = (FieldFlags)(fieldFlags | FieldFlags_Const);
  4699. int customAttrIdx = _HandleCustomAttrs(fieldInstance->mCustomAttributes);
  4700. BfIRValue constValue = GetConstValue(0, longType);
  4701. if (fieldInstance->GetFieldDef()->mIsConst)
  4702. {
  4703. if (fieldInstance->mConstIdx != -1)
  4704. {
  4705. auto constant = typeInstance->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  4706. constValue = mBfIRBuilder->CreateConst(BfTypeCode_UInt64, constant->mUInt64);
  4707. }
  4708. }
  4709. SizedArray<BfIRValue, 8> fieldVals =
  4710. {
  4711. emptyValueType,
  4712. fieldNameConst, // mName
  4713. constValue, // mConstValue
  4714. GetConstValue(fieldInstance->mDataOffset, intType), // mDataOffset
  4715. GetConstValue(typeId, typeIdType), // mFieldTypeId
  4716. GetConstValue(fieldFlags, shortType), // mFlags
  4717. GetConstValue(customAttrIdx, intType), // mCustomAttributesIdx
  4718. };
  4719. auto fieldData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance(), BfIRPopulateType_Full), fieldVals);
  4720. fieldTypes.push_back(fieldData);
  4721. }
  4722. auto reflectFieldDataIRType = mBfIRBuilder->MapType(reflectFieldDataType);
  4723. BfIRValue fieldDataPtr;
  4724. BfIRType fieldDataPtrType = mBfIRBuilder->GetPointerTo(reflectFieldDataIRType);
  4725. if (fieldTypes.size() == 0)
  4726. {
  4727. if ((type->IsSplattable()) && (type->IsStruct()) && (!type->IsValuelessType()))
  4728. {
  4729. BfTypeInstance* reflectFieldSplatDataType = ResolveTypeDef(mCompiler->mReflectFieldSplatDataDef)->ToTypeInstance();
  4730. SizedArray<BfIRValue, 3> splatTypes;
  4731. SizedArray<BfIRValue, 3> splatOffsets;
  4732. std::function<void(BfType*, int)> _CheckSplat = [&](BfType* checkType, int offset)
  4733. {
  4734. auto checkTypeInstance = checkType->ToTypeInstance();
  4735. if ((checkTypeInstance != NULL) && (checkTypeInstance->IsValueType()) && (checkTypeInstance->IsDataIncomplete()))
  4736. PopulateType(checkTypeInstance);
  4737. if (checkType->IsStruct())
  4738. {
  4739. int dataEnd = offset;
  4740. if (checkTypeInstance->mBaseType != NULL)
  4741. _CheckSplat(checkTypeInstance->mBaseType, offset);
  4742. if (checkTypeInstance->mIsUnion)
  4743. {
  4744. BfType* unionInnerType = checkTypeInstance->GetUnionInnerType();
  4745. _CheckSplat(unionInnerType, offset);
  4746. }
  4747. else
  4748. {
  4749. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  4750. {
  4751. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  4752. if (fieldInstance->mDataIdx >= 0)
  4753. {
  4754. _CheckSplat(fieldInstance->GetResolvedType(), offset + fieldInstance->mDataOffset);
  4755. dataEnd = offset + fieldInstance->mDataOffset + fieldInstance->mResolvedType->mSize;
  4756. }
  4757. }
  4758. }
  4759. if (checkTypeInstance->IsEnum())
  4760. {
  4761. // Add discriminator
  4762. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  4763. if (!checkTypeInstance->mIsPacked)
  4764. dataEnd = BF_ALIGN(dataEnd, dscrType->mAlign);
  4765. _CheckSplat(dscrType, dataEnd);
  4766. }
  4767. }
  4768. else if (checkType->IsMethodRef())
  4769. {
  4770. // auto methodRefType = (BfMethodRefType*)checkType;
  4771. // for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  4772. // {
  4773. // if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  4774. // _CheckSplat(methodRefType->GetCaptureType(dataIdx), offsetof);
  4775. // else
  4776. // dataLambda(methodRefType->GetCaptureType(dataIdx));
  4777. // }
  4778. }
  4779. else if (!checkType->IsValuelessType())
  4780. {
  4781. splatTypes.Add(GetConstValue(checkType->mTypeId, typeIdType));
  4782. splatOffsets.Add(GetConstValue(offset, intType));
  4783. }
  4784. };
  4785. _CheckSplat(type, 0);
  4786. while (splatTypes.size() < 3)
  4787. {
  4788. splatTypes.Add(GetConstValue(0, typeIdType));
  4789. splatOffsets.Add(GetConstValue(0, intType));
  4790. }
  4791. BfIRValue splatTypesConst = mBfIRBuilder->CreateConstArray(mBfIRBuilder->MapType(reflectFieldSplatDataType->mFieldInstances[0].mResolvedType), splatTypes);
  4792. BfIRValue splatOffsetsConst = mBfIRBuilder->CreateConstArray(mBfIRBuilder->MapType(reflectFieldSplatDataType->mFieldInstances[1].mResolvedType), splatOffsets);
  4793. SizedArray<BfIRValue, 8> splatVals =
  4794. {
  4795. emptyValueType,
  4796. splatTypesConst,
  4797. splatOffsetsConst
  4798. };
  4799. auto fieldSplatData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectFieldSplatDataType->ToTypeInstance(), BfIRPopulateType_Full), splatVals);
  4800. BfIRValue fieldDataArray = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(reflectFieldSplatDataType), true, BfIRLinkageType_Internal,
  4801. fieldSplatData, typeDataName + ".splats");
  4802. fieldDataPtr = mBfIRBuilder->CreateBitCast(fieldDataArray, fieldDataPtrType);
  4803. }
  4804. else
  4805. fieldDataPtr = mBfIRBuilder->CreateConstNull(fieldDataPtrType);
  4806. }
  4807. else
  4808. {
  4809. BfIRType fieldDataConstType = mBfIRBuilder->GetSizedArrayType(reflectFieldDataIRType, (int)fieldTypes.size());
  4810. BfIRValue fieldDataConst = mBfIRBuilder->CreateConstArray(fieldDataConstType, fieldTypes);
  4811. BfIRValue fieldDataArray = mBfIRBuilder->CreateGlobalVariable(fieldDataConstType, true, BfIRLinkageType_Internal,
  4812. fieldDataConst, "fields." + typeDataName);
  4813. fieldDataPtr = mBfIRBuilder->CreateBitCast(fieldDataArray, fieldDataPtrType);
  4814. }
  4815. /// Methods
  4816. BfType* reflectMethodDataType = ResolveTypeDef(mCompiler->mReflectMethodDataDef);
  4817. BfType* reflectParamDataType = ResolveTypeDef(mCompiler->mReflectParamDataDef);
  4818. BfType* reflectParamDataPtrType = CreatePointerType(reflectParamDataType);
  4819. SizedArray<BfIRValue, 16> methodTypes;
  4820. for (int methodIdx = 0; methodIdx < (int)typeDef->mMethods.size(); methodIdx++)
  4821. {
  4822. if (!needsTypeData)
  4823. break;
  4824. auto methodInstanceGroup = &typeInstance->mMethodInstanceGroups[methodIdx];
  4825. if (!methodInstanceGroup->IsImplemented())
  4826. continue;
  4827. auto methodDef = typeDef->mMethods[methodIdx];
  4828. if (methodDef->mNoReflect)
  4829. continue;
  4830. auto defaultMethod = methodInstanceGroup->mDefault;
  4831. if (defaultMethod == NULL)
  4832. continue;
  4833. if (defaultMethod->mIsUnspecialized)
  4834. continue;
  4835. if (!defaultMethod->mIsReified)
  4836. continue;
  4837. if ((defaultMethod->mChainType == BfMethodChainType_ChainMember) || (defaultMethod->mChainType == BfMethodChainType_ChainSkip))
  4838. continue;
  4839. if (defaultMethod->mMethodDef->mMethodType == BfMethodType_CtorNoBody)
  4840. continue;
  4841. auto methodReflectKind = (ReflectKind)(reflectKind & ~ReflectKind_User);
  4842. bool includeMethod = reflectIncludeAllMethods;
  4843. BfCustomAttributes* methodCustomAttributes = NULL;
  4844. if ((defaultMethod->mMethodInfoEx != NULL) && (defaultMethod->mMethodInfoEx->mMethodCustomAttributes != NULL) && (defaultMethod->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes != NULL))
  4845. {
  4846. methodCustomAttributes = defaultMethod->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes;
  4847. for (auto& customAttr : defaultMethod->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes->mAttributes)
  4848. {
  4849. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  4850. {
  4851. includeMethod = true;
  4852. }
  4853. else
  4854. {
  4855. auto userReflectKind = _GetReflectUser(customAttr.mType);
  4856. methodReflectKind = (ReflectKind)(methodReflectKind | userReflectKind);
  4857. }
  4858. }
  4859. }
  4860. if (!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, mProject))
  4861. continue;
  4862. if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  4863. {
  4864. for (BfParameterDeclaration* paramDecl : methodDeclaration->mParams)
  4865. {
  4866. if (paramDecl->mAttributes != NULL)
  4867. methodReflectKind = (ReflectKind)(methodReflectKind | _GetReflectUserFromDirective(paramDecl->mAttributes, BfAttributeTargets_Parameter));
  4868. }
  4869. if (methodDeclaration->mReturnAttributes != NULL)
  4870. methodReflectKind = (ReflectKind)(methodReflectKind | _GetReflectUserFromDirective(methodDeclaration->mReturnAttributes, BfAttributeTargets_ReturnValue));
  4871. }
  4872. if ((methodReflectKind & (ReflectKind_Methods | ReflectKind_User)) != 0)
  4873. includeMethod = true;
  4874. if ((methodDef->mIsStatic) && ((methodReflectKind & ReflectKind_StaticMethods) != 0))
  4875. includeMethod = true;
  4876. if (!includeMethod)
  4877. continue;
  4878. BfModuleMethodInstance moduleMethodInstance;
  4879. BfIRValue funcVal = voidPtrNull;
  4880. if (((!typeInstance->IsBoxed()) || (!methodDef->mIsStatic)) &&
  4881. (!typeInstance->IsUnspecializedType()) &&
  4882. (methodDef->mMethodType != BfMethodType_Ignore) &&
  4883. (methodDef->mMethodType != BfMethodType_Mixin) &&
  4884. (!methodDef->mIsAbstract) &&
  4885. (methodDef->mGenericParams.size() == 0))
  4886. {
  4887. moduleMethodInstance = GetMethodInstanceAtIdx(typeInstance, methodIdx);
  4888. if (moduleMethodInstance.mFunc)
  4889. funcVal = mBfIRBuilder->CreateBitCast(moduleMethodInstance.mFunc, voidPtrIRType);
  4890. }
  4891. BfIRValue methodNameConst = GetStringObjectValue(methodDef->mName, true);
  4892. enum MethodFlags
  4893. {
  4894. MethodFlags_Protected = 3,
  4895. MethodFlags_Public = 6,
  4896. MethodFlags_Static = 0x10,
  4897. MethodFlags_Virtual = 0x40,
  4898. MethodFlags_StdCall = 0x1000,
  4899. MethodFlags_FastCall = 0x2000,
  4900. MethodFlags_Mutating = 0x4000,
  4901. };
  4902. MethodFlags methodFlags = (MethodFlags)0;
  4903. if (methodDef->mProtection == BfProtection_Protected)
  4904. methodFlags = (MethodFlags)(methodFlags | MethodFlags_Protected);
  4905. if (methodDef->mProtection == BfProtection_Public)
  4906. methodFlags = (MethodFlags)(methodFlags | MethodFlags_Public);
  4907. if (methodDef->mIsStatic)
  4908. methodFlags = (MethodFlags)(methodFlags | MethodFlags_Static);
  4909. if (methodDef->mIsVirtual)
  4910. methodFlags = (MethodFlags)(methodFlags | MethodFlags_Virtual);
  4911. if (methodDef->mCallingConvention == BfCallingConvention_Fastcall)
  4912. methodFlags = (MethodFlags)(methodFlags | MethodFlags_FastCall);
  4913. if (methodDef->mIsMutating)
  4914. methodFlags = (MethodFlags)(methodFlags | MethodFlags_Mutating);
  4915. int customAttrIdx = _HandleCustomAttrs(methodCustomAttributes);
  4916. enum ParamFlags
  4917. {
  4918. ParamFlag_None = 0,
  4919. ParamFlag_Splat = 1,
  4920. ParamFlag_Implicit = 2,
  4921. };
  4922. SizedArray<BfIRValue, 8> paramVals;
  4923. for (int paramIdx = 0; paramIdx < defaultMethod->GetParamCount(); paramIdx++)
  4924. {
  4925. String paramName = defaultMethod->GetParamName(paramIdx);
  4926. BfType* paramType = defaultMethod->GetParamType(paramIdx);
  4927. ParamFlags paramFlags = ParamFlag_None;
  4928. if (defaultMethod->GetParamIsSplat(paramIdx))
  4929. paramFlags = (ParamFlags)(paramFlags | ParamFlag_Splat);
  4930. BfIRValue paramNameConst = GetStringObjectValue(paramName, true);
  4931. SizedArray<BfIRValue, 8> paramDataVals =
  4932. {
  4933. emptyValueType,
  4934. paramNameConst,
  4935. GetConstValue(paramType->mTypeId, typeIdType),
  4936. GetConstValue((int32)paramFlags, shortType),
  4937. GetConstValue(customAttrIdx, intType) // defaultIdx
  4938. };
  4939. auto paramData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapType(reflectParamDataType, BfIRPopulateType_Full), paramDataVals);
  4940. paramVals.Add(paramData);
  4941. }
  4942. BfIRValue paramsVal;
  4943. if (paramVals.size() > 0)
  4944. {
  4945. BfIRType paramDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(reflectParamDataType, BfIRPopulateType_Full), (int)paramVals.size());
  4946. BfIRValue paramDataConst = mBfIRBuilder->CreateConstArray(paramDataArrayType, paramVals);
  4947. BfIRValue paramDataArray = mBfIRBuilder->CreateGlobalVariable(paramDataArrayType, true, BfIRLinkageType_Internal,
  4948. paramDataConst, typeDataName + StrFormat(".params%d", methodIdx));
  4949. paramsVal = mBfIRBuilder->CreateBitCast(paramDataArray, mBfIRBuilder->MapType(reflectParamDataPtrType));
  4950. }
  4951. else
  4952. paramsVal = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(reflectParamDataPtrType));
  4953. int vDataVal = -1;
  4954. if (defaultMethod->mVirtualTableIdx != -1)
  4955. {
  4956. int vDataIdx = -1;
  4957. vDataIdx = 1 + mCompiler->GetDynCastVDataCount() + mCompiler->mMaxInterfaceSlots;
  4958. if ((mCompiler->mOptions.mHasVDataExtender) && (mCompiler->IsHotCompile()))
  4959. {
  4960. auto typeInst = defaultMethod->mMethodInstanceGroup->mOwner;
  4961. int extMethodIdx = (defaultMethod->mVirtualTableIdx - typeInst->GetBaseVTableSize()) - typeInst->GetOrigSelfVTableSize();
  4962. if (extMethodIdx >= 0)
  4963. {
  4964. // Extension?
  4965. int vExtOfs = typeInst->GetOrigBaseVTableSize();
  4966. vDataVal = ((vDataIdx + vExtOfs + 1) << 20) | (extMethodIdx);
  4967. }
  4968. else
  4969. {
  4970. // Map this new virtual index back to the original index
  4971. vDataIdx += (defaultMethod->mVirtualTableIdx - typeInst->GetBaseVTableSize()) + typeInst->GetOrigBaseVTableSize();
  4972. }
  4973. }
  4974. else
  4975. {
  4976. vDataIdx += defaultMethod->mVirtualTableIdx;
  4977. }
  4978. if (vDataVal == -1)
  4979. vDataVal = vDataIdx * mSystem->mPtrSize;
  4980. }
  4981. SizedArray<BfIRValue, 8> methodDataVals =
  4982. {
  4983. emptyValueType,
  4984. methodNameConst, // mName
  4985. funcVal, // mFuncPtr
  4986. paramsVal,
  4987. GetConstValue(defaultMethod->mReturnType->mTypeId, typeIdType),
  4988. GetConstValue((int)paramVals.size(), shortType),
  4989. GetConstValue(methodFlags, shortType),
  4990. GetConstValue(vDataVal, intType),
  4991. GetConstValue(-1, intType),
  4992. };
  4993. auto methodData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectMethodDataType->ToTypeInstance(), BfIRPopulateType_Full), methodDataVals);
  4994. methodTypes.push_back(methodData);
  4995. }
  4996. BfIRValue methodDataPtr;
  4997. BfIRType methodDataPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(reflectMethodDataType));
  4998. if (methodTypes.size() == 0)
  4999. methodDataPtr = mBfIRBuilder->CreateConstNull(methodDataPtrType);
  5000. else
  5001. {
  5002. BfIRType methodDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(reflectMethodDataType, BfIRPopulateType_Full), (int)methodTypes.size());
  5003. BfIRValue methodDataConst = mBfIRBuilder->CreateConstArray(methodDataArrayType, methodTypes);
  5004. BfIRValue methodDataArray = mBfIRBuilder->CreateGlobalVariable(methodDataArrayType, true, BfIRLinkageType_Internal,
  5005. methodDataConst, "methods." + typeDataName);
  5006. methodDataPtr = mBfIRBuilder->CreateBitCast(methodDataArray, methodDataPtrType);
  5007. }
  5008. /////
  5009. int underlyingType = 0;
  5010. if ((typeInstance->IsTypedPrimitive()) || (typeInstance->IsBoxed()))
  5011. {
  5012. underlyingType = typeInstance->GetUnderlyingType()->mTypeId;
  5013. }
  5014. int outerTypeId = 0;
  5015. auto outerType = GetOuterType(typeInstance);
  5016. if (outerType != NULL)
  5017. outerTypeId = outerType->mTypeId;
  5018. BfIRValue customAttrDataPtr;
  5019. if (customAttrs.size() > 0)
  5020. {
  5021. BfIRType customAttrsArrayType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)customAttrs.size());
  5022. BfIRValue customAttrsConst = mBfIRBuilder->CreateConstArray(customAttrsArrayType, customAttrs);
  5023. BfIRValue customAttrsArray = mBfIRBuilder->CreateGlobalVariable(customAttrsArrayType, true, BfIRLinkageType_Internal,
  5024. customAttrsConst, "customAttrs." + typeDataName);
  5025. customAttrDataPtr = mBfIRBuilder->CreateBitCast(customAttrsArray, voidPtrPtrIRType);
  5026. }
  5027. else
  5028. {
  5029. customAttrDataPtr = mBfIRBuilder->CreateConstNull(voidPtrPtrIRType);
  5030. }
  5031. SizedArray<BfIRValue, 32> typeDataVals =
  5032. {
  5033. typeData,
  5034. castedClassVData, // mTypeClassVData
  5035. typeNameConst, // mName
  5036. namespaceConst, // mNamespace
  5037. GetConstValue(typeInstance->mInstSize, intType), // mInstSize
  5038. GetConstValue(typeInstance->mInstAlign, intType), // mInstAlign
  5039. GetConstValue(typeCustomAttrIdx, intType), // mCustomAttributes
  5040. GetConstValue(baseTypeId, typeIdType), // mBaseType
  5041. GetConstValue(underlyingType, typeIdType), // mUnderlyingType
  5042. GetConstValue(outerTypeId, typeIdType), // mOuterType
  5043. GetConstValue(typeInstance->mInheritanceId, intType), // mInheritanceId
  5044. GetConstValue(typeInstance->mInheritanceCount, intType), // mInheritanceCount
  5045. GetConstValue(typeInstance->mSlotNum, byteType), // mInterfaceSlot
  5046. GetConstValue(0, byteType), // mInterfaceCount
  5047. GetConstValue((int)methodTypes.size(), shortType), // mMethodDataCount
  5048. GetConstValue(0, shortType), // mPropertyDataCount
  5049. GetConstValue((int)fieldTypes.size(), shortType), // mFieldDataCount
  5050. GetConstValue(0, shortType), // mConstructorDataCount
  5051. voidPtrNull, // mInterfaceDataPtr
  5052. methodDataPtr, // mMethodDataPtr
  5053. voidPtrNull, // mPropertyDataPtr
  5054. fieldDataPtr, // mFieldDataPtr
  5055. voidPtrNull, // mConstructorDataPtr
  5056. customAttrDataPtr, // mCustomAttrDataPtr
  5057. };
  5058. BfIRType typeInstanceDataType = mBfIRBuilder->MapTypeInst(typeInstanceType->ToTypeInstance(), BfIRPopulateType_Full);
  5059. auto typeInstanceData = mBfIRBuilder->CreateConstStruct(typeInstanceDataType, typeDataVals);
  5060. if (!needsTypeData)
  5061. {
  5062. // No need for anything beyond typeInstanceData
  5063. }
  5064. else if ((typeInstance->IsGenericTypeInstance()) && (typeInstance->IsUnspecializedType()))
  5065. {
  5066. auto genericTypeInstance = typeInstance->ToGenericTypeInstance();
  5067. SizedArray<BfIRValue, 4> unspecializedData =
  5068. {
  5069. typeInstanceData,
  5070. GetConstValue((int)genericTypeInstance->mTypeGenericArguments.size(), byteType), // mGenericParamCount
  5071. };
  5072. auto reflectUnspecializedGenericType = ResolveTypeDef(mCompiler->mReflectUnspecializedGenericType);
  5073. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectUnspecializedGenericType->ToTypeInstance(), BfIRPopulateType_Full);
  5074. typeInstanceData = mBfIRBuilder->CreateConstStruct(typeInstanceDataType, unspecializedData);
  5075. }
  5076. else if (typeInstance->IsGenericTypeInstance())
  5077. {
  5078. auto genericTypeInstance = typeInstance->ToGenericTypeInstance();
  5079. auto reflectSpecializedGenericType = ResolveTypeDef(mCompiler->mReflectSpecializedGenericType);
  5080. auto unspecializedType = ResolveTypeDef(typeInstance->mTypeDef);
  5081. SizedArray<BfIRValue, 4> resolvedTypes;
  5082. for (auto typeGenericArg : genericTypeInstance->mTypeGenericArguments)
  5083. resolvedTypes.push_back(GetConstValue(typeGenericArg->mTypeId, typeIdType));
  5084. auto typeIRType = mBfIRBuilder->MapType(typeIdType);
  5085. auto typePtrIRType = mBfIRBuilder->GetPointerTo(typeIRType);
  5086. auto genericArrayType = mBfIRBuilder->GetSizedArrayType(typeIRType, (int)resolvedTypes.size());
  5087. BfIRValue resolvedTypesConst = mBfIRBuilder->CreateConstArray(genericArrayType, resolvedTypes);
  5088. BfIRValue resolvedTypesArray = mBfIRBuilder->CreateGlobalVariable(genericArrayType, true, BfIRLinkageType_Internal,
  5089. resolvedTypesConst, "resolvedTypes." + typeDataName);
  5090. BfIRValue resovledTypesPtr = mBfIRBuilder->CreateBitCast(resolvedTypesArray, typePtrIRType);
  5091. SizedArray<BfIRValue, 3> specGenericData =
  5092. {
  5093. typeInstanceData,
  5094. GetConstValue(unspecializedType->mTypeId, typeIdType), // mUnspecialziedType
  5095. resovledTypesPtr, // mFieldDataPtr
  5096. };
  5097. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectSpecializedGenericType->ToTypeInstance(), BfIRPopulateType_Full);
  5098. typeInstanceData = mBfIRBuilder->CreateConstStruct(typeInstanceDataType, specGenericData);
  5099. if (typeInstance->IsArray())
  5100. {
  5101. auto arrayType = (BfArrayType*)typeInstance;
  5102. BfType* elementType = genericTypeInstance->mTypeGenericArguments[0];
  5103. BfFieldInstance* elementFieldInstance = &genericTypeInstance->mFieldInstances[0];
  5104. SizedArray<BfIRValue, 4> arrayData =
  5105. {
  5106. typeInstanceData,
  5107. GetConstValue(elementType->mSize, intType), // mElementSize
  5108. GetConstValue(1, byteType), // mRank
  5109. GetConstValue(elementFieldInstance->mDataOffset, byteType), // mElementsDataOffset
  5110. };
  5111. auto reflectArrayType = ResolveTypeDef(mCompiler->mReflectArrayType);
  5112. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectArrayType->ToTypeInstance(), BfIRPopulateType_Full);
  5113. typeInstanceData = mBfIRBuilder->CreateConstStruct(typeInstanceDataType, arrayData);
  5114. }
  5115. }
  5116. BfIRValue typeDataVar;
  5117. if (needsTypeData)
  5118. {
  5119. typeDataVar = mBfIRBuilder->CreateGlobalVariable(typeInstanceDataType, true,
  5120. BfIRLinkageType_External, typeInstanceData, typeDataName);
  5121. if (mBfIRBuilder->DbgHasInfo())
  5122. {
  5123. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, typeDataName, typeDataName, NULL, 0, mBfIRBuilder->DbgGetTypeInst(typeInstanceType->ToTypeInstance()), false, typeDataVar);
  5124. }
  5125. }
  5126. else
  5127. {
  5128. typeDataVar = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(mContext->mBfTypeType));
  5129. }
  5130. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  5131. mTypeDataRefs[typeInstance] = typeDataVar;
  5132. if (classVDataVar)
  5133. {
  5134. BF_ASSERT(!classVDataName.IsEmpty());
  5135. vData[0] = mBfIRBuilder->CreateBitCast(typeDataVar, voidPtrIRType);
  5136. auto classVDataConstDataType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)vData.size());
  5137. auto classVDataConstData = mBfIRBuilder->CreateConstArray(classVDataConstDataType, vData);
  5138. mBfIRBuilder->GlobalVar_SetInitializer(classVDataVar, classVDataConstData);
  5139. if (mCompiler->mOptions.mObjectHasDebugFlags)
  5140. mBfIRBuilder->GlobalVar_SetAlignment(classVDataVar, 256);
  5141. else
  5142. mBfIRBuilder->GlobalVar_SetAlignment(classVDataVar, mContext->mBfClassVDataPtrType->mAlign);
  5143. if (mBfIRBuilder->DbgHasInfo())
  5144. {
  5145. BfType* voidType = GetPrimitiveType(BfTypeCode_None);
  5146. BfType* voidPtrType = CreatePointerType(voidType);
  5147. BfType* classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  5148. BfIRMDNode arrayType = mBfIRBuilder->DbgCreateArrayType(vData.size() * mSystem->mPtrSize * 8, mSystem->mPtrSize * 8, mBfIRBuilder->DbgGetType(voidPtrType), vData.size());
  5149. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, classVDataName, classVDataName, NULL, 0, arrayType, false, classVDataVar);
  5150. }
  5151. }
  5152. return typeDataVar;
  5153. }
  5154. BfIRValue BfModule::FixClassVData(BfIRValue value)
  5155. {
  5156. if (!mCompiler->mOptions.mObjectHasDebugFlags)
  5157. return value;
  5158. auto intptrValue = mBfIRBuilder->CreatePtrToInt(value, BfTypeCode_IntPtr);
  5159. auto maskedValue = mBfIRBuilder->CreateAnd(intptrValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)~0xFFULL));
  5160. return mBfIRBuilder->CreateIntToPtr(maskedValue, mBfIRBuilder->GetType(value));
  5161. }
  5162. void BfModule::CheckStaticAccess(BfTypeInstance* typeInstance)
  5163. {
  5164. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  5165. //TODO: Create a hashset of these, we don't need to repeatedly call static ctors for a given type
  5166. // When we access classes with static constructors FROM a static constructor,
  5167. // we call that other class's static constructor first. Recursion cannot occur, since
  5168. // we simply ignore subsequent attempts to re-enter the constructor
  5169. if (!typeInstance->mHasStaticInitMethod)
  5170. return;
  5171. if ((mCurMethodInstance == NULL) || ((mCurMethodInstance->mMethodDef->mMethodType != BfMethodType_Ctor) || (!mCurMethodInstance->mMethodDef->mIsStatic)))
  5172. return;
  5173. if (mCurMethodInstance->mMethodInstanceGroup->mOwner == typeInstance)
  5174. return;
  5175. auto checkTypeDef = typeInstance->mTypeDef;
  5176. checkTypeDef->PopulateMemberSets();
  5177. BfMethodDef* nextMethodDef = NULL;
  5178. BfMemberSetEntry* entry;
  5179. if (checkTypeDef->mMethodSet.TryGetWith(String("__BfStaticCtor"), &entry))
  5180. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  5181. while (nextMethodDef != NULL)
  5182. {
  5183. auto checkMethod = nextMethodDef;
  5184. nextMethodDef = nextMethodDef->mNextWithSameName;
  5185. auto methodModule = GetMethodInstance(typeInstance, checkMethod, BfTypeVector());
  5186. if (methodModule)
  5187. {
  5188. auto methodInstance = methodModule.mMethodInstance;
  5189. if ((methodInstance != NULL) &&
  5190. (methodInstance->mMethodDef->mIsStatic) &&
  5191. (methodInstance->mMethodDef->mMethodType == BfMethodType_Ctor) &&
  5192. ((methodInstance->mChainType == BfMethodChainType_ChainHead) || (methodInstance->mChainType == BfMethodChainType_None)))
  5193. {
  5194. mBfIRBuilder->CreateCall(methodModule.mFunc, SizedArray<BfIRValue, 0>());
  5195. break;
  5196. }
  5197. }
  5198. }
  5199. }
  5200. BfIRFunction BfModule::GetIntrinsic(BfMethodInstance* methodInstance, bool reportFailure)
  5201. {
  5202. auto methodOwner = methodInstance->GetOwner();
  5203. auto methodDef = methodInstance->mMethodDef;
  5204. auto methodDeclaration = methodDef->GetMethodDeclaration();
  5205. bool hasExternSpecifier = (methodDeclaration != NULL) && (methodDeclaration->mExternSpecifier != NULL);
  5206. if (!hasExternSpecifier)
  5207. return BfIRFunction();
  5208. if (methodInstance->GetCustomAttributes() == NULL)
  5209. return BfIRFunction();
  5210. for (auto& customAttribute : methodInstance->GetCustomAttributes()->mAttributes)
  5211. {
  5212. String typeName = TypeToString(customAttribute.mType);
  5213. if ((typeName == "System.IntrinsicAttribute") && (customAttribute.mCtorArgs.size() > 0))
  5214. {
  5215. methodInstance->mIsIntrinsic = true;
  5216. auto constant = methodOwner->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  5217. String error;
  5218. if ((constant != NULL) && (BfIRConstHolder::IsInt(constant->mTypeCode)))
  5219. {
  5220. int stringId = constant->mInt32;
  5221. auto entry = mContext->mStringObjectIdMap[stringId];
  5222. int intrinId = BfIRCodeGen::GetIntrinsicId(entry.mString);
  5223. if (intrinId != -1)
  5224. {
  5225. if (intrinId == BfIRIntrinsic_Malloc)
  5226. {
  5227. return GetBuiltInFunc(BfBuiltInFuncType_Malloc);
  5228. }
  5229. else if (intrinId == BfIRIntrinsic_Free)
  5230. {
  5231. return GetBuiltInFunc(BfBuiltInFuncType_Free);
  5232. }
  5233. SizedArray<BfIRType, 2> paramTypes;
  5234. for (auto& param : methodInstance->mParams)
  5235. paramTypes.push_back(mBfIRBuilder->MapType(param.mResolvedType));
  5236. return mBfIRBuilder->GetIntrinsic(intrinId, paramTypes);
  5237. }
  5238. else if (reportFailure)
  5239. error = StrFormat("Unable to find intrinsic '%s'", entry.mString.c_str());
  5240. }
  5241. else if (reportFailure)
  5242. error = "Intrinsic name must be a constant string";
  5243. if (reportFailure)
  5244. {
  5245. BfAstNode* ref = methodDeclaration->mAttributes;
  5246. Fail(error, ref);
  5247. }
  5248. }
  5249. }
  5250. return BfIRFunction();
  5251. }
  5252. BfIRFunction BfModule::GetBuiltInFunc(BfBuiltInFuncType funcTypeId)
  5253. {
  5254. if (mBfIRBuilder->mIgnoreWrites)
  5255. return mBfIRBuilder->GetFakeFunction();
  5256. if (!mBuiltInFuncs[(int)funcTypeId])
  5257. {
  5258. SizedArray<BfIRType, 4> paramTypes;
  5259. auto nullPtrType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr));
  5260. auto intType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_IntPtr));
  5261. auto int32Type = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int32));
  5262. auto intPtrType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_IntPtr));
  5263. auto byteType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int8));
  5264. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  5265. auto objType = mBfIRBuilder->MapType(mContext->mBfObjectType);
  5266. BfIRFunctionType funcType;
  5267. BfIRFunction func;
  5268. switch (funcTypeId)
  5269. {
  5270. case BfBuiltInFuncType_PrintF:
  5271. funcType = mBfIRBuilder->CreateFunctionType(int32Type, paramTypes, true);
  5272. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, "PrintF");
  5273. break;
  5274. case BfBuiltInFuncType_Malloc:
  5275. {
  5276. if (mCompiler->mOptions.mDebugAlloc)
  5277. {
  5278. func = GetInternalMethod("Dbg_RawAlloc", 1).mFunc;
  5279. }
  5280. else
  5281. {
  5282. String funcName = mCompiler->mOptions.mMallocLinkName;
  5283. if (funcName.IsEmpty())
  5284. funcName = "malloc";
  5285. func = mBfIRBuilder->GetFunction(funcName);
  5286. if (!func)
  5287. {
  5288. paramTypes.clear();
  5289. paramTypes.push_back(intType);
  5290. funcType = mBfIRBuilder->CreateFunctionType(nullPtrType, paramTypes);
  5291. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, funcName);
  5292. mBfIRBuilder->Func_SetParamName(func, 1, "size");
  5293. }
  5294. }
  5295. }
  5296. break;
  5297. case BfBuiltInFuncType_Free:
  5298. {
  5299. if (mCompiler->mOptions.mDebugAlloc)
  5300. {
  5301. func = GetInternalMethod("Dbg_RawFree").mFunc;
  5302. }
  5303. else
  5304. {
  5305. String funcName = mCompiler->mOptions.mFreeLinkName;
  5306. if (funcName.IsEmpty())
  5307. funcName = "free";
  5308. func = mBfIRBuilder->GetFunction(funcName);
  5309. if (!func)
  5310. {
  5311. paramTypes.clear();
  5312. paramTypes.push_back(nullPtrType);
  5313. funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  5314. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, funcName);
  5315. mBfIRBuilder->Func_SetParamName(func, 1, "ptr");
  5316. }
  5317. }
  5318. }
  5319. break;
  5320. case BfBuiltInFuncType_LoadSharedLibraries:
  5321. paramTypes.clear();
  5322. funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  5323. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, "BfLoadSharedLibraries");
  5324. break;
  5325. }
  5326. mBuiltInFuncs[(int)funcTypeId] = func;
  5327. return func;
  5328. }
  5329. return mBuiltInFuncs[(int)funcTypeId];
  5330. }
  5331. void BfModule::ResolveGenericParamConstraints(BfGenericParamInstance* genericParamInstance, const Array<BfGenericParamDef*>& genericParamDefs, int genericParamIdx)
  5332. {
  5333. BfGenericParamDef* genericParamDef = genericParamDefs[genericParamIdx];
  5334. BfType* startingTypeConstraint = genericParamInstance->mTypeConstraint;
  5335. BfAutoComplete* bfAutocomplete = NULL;
  5336. if (mCompiler->mResolvePassData != NULL)
  5337. bfAutocomplete = mCompiler->mResolvePassData->mAutoComplete;
  5338. if (bfAutocomplete != NULL)
  5339. {
  5340. for (int nameIdx = 0; nameIdx < (int)genericParamDef->mNameNodes.size(); nameIdx++)
  5341. {
  5342. auto nameNode = genericParamDef->mNameNodes[nameIdx];
  5343. if (bfAutocomplete->IsAutocompleteNode(nameNode))
  5344. {
  5345. String filter = nameNode->ToString();
  5346. bfAutocomplete->mInsertStartIdx = nameNode->GetSrcStart();
  5347. bfAutocomplete->mInsertEndIdx = nameNode->GetSrcEnd();
  5348. if (nameIdx != 0)
  5349. {
  5350. for (auto checkGenericParam : genericParamDefs)
  5351. bfAutocomplete->AddEntry(AutoCompleteEntry("generic", checkGenericParam->mName.c_str()), filter);
  5352. }
  5353. }
  5354. }
  5355. }
  5356. for (auto constraintTypeRef : genericParamDef->mInterfaceConstraints)
  5357. {
  5358. if (bfAutocomplete != NULL)
  5359. bfAutocomplete->CheckTypeRef(constraintTypeRef, true);
  5360. //TODO: Constraints may refer to other generic params (of either type or method)
  5361. // TO allow resolution, perhaps move this generic param initalization into GetMethodInstance (passing a genericPass bool)
  5362. auto constraintType = ResolveTypeRef(constraintTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_AllowGenericMethodParamConstValue);
  5363. if (constraintType != NULL)
  5364. {
  5365. if ((genericParamDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  5366. {
  5367. bool isValidTypeCode = false;
  5368. BfTypeCode typeCode = BfTypeCode_None;
  5369. if (constraintType->IsTypedPrimitive())
  5370. {
  5371. auto underlyingType = constraintType->GetUnderlyingType();
  5372. if (underlyingType->IsPrimitiveType())
  5373. typeCode = ((BfPrimitiveType*)underlyingType)->mTypeDef->mTypeCode;
  5374. }
  5375. if (constraintType->IsPrimitiveType())
  5376. typeCode = ((BfPrimitiveType*)constraintType)->mTypeDef->mTypeCode;
  5377. switch (typeCode)
  5378. {
  5379. case BfTypeCode_Int8:
  5380. case BfTypeCode_UInt8:
  5381. case BfTypeCode_Int16:
  5382. case BfTypeCode_UInt16:
  5383. case BfTypeCode_Int32:
  5384. case BfTypeCode_UInt32:
  5385. case BfTypeCode_Int64:
  5386. case BfTypeCode_UInt64:
  5387. case BfTypeCode_IntPtr:
  5388. case BfTypeCode_UIntPtr:
  5389. case BfTypeCode_IntUnknown:
  5390. case BfTypeCode_UIntUnknown:
  5391. case BfTypeCode_Single:
  5392. case BfTypeCode_Double:
  5393. case BfTypeCode_Char8:
  5394. case BfTypeCode_Char16:
  5395. case BfTypeCode_Char32:
  5396. isValidTypeCode = true;
  5397. break;
  5398. }
  5399. if (isValidTypeCode)
  5400. {
  5401. genericParamInstance->mTypeConstraint = constraintType;
  5402. }
  5403. else
  5404. {
  5405. Fail("Const constraint must be a primitive type", constraintTypeRef);
  5406. }
  5407. }
  5408. else
  5409. {
  5410. if (constraintType->IsPrimitiveType())
  5411. {
  5412. Fail("Primitive constraints are not allowed unless preceded with 'const'", constraintTypeRef);
  5413. continue;
  5414. }
  5415. if (constraintType->IsArray())
  5416. {
  5417. 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);
  5418. continue;
  5419. }
  5420. if ((!constraintType->IsTypeInstance()) && (!constraintType->IsSizedArray()))
  5421. {
  5422. Fail(StrFormat("Type '%s' is not allowed as a generic constraint", TypeToString(constraintType).c_str()), constraintTypeRef);
  5423. continue;
  5424. }
  5425. if (constraintType->IsInterface())
  5426. {
  5427. genericParamInstance->mInterfaceConstraints.push_back(constraintType->ToTypeInstance());
  5428. }
  5429. else
  5430. {
  5431. auto constraintTypeInst = constraintType->ToTypeInstance();
  5432. if (genericParamInstance->mTypeConstraint != NULL)
  5433. {
  5434. if ((constraintTypeInst != NULL) && (TypeIsSubTypeOf(constraintTypeInst, genericParamInstance->mTypeConstraint->ToTypeInstance(), false)))
  5435. {
  5436. // Allow more specific type
  5437. genericParamInstance->mTypeConstraint = constraintTypeInst;
  5438. }
  5439. else if ((constraintTypeInst != NULL) && (TypeIsSubTypeOf(genericParamInstance->mTypeConstraint->ToTypeInstance(), constraintTypeInst, false)))
  5440. {
  5441. // Silently ignore less-specific type
  5442. if ((startingTypeConstraint != NULL) && (startingTypeConstraint->IsDelegate()))
  5443. {
  5444. // 'System.Delegate' means that we are expecting an actual delegate instance. Simulate this by wanting a class.
  5445. genericParamInstance->mGenericParamFlags |= BfGenericParamFlag_Class;
  5446. }
  5447. }
  5448. else
  5449. {
  5450. Fail("Only one concrete type constraint may be specified", constraintTypeRef);
  5451. return;
  5452. }
  5453. }
  5454. else
  5455. genericParamInstance->mTypeConstraint = constraintType;
  5456. }
  5457. }
  5458. }
  5459. }
  5460. if (((genericParamDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0) &&
  5461. (genericParamInstance->mTypeConstraint == NULL))
  5462. genericParamInstance->mTypeConstraint = GetPrimitiveType(BfTypeCode_IntPtr);
  5463. }
  5464. String BfModule::GenericParamSourceToString(const BfGenericParamSource & genericParamSource)
  5465. {
  5466. if (genericParamSource.mMethodInstance != NULL)
  5467. {
  5468. auto methodInst = GetUnspecializedMethodInstance(genericParamSource.mMethodInstance);
  5469. SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, methodInst);
  5470. return MethodToString(methodInst);
  5471. }
  5472. else
  5473. {
  5474. auto typeInst = GetUnspecializedTypeInstance(genericParamSource.mTypeInstance);
  5475. SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, NULL);
  5476. SetAndRestoreValue<BfTypeInstance*> prevTypeInst(mCurTypeInstance, typeInst);
  5477. return TypeToString(typeInst);
  5478. }
  5479. }
  5480. bool BfModule::CheckGenericConstraints(const BfGenericParamSource& genericParamSource, BfType* checkArgType, BfAstNode* checkArgTypeRef, BfGenericParamInstance* genericParamInst, BfTypeVector* methodGenericArgs, BfError** errorOut)
  5481. {
  5482. bool ignoreErrors = mIgnoreErrors || (errorOut == NULL) ||
  5483. ((genericParamSource.mMethodInstance == NULL) && (genericParamSource.mTypeInstance == NULL));
  5484. BfType* origCheckArgType = checkArgType;
  5485. if (origCheckArgType->IsRef())
  5486. origCheckArgType = origCheckArgType->GetUnderlyingType();
  5487. bool argMayBeReferenceType = false;
  5488. int checkGenericParamFlags = 0;
  5489. if (checkArgType->IsGenericParam())
  5490. {
  5491. auto checkGenericParamInst = GetGenericParamInstance((BfGenericParamType*)checkArgType);
  5492. checkGenericParamFlags = checkGenericParamInst->mGenericParamFlags;
  5493. if (checkGenericParamInst->mTypeConstraint != NULL)
  5494. checkArgType = checkGenericParamInst->mTypeConstraint;
  5495. if ((checkGenericParamFlags & (BfGenericParamFlag_Struct | BfGenericParamFlag_StructPtr)) != 0)
  5496. {
  5497. argMayBeReferenceType = false;
  5498. }
  5499. else
  5500. {
  5501. argMayBeReferenceType = true;
  5502. }
  5503. }
  5504. if (checkArgType->IsObjectOrInterface())
  5505. argMayBeReferenceType = true;
  5506. BfTypeInstance* typeConstraintInst = NULL;
  5507. if (genericParamInst->mTypeConstraint != NULL)
  5508. typeConstraintInst = genericParamInst->mTypeConstraint->ToTypeInstance();
  5509. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Struct) &&
  5510. ((checkGenericParamFlags & (BfGenericParamFlag_Struct | BfGenericParamFlag_Var)) == 0) && (!checkArgType->IsValueType()))
  5511. {
  5512. if (!ignoreErrors)
  5513. *errorOut = Fail(StrFormat("The type '%s' must be a value type in order to use it as parameter '%s' for '%s'",
  5514. TypeToString(origCheckArgType).c_str(), genericParamInst->GetGenericParamDef()->mName.c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5515. return false;
  5516. }
  5517. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_StructPtr) &&
  5518. ((checkGenericParamFlags & (BfGenericParamFlag_StructPtr | BfGenericParamFlag_Var)) == 0) && (!checkArgType->IsPointer()))
  5519. {
  5520. if (!ignoreErrors)
  5521. *errorOut = Fail(StrFormat("The type '%s' must be a pointer type in order to use it as parameter '%s' for '%s'",
  5522. TypeToString(origCheckArgType).c_str(), genericParamInst->GetGenericParamDef()->mName.c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5523. return false;
  5524. }
  5525. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Class) &&
  5526. ((checkGenericParamFlags & (BfGenericParamFlag_Class | BfGenericParamFlag_Var)) == 0) && (!argMayBeReferenceType))
  5527. {
  5528. if (!ignoreErrors)
  5529. *errorOut = Fail(StrFormat("The type '%s' must be a reference type in order to use it as parameter '%s' for '%s'",
  5530. TypeToString(origCheckArgType).c_str(), genericParamInst->GetGenericParamDef()->mName.c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5531. return false;
  5532. }
  5533. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  5534. {
  5535. if (((checkGenericParamFlags & BfGenericParamFlag_Const) == 0) && (!checkArgType->IsConstExprValue()))
  5536. {
  5537. if (!ignoreErrors)
  5538. *errorOut = Fail(StrFormat("The type '%s' must be a const value in order to use it as parameter '%s' for '%s'",
  5539. TypeToString(origCheckArgType).c_str(), genericParamInst->GetGenericParamDef()->mName.c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5540. return false;
  5541. }
  5542. }
  5543. else
  5544. {
  5545. if (checkArgType->IsConstExprValue())
  5546. {
  5547. if (!ignoreErrors)
  5548. *errorOut = Fail(StrFormat("The value '%s' cannot be used for generic type parameter '%s' for '%s'",
  5549. TypeToString(origCheckArgType).c_str(), genericParamInst->GetGenericParamDef()->mName.c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5550. return false;
  5551. }
  5552. }
  5553. if ((genericParamInst->mInterfaceConstraints.size() == 0) && (genericParamInst->mTypeConstraint == NULL))
  5554. return true;
  5555. if (checkArgType->IsPointer())
  5556. {
  5557. auto ptrType = (BfPointerType*)checkArgType;
  5558. checkArgType = ptrType->mElementType;
  5559. }
  5560. if (genericParamInst->mTypeConstraint != NULL)
  5561. {
  5562. bool constraintMatched = false;
  5563. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  5564. {
  5565. if (checkArgType->IsConstExprValue())
  5566. {
  5567. auto constExprValueType = (BfConstExprValueType*)checkArgType;
  5568. if (genericParamInst->mTypeConstraint->IsPrimitiveType())
  5569. {
  5570. auto primType = (BfPrimitiveType*)genericParamInst->mTypeConstraint;
  5571. // Let either an exact typematch or an undef pass through. Eventually instead of undefs we may want to do
  5572. // actual expression comparisons, but we are overly permissive now and then we may fail on specialization
  5573. if ((constExprValueType->mValue.mTypeCode != primType->mTypeDef->mTypeCode) &&
  5574. (constExprValueType->mValue.mTypeCode != BfTypeCode_Let) &&
  5575. (primType->mTypeDef->mTypeCode != BfTypeCode_Let))
  5576. {
  5577. if (BfIRConstHolder::IsInt(constExprValueType->mValue.mTypeCode))
  5578. {
  5579. if (BfIRConstHolder::IsInt(primType->mTypeDef->mTypeCode))
  5580. {
  5581. if (!mCompiler->mSystem->DoesLiteralFit(primType->mTypeDef->mTypeCode, constExprValueType->mValue.mInt64))
  5582. {
  5583. if (!ignoreErrors)
  5584. *errorOut = Fail(StrFormat("Const generic argument '%s', declared with const '%lld', does not fit into const constraint '%s' for '%s'", genericParamInst->GetGenericParamDef()->mName.c_str(),
  5585. constExprValueType->mValue.mInt64, TypeToString(genericParamInst->mTypeConstraint).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5586. return false;
  5587. }
  5588. }
  5589. else
  5590. {
  5591. if (!ignoreErrors)
  5592. *errorOut = Fail(StrFormat("Const generic argument '%s', declared with integer const '%lld', is not compatible with const constraint '%s' for '%s'", genericParamInst->GetGenericParamDef()->mName.c_str(),
  5593. constExprValueType->mValue.mInt64, TypeToString(genericParamInst->mTypeConstraint).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5594. return false;
  5595. }
  5596. }
  5597. else
  5598. {
  5599. if (BfIRConstHolder::IsInt(primType->mTypeDef->mTypeCode))
  5600. {
  5601. char valStr[64];
  5602. ExactMinimalDoubleToStr(constExprValueType->mValue.mDouble, valStr);
  5603. if (!ignoreErrors)
  5604. *errorOut = Fail(StrFormat("Const generic argument '%s', declared with floating point const '%s', is not compatible with const constraint '%s' for '%s'", genericParamInst->GetGenericParamDef()->mName.c_str(),
  5605. valStr, TypeToString(genericParamInst->mTypeConstraint).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5606. return false;
  5607. }
  5608. }
  5609. }
  5610. }
  5611. }
  5612. }
  5613. else
  5614. {
  5615. BfType* convCheckConstraint = genericParamInst->mTypeConstraint;
  5616. if ((convCheckConstraint->IsUnspecializedType()) && (methodGenericArgs != NULL))
  5617. convCheckConstraint = ResolveGenericType(convCheckConstraint, *methodGenericArgs);
  5618. if ((checkArgType->IsMethodRef()) && (convCheckConstraint->IsDelegate()))
  5619. {
  5620. auto methodRefType = (BfMethodRefType*)checkArgType;
  5621. auto invokeMethod = GetRawMethodInstanceAtIdx(convCheckConstraint->ToTypeInstance(), 0, "Invoke");
  5622. BfExprEvaluator exprEvaluator(this);
  5623. if (exprEvaluator.IsExactMethodMatch(methodRefType->mMethodRef, invokeMethod))
  5624. constraintMatched = true;
  5625. }
  5626. else if (CanImplicitlyCast(GetFakeTypedValue(checkArgType), convCheckConstraint))
  5627. {
  5628. constraintMatched = true;
  5629. }
  5630. else if (origCheckArgType->IsWrappableType())
  5631. {
  5632. if (origCheckArgType->IsSizedArray())
  5633. {
  5634. auto sizedArrayType = (BfSizedArrayType*)origCheckArgType;
  5635. if (convCheckConstraint->IsGenericTypeInstance())
  5636. {
  5637. auto convCheckConstraintInst = (BfGenericTypeInstance*)convCheckConstraint;
  5638. if (convCheckConstraintInst->mTypeDef == mCompiler->mSizedArrayTypeDef)
  5639. {
  5640. if (convCheckConstraintInst->mTypeGenericArguments[0] == sizedArrayType->mElementType)
  5641. {
  5642. auto constExprValueType = (BfConstExprValueType*)convCheckConstraintInst->mTypeGenericArguments[1];
  5643. if (sizedArrayType->mElementCount == constExprValueType->mValue.mInt64)
  5644. constraintMatched = true;
  5645. }
  5646. }
  5647. }
  5648. }
  5649. if (!constraintMatched)
  5650. {
  5651. BfType* wrappedStructType = GetWrappedStructType(origCheckArgType, false);
  5652. if (CanImplicitlyCast(GetFakeTypedValue(wrappedStructType), convCheckConstraint))
  5653. constraintMatched = true;
  5654. }
  5655. }
  5656. if (!constraintMatched)
  5657. {
  5658. if (!ignoreErrors)
  5659. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must derive from '%s'", genericParamInst->GetGenericParamDef()->mName.c_str(),
  5660. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(), TypeToString(convCheckConstraint).c_str(),
  5661. TypeToString(genericParamInst->mTypeConstraint).c_str()), checkArgTypeRef);
  5662. return false;
  5663. }
  5664. }
  5665. }
  5666. if ((genericParamInst->mInterfaceConstraints.size() > 0) && (origCheckArgType->IsInterface()))
  5667. {
  5668. PopulateType(origCheckArgType);
  5669. auto checkTypeInst = origCheckArgType->ToTypeInstance();
  5670. if (checkTypeInst->mTypeDef->mIsConcrete)
  5671. {
  5672. if (!ignoreErrors)
  5673. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be concrete interface '%s' for '%s', must be a concrete type", genericParamInst->GetGenericParamDef()->mName.c_str(),
  5674. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5675. return false;
  5676. }
  5677. }
  5678. for (auto checkConstraint : genericParamInst->mInterfaceConstraints)
  5679. {
  5680. BfType* convCheckConstraint = checkConstraint;
  5681. if (convCheckConstraint->IsUnspecializedType())
  5682. convCheckConstraint = ResolveGenericType(convCheckConstraint, *methodGenericArgs);
  5683. BfTypeInstance* typeConstraintInst = convCheckConstraint->ToTypeInstance();
  5684. bool implementsInterface = false;
  5685. if (origCheckArgType != checkArgType)
  5686. {
  5687. implementsInterface = CanImplicitlyCast(origCheckArgType, convCheckConstraint);
  5688. }
  5689. if (!implementsInterface)
  5690. implementsInterface = CanImplicitlyCast(checkArgType, convCheckConstraint);
  5691. if ((!implementsInterface) && (origCheckArgType->IsWrappableType()))
  5692. {
  5693. BfTypeInstance* wrappedStructType = GetWrappedStructType(origCheckArgType, false);
  5694. if (TypeIsSubTypeOf(wrappedStructType, typeConstraintInst))
  5695. implementsInterface = true;
  5696. }
  5697. if ((!implementsInterface) && (origCheckArgType->IsTypedPrimitive()))
  5698. {
  5699. auto underlyingType = origCheckArgType->GetUnderlyingType();
  5700. BfTypeInstance* wrappedStructType = GetWrappedStructType(underlyingType, false);
  5701. if (TypeIsSubTypeOf(wrappedStructType, typeConstraintInst))
  5702. implementsInterface = true;
  5703. }
  5704. if (!implementsInterface)
  5705. {
  5706. if (!ignoreErrors)
  5707. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must implement '%s'", genericParamInst->GetGenericParamDef()->mName.c_str(),
  5708. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(), TypeToString(checkConstraint).c_str()), checkArgTypeRef);
  5709. return false;
  5710. }
  5711. }
  5712. return true;
  5713. }
  5714. BfGenericParamType* BfModule::GetGenericParamType(BfGenericParamKind paramKind, int paramIdx)
  5715. {
  5716. if (paramIdx < (int)mContext->mGenericParamTypes[paramKind].size())
  5717. {
  5718. auto genericParamType = mContext->mGenericParamTypes[paramKind][paramIdx];
  5719. return genericParamType;
  5720. }
  5721. auto genericParamType = new BfGenericParamType();
  5722. genericParamType->mContext = mContext;
  5723. genericParamType->mGenericParamKind = paramKind;
  5724. genericParamType->mGenericParamIdx = paramIdx;
  5725. PopulateType(genericParamType);
  5726. BF_ASSERT(paramIdx == (int)mContext->mGenericParamTypes[paramKind].size());
  5727. mContext->mGenericParamTypes[paramKind].push_back(genericParamType);
  5728. BfResolvedTypeSet::LookupContext lookupCtx;
  5729. lookupCtx.mModule = this;
  5730. BfResolvedTypeSet::Entry* typeEntry = NULL;
  5731. auto inserted = mContext->mResolvedTypes.Insert(genericParamType, &lookupCtx, &typeEntry);
  5732. BF_ASSERT(inserted);
  5733. typeEntry->mValue = genericParamType;
  5734. return genericParamType;
  5735. }
  5736. static int sValueFromExprIdx = 0;
  5737. BfTypedValue BfModule::FlushNullConditional(BfTypedValue result, bool ignoreNullable)
  5738. {
  5739. auto pendingNullCond = mCurMethodState->mPendingNullConditional;
  5740. if ((result) && (!ignoreNullable))
  5741. {
  5742. auto notNullBB = mBfIRBuilder->GetInsertBlock();
  5743. //TODO: Make this work, needed for 'void' and such
  5744. BfType* nullableType = NULL;
  5745. if ((result.mType->IsValueType()) && (!result.mType->IsNullable()))
  5746. {
  5747. BfTypeVector typeVec;
  5748. typeVec.push_back(result.mType);
  5749. nullableType = ResolveTypeDef(mCompiler->mNullableTypeDef, typeVec);
  5750. BF_ASSERT(nullableType != NULL);
  5751. }
  5752. // Go back to start and do any setup we need
  5753. mBfIRBuilder->SetInsertPoint(pendingNullCond->mPrevBB);
  5754. BfTypedValue nullableTypedValue;
  5755. if (nullableType != NULL)
  5756. {
  5757. nullableTypedValue = BfTypedValue(CreateAlloca(nullableType, true, "nullCond.nullable"), nullableType, true);
  5758. mBfIRBuilder->CreateMemSet(nullableTypedValue.mValue, GetConstValue(0, GetPrimitiveType(BfTypeCode_Int8)),
  5759. GetConstValue(nullableType->mSize), nullableType->mAlign);
  5760. }
  5761. mBfIRBuilder->CreateBr(pendingNullCond->mCheckBB);
  5762. // Now that we have the nullableTypedValue we can set that, or just jump if we didn't need it
  5763. mBfIRBuilder->SetInsertPoint(notNullBB);
  5764. result = LoadValue(result);
  5765. if (nullableTypedValue)
  5766. {
  5767. auto elementType = nullableType->GetUnderlyingType();
  5768. if (elementType->IsValuelessType())
  5769. {
  5770. BfIRValue ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 1); // mHasValue
  5771. mBfIRBuilder->CreateStore(GetConstValue(1, GetPrimitiveType(BfTypeCode_Boolean)), ptrValue);
  5772. result = nullableTypedValue;
  5773. }
  5774. else
  5775. {
  5776. BfIRValue ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 1); // mValue
  5777. mBfIRBuilder->CreateStore(result.mValue, ptrValue);
  5778. ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 2); // mHasValue
  5779. mBfIRBuilder->CreateStore(GetConstValue(1, GetPrimitiveType(BfTypeCode_Boolean)), ptrValue);
  5780. result = nullableTypedValue;
  5781. }
  5782. }
  5783. mBfIRBuilder->CreateBr(pendingNullCond->mDoneBB);
  5784. AddBasicBlock(pendingNullCond->mDoneBB);
  5785. if (nullableType == NULL)
  5786. {
  5787. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapType(result.mType), 2);
  5788. mBfIRBuilder->AddPhiIncoming(phi, result.mValue, notNullBB);
  5789. mBfIRBuilder->AddPhiIncoming(phi, GetDefaultValue(result.mType), pendingNullCond->mCheckBB);
  5790. result.mValue = phi;
  5791. }
  5792. }
  5793. else
  5794. {
  5795. mBfIRBuilder->CreateBr(pendingNullCond->mDoneBB);
  5796. mBfIRBuilder->SetInsertPoint(pendingNullCond->mPrevBB);
  5797. mBfIRBuilder->CreateBr(pendingNullCond->mCheckBB);
  5798. AddBasicBlock(pendingNullCond->mDoneBB);
  5799. }
  5800. delete mCurMethodState->mPendingNullConditional;
  5801. mCurMethodState->mPendingNullConditional = NULL;
  5802. return result;
  5803. }
  5804. BF_NOINLINE void BfModule::EvaluateWithNewScope(BfExprEvaluator& exprEvaluator, BfExpression* expr, BfEvalExprFlags flags)
  5805. {
  5806. BfScopeData newScope;
  5807. newScope.mOuterIsConditional = true;
  5808. newScope.mAllowTargeting = false;
  5809. mCurMethodState->AddScope(&newScope);
  5810. NewScopeState();
  5811. exprEvaluator.mBfEvalExprFlags = flags;
  5812. exprEvaluator.Evaluate(expr, (flags & BfEvalExprFlags_PropogateNullConditional) != 0, (flags & BfEvalExprFlags_IgnoreNullConditional) != 0, true);
  5813. RestoreScopeState();
  5814. }
  5815. BfTypedValue BfModule::CreateValueFromExpression(BfExprEvaluator& exprEvaluator, BfExpression* expr, BfType* wantTypeRef, BfEvalExprFlags flags, BfType** outOrigType)
  5816. {
  5817. //
  5818. {
  5819. BP_ZONE("CreateValueFromExpression:CheckStack");
  5820. StackHelper stackHelper;
  5821. if (!stackHelper.CanStackExpand(64 * 1024))
  5822. {
  5823. BfTypedValue result;
  5824. if (!stackHelper.Execute([&]()
  5825. {
  5826. result = CreateValueFromExpression(exprEvaluator, expr, wantTypeRef, flags, outOrigType);
  5827. }))
  5828. {
  5829. Fail("Expression too complex to compile", expr);
  5830. }
  5831. return result;
  5832. }
  5833. }
  5834. BP_ZONE("BfModule::CreateValueFromExpression");
  5835. if (outOrigType != NULL)
  5836. *outOrigType = NULL;
  5837. exprEvaluator.mExpectingType = wantTypeRef;
  5838. exprEvaluator.mBfEvalExprFlags = flags;
  5839. exprEvaluator.mExplicitCast = (flags & BfEvalExprFlags_ExplicitCast) != 0;
  5840. if ((flags & BfEvalExprFlags_CreateConditionalScope) != 0)
  5841. {
  5842. EvaluateWithNewScope(exprEvaluator, expr, flags);
  5843. }
  5844. else
  5845. exprEvaluator.Evaluate(expr, (flags & BfEvalExprFlags_PropogateNullConditional) != 0, (flags & BfEvalExprFlags_IgnoreNullConditional) != 0, true);
  5846. if (!exprEvaluator.mResult)
  5847. {
  5848. if (!mCompiler->mPassInstance->HasFailed())
  5849. Fail("INTERNAL ERROR: No expression result returned but no error caught in expression evaluator", expr);
  5850. return BfTypedValue();
  5851. }
  5852. auto typedVal = exprEvaluator.mResult;
  5853. if (typedVal.mKind == BfTypedValueKind_GenericConstValue)
  5854. {
  5855. BF_ASSERT(typedVal.mType->IsGenericParam());
  5856. auto genericParamDef = GetGenericParamInstance((BfGenericParamType*)typedVal.mType);
  5857. bool handled = false;
  5858. if ((genericParamDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  5859. {
  5860. auto genericTypeConstraint = genericParamDef->mTypeConstraint;
  5861. if (genericTypeConstraint != NULL)
  5862. {
  5863. auto primType = genericTypeConstraint->ToPrimitiveType();
  5864. if (primType != NULL)
  5865. {
  5866. BfTypedValue result;
  5867. result.mKind = BfTypedValueKind_Value;
  5868. result.mType = genericTypeConstraint;
  5869. result.mValue = mBfIRBuilder->GetUndefConstValue(primType->mTypeDef->mTypeCode);
  5870. typedVal = result;
  5871. handled = true;
  5872. }
  5873. }
  5874. }
  5875. if (!handled)
  5876. {
  5877. //Fail("Only const generic parameters can be used as values", expr);
  5878. AssertErrorState();
  5879. return BfTypedValue();
  5880. }
  5881. }
  5882. if ((flags & BfEvalExprFlags_AllowIntUnknown) == 0)
  5883. FixIntUnknown(typedVal);
  5884. exprEvaluator.CheckResultForReading(typedVal);
  5885. if ((wantTypeRef == NULL) || (!wantTypeRef->IsRef()))
  5886. {
  5887. if ((flags & BfEvalExprFlags_NoCast) == 0)
  5888. {
  5889. // Only allow a 'ref' type if we have an explicit 'ref' operator
  5890. bool allowRef = false;
  5891. BfExpression* checkExpr = expr;
  5892. while (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(checkExpr))
  5893. checkExpr = parenExpr->mExpression;
  5894. if (auto unaryOp = BfNodeDynCast<BfUnaryOperatorExpression>(checkExpr))
  5895. {
  5896. if ((unaryOp->mOp == BfUnaryOp_Ref) || (unaryOp->mOp == BfUnaryOp_Mut))
  5897. allowRef = true;
  5898. }
  5899. if (!allowRef)
  5900. typedVal = RemoveRef(typedVal);
  5901. }
  5902. }
  5903. if (!typedVal.mType->IsComposite()) // Load non-structs by default
  5904. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  5905. if (wantTypeRef != NULL)
  5906. {
  5907. if (outOrigType != NULL)
  5908. *outOrigType = typedVal.mType;
  5909. if ((flags & BfEvalExprFlags_NoCast) == 0)
  5910. {
  5911. BfCastFlags castFlags = ((flags & BfEvalExprFlags_ExplicitCast) != 0) ? BfCastFlags_Explicit : BfCastFlags_None;
  5912. if ((flags & BfEvalExprFlags_FieldInitializer) != 0)
  5913. castFlags = (BfCastFlags)(castFlags | BfCastFlags_WarnOnBox);
  5914. typedVal = Cast(expr, typedVal, wantTypeRef, castFlags);
  5915. if (!typedVal)
  5916. return typedVal;
  5917. }
  5918. //WTF- why did we have this?
  5919. /*if ((flags & BfEvalExprFlags_ExplicitCast) == 0)
  5920. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);*/
  5921. if (exprEvaluator.mIsVolatileReference)
  5922. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  5923. }
  5924. // if ((typedVal.IsSplat()) && ((flags & BfEvalExprFlags_AllowSplat) == 0))
  5925. // typedVal = MakeAddressable(typedVal);
  5926. //typedVal = AggregateSplat(typedVal);
  5927. if ((typedVal.mType->IsValueType()) && ((flags & BfEvalExprFlags_NoValueAddr) != 0))
  5928. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  5929. return typedVal;
  5930. }
  5931. BfTypedValue BfModule::CreateValueFromExpression(BfExpression* expr, BfType* wantTypeRef, BfEvalExprFlags flags, BfType** outOrigType)
  5932. {
  5933. BfExprEvaluator exprEvaluator(this);
  5934. return CreateValueFromExpression(exprEvaluator, expr, wantTypeRef, flags, outOrigType);
  5935. }
  5936. BfTypedValue BfModule::GetOrCreateVarAddr(BfExpression* expr)
  5937. {
  5938. BfExprEvaluator exprEvaluator(this);
  5939. exprEvaluator.Evaluate(expr);
  5940. if (!exprEvaluator.mResult)
  5941. {
  5942. Fail("Invalid expression type", expr);
  5943. return BfTypedValue();
  5944. }
  5945. if (!exprEvaluator.mResult.IsAddr())
  5946. {
  5947. Fail("Cannot assign to value", expr);
  5948. return BfTypedValue();
  5949. }
  5950. return exprEvaluator.mResult;
  5951. }
  5952. // Clear memory, set classVData, call init. Actual ctor is called elsewhere.
  5953. void BfModule::InitTypeInst(BfTypedValue typedValue, BfScopeData* scopeData, bool zeroMemory, BfIRValue sizeValue)
  5954. {
  5955. auto typeInstance = typedValue.mType->ToTypeInstance();
  5956. if (zeroMemory)
  5957. {
  5958. int zeroAlign = typedValue.mType->mAlign;
  5959. if (typeInstance != NULL)
  5960. zeroAlign = typeInstance->mInstAlign;
  5961. mBfIRBuilder->CreateMemSet(typedValue.mValue, GetConstValue8(0), sizeValue, zeroAlign);
  5962. }
  5963. if (!typedValue.mType->IsObject())
  5964. {
  5965. return;
  5966. }
  5967. if ((scopeData == NULL) && (mCurMethodState != NULL))
  5968. return; // Handled in heap alloc funcs
  5969. auto typeDef = typeInstance->mTypeDef;
  5970. mBfIRBuilder->PopulateType(typedValue.mType);
  5971. auto vObjectAddr = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, 0);
  5972. bool isAutocomplete = mCompiler->IsAutocomplete();
  5973. BfIRValue vDataRef;
  5974. if (!isAutocomplete)
  5975. {
  5976. vDataRef = GetClassVDataPtr(typeInstance);
  5977. }
  5978. auto i8Type = GetPrimitiveType(BfTypeCode_Int8);
  5979. auto ptrType = CreatePointerType(i8Type);
  5980. auto ptrPtrType = CreatePointerType(ptrType);
  5981. PopulateType(ptrPtrType, BfPopulateType_Declaration);
  5982. PopulateType(ptrType, BfPopulateType_Declaration);
  5983. auto destAddr = mBfIRBuilder->CreateBitCast(vObjectAddr, mBfIRBuilder->MapType(ptrPtrType));
  5984. if (!isAutocomplete)
  5985. {
  5986. if (mCompiler->mOptions.mObjectHasDebugFlags)
  5987. {
  5988. auto objectPtr = mBfIRBuilder->CreateBitCast(destAddr, mBfIRBuilder->MapType(mContext->mBfObjectType));
  5989. SizedArray<BfIRValue, 4> llvmArgs;
  5990. llvmArgs.push_back(objectPtr);
  5991. llvmArgs.push_back(vDataRef);
  5992. auto objectStackInitMethod = GetInternalMethod("Dbg_ObjectStackInit");
  5993. if (objectStackInitMethod)
  5994. mBfIRBuilder->CreateCall(objectStackInitMethod.mFunc, llvmArgs);
  5995. }
  5996. else
  5997. {
  5998. auto srcVal = mBfIRBuilder->CreateBitCast(vDataRef, mBfIRBuilder->MapType(ptrType));
  5999. auto objectPtr = mBfIRBuilder->CreateBitCast(destAddr, mBfIRBuilder->MapType(ptrType));
  6000. mBfIRBuilder->CreateStore(srcVal, destAddr);
  6001. }
  6002. }
  6003. }
  6004. BfIRValue BfModule::AllocBytes(BfAstNode* refNode, const BfAllocTarget& allocTarget, BfType* type, BfIRValue sizeValue, BfIRValue alignValue, BfAllocFlags allocFlags/*, bool zeroMemory, bool defaultToMalloc*/)
  6005. {
  6006. BfIRValue result;
  6007. BfType* ptrType;
  6008. if ((type->IsObject()) && ((allocFlags & BfAllocFlags_RawArray) == 0))
  6009. ptrType = type;
  6010. else
  6011. ptrType = CreatePointerType(type);
  6012. if ((allocTarget.mScopedInvocationTarget != NULL) || (allocTarget.mCustomAllocator))
  6013. {
  6014. auto intType = GetPrimitiveType(BfTypeCode_IntPtr);
  6015. SizedArray<BfExpression*, 2> argExprs;
  6016. BfTypedValueExpression typedValueExpr;
  6017. typedValueExpr.Init(BfTypedValue(sizeValue, intType));
  6018. typedValueExpr.mRefNode = refNode;
  6019. argExprs.push_back(&typedValueExpr);
  6020. BfTypedValueExpression appendSizeValueExpr;
  6021. appendSizeValueExpr.Init(BfTypedValue(alignValue, intType));
  6022. appendSizeValueExpr.mRefNode = refNode;
  6023. argExprs.push_back(&appendSizeValueExpr);
  6024. BfExprEvaluator exprEvaluator(this);
  6025. BfTypedValue allocResult;
  6026. if (allocTarget.mScopedInvocationTarget != NULL)
  6027. {
  6028. SizedArray<BfTypeReference*, 2> genericArgs;
  6029. exprEvaluator.DoInvocation(allocTarget.mScopedInvocationTarget, NULL, argExprs, NULL);
  6030. allocResult = LoadValue(exprEvaluator.mResult);
  6031. }
  6032. else if (allocTarget.mCustomAllocator)
  6033. {
  6034. auto customTypeInst = allocTarget.mCustomAllocator.mType->ToTypeInstance();
  6035. if (customTypeInst != NULL)
  6036. {
  6037. BfTypedValueExpression typeValueExpr;
  6038. String allocMethodName = "Alloc";
  6039. if (GetRawMethodByName(customTypeInst, "AllocTyped", -1, true, true))
  6040. {
  6041. allocMethodName = "AllocTyped";
  6042. auto typeType = ResolveTypeDef(mCompiler->mTypeTypeDef);
  6043. auto typeRefVal = CreateTypeDataRef(type);
  6044. typeValueExpr.Init(BfTypedValue(typeRefVal, typeType));
  6045. typeValueExpr.mRefNode = refNode;
  6046. argExprs.Insert(0, &typeValueExpr);
  6047. }
  6048. if (HasMixin(customTypeInst, allocMethodName, 2))
  6049. {
  6050. BfSizedArray<BfExpression*> argExprArr;
  6051. argExprArr.mSize = (int)argExprs.size();
  6052. argExprArr.mVals = &argExprs[0];
  6053. exprEvaluator.InjectMixin(refNode, allocTarget.mCustomAllocator, false, allocMethodName, argExprs, {});
  6054. allocResult = exprEvaluator.GetResult();
  6055. }
  6056. else
  6057. {
  6058. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  6059. BfResolvedArgs argValues(&sizedArgExprs);
  6060. exprEvaluator.ResolveArgValues(argValues);
  6061. SetAndRestoreValue<bool> prevNoBind(mCurMethodState->mNoBind, true);
  6062. allocResult = exprEvaluator.MatchMethod(refNode, NULL, allocTarget.mCustomAllocator, false, false, allocMethodName, argValues, NULL);
  6063. }
  6064. }
  6065. }
  6066. if (allocResult)
  6067. {
  6068. if (allocResult.mType->IsVoidPtr())
  6069. result = mBfIRBuilder->CreateBitCast(allocResult.mValue, mBfIRBuilder->MapType(ptrType));
  6070. else
  6071. result = CastToValue(refNode, allocResult, ptrType, BfCastFlags_Explicit);
  6072. return result;
  6073. }
  6074. }
  6075. if ((allocFlags & BfAllocFlags_NoDefaultToMalloc) != 0)
  6076. return result;
  6077. if (mCompiler->mOptions.mDebugAlloc)
  6078. {
  6079. BfIRValue allocData = GetDbgRawAllocData(type);
  6080. BfModuleMethodInstance allocMethod = GetInternalMethod("Dbg_RawAlloc", 2);
  6081. SizedArray<BfIRValue, 2> llvmArgs;
  6082. llvmArgs.push_back(sizeValue);
  6083. llvmArgs.push_back(allocData);
  6084. BfIRValue bitData = mBfIRBuilder->CreateCall(allocMethod.mFunc, llvmArgs);
  6085. return mBfIRBuilder->CreateBitCast(bitData, mBfIRBuilder->MapType(ptrType));
  6086. }
  6087. BfModuleMethodInstance moduleMethodInstance;
  6088. moduleMethodInstance = GetInternalMethod("Malloc");
  6089. SizedArray<BfIRValue, 1> llvmArgs;
  6090. llvmArgs.push_back(sizeValue);
  6091. auto func = moduleMethodInstance.mFunc;
  6092. if ((!func) || (func.IsFake()))
  6093. {
  6094. BF_ASSERT((mCompiler->mIsResolveOnly) || (mBfIRBuilder->mIgnoreWrites));
  6095. return mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(ptrType));
  6096. }
  6097. BfIRValue bitData = mBfIRBuilder->CreateCall(func, llvmArgs);
  6098. if ((allocFlags & BfAllocFlags_ZeroMemory) != 0)
  6099. mBfIRBuilder->CreateMemSet(bitData, GetConstValue8(0), sizeValue, alignValue);
  6100. result = mBfIRBuilder->CreateBitCast(bitData, mBfIRBuilder->MapType(ptrType));
  6101. return result;
  6102. }
  6103. BfIRValue BfModule::GetMarkFuncPtr(BfType* type)
  6104. {
  6105. if (type->IsStruct())
  6106. {
  6107. auto typeInstance = type->ToTypeInstance();
  6108. BfModuleMethodInstance moduleMethodInst = GetMethodByName(typeInstance, BF_METHODNAME_MARKMEMBERS, 0, true);
  6109. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  6110. }
  6111. else if (type->IsObjectOrInterface())
  6112. {
  6113. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  6114. BfModuleMethodInstance moduleMethodInst = GetMethodByName(gcType, "MarkDerefedObject");
  6115. BF_ASSERT(moduleMethodInst.mFunc);
  6116. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  6117. }
  6118. else
  6119. {
  6120. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  6121. BfExprEvaluator exprEvaluator(this);
  6122. SizedArray<BfResolvedArg, 1> resolvedArgs;
  6123. BfResolvedArg resolvedArg;
  6124. resolvedArg.mTypedValue = BfTypedValue(mBfIRBuilder->GetFakeVal(), type, type->IsComposite());
  6125. resolvedArgs.Add(resolvedArg);
  6126. BfMethodMatcher methodMatcher(NULL, this, "Mark", resolvedArgs, NULL);
  6127. methodMatcher.CheckType(gcType, BfTypedValue(), false);
  6128. BfModuleMethodInstance moduleMethodInst = exprEvaluator.GetSelectedMethod(NULL, methodMatcher.mBestMethodTypeInstance, methodMatcher.mBestMethodDef, methodMatcher);
  6129. BF_ASSERT(moduleMethodInst.mFunc);
  6130. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  6131. }
  6132. return BfIRValue();
  6133. }
  6134. BfIRValue BfModule::GetDbgRawAllocData(BfType* type)
  6135. {
  6136. BfIRValue allocDataValue;
  6137. if (mDbgRawAllocDataRefs.TryGetValue(type, &allocDataValue))
  6138. return allocDataValue;
  6139. BfIRValue markFuncPtr;
  6140. if (type->WantsGCMarking())
  6141. markFuncPtr = GetMarkFuncPtr(type);
  6142. else
  6143. markFuncPtr = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  6144. BfIRValue typeDataRef = CreateTypeDataRef(type);
  6145. auto dbgRawAllocDataType = ResolveTypeDef(mCompiler->mDbgRawAllocDataTypeDef)->ToTypeInstance();
  6146. BfTypeInstance* typeInstance = type->ToTypeInstance();
  6147. if (typeInstance == NULL)
  6148. {
  6149. typeInstance = GetWrappedStructType(type);
  6150. if (typeInstance != NULL)
  6151. AddDependency(typeInstance, mCurTypeInstance, BfDependencyMap::DependencyFlag_Allocates);
  6152. }
  6153. if (typeInstance != NULL)
  6154. PopulateType(typeInstance);
  6155. int stackCount = mCompiler->mOptions.mAllocStackCount;
  6156. if ((typeInstance != NULL) && (typeInstance->mTypeOptionsIdx != -1))
  6157. {
  6158. auto typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  6159. stackCount = BfTypeOptions::Apply(stackCount, typeOptions->mAllocStackTraceDepth);
  6160. }
  6161. SizedArray<BfIRValue, 2> dataValues;
  6162. dataValues.Add(mBfIRBuilder->CreateConstStructZero(mBfIRBuilder->MapType(dbgRawAllocDataType->mBaseType, BfIRPopulateType_Full)));
  6163. dataValues.Add(typeDataRef);
  6164. dataValues.Add(markFuncPtr);
  6165. dataValues.Add(mBfIRBuilder->CreateConst(BfTypeCode_Int32, stackCount));
  6166. BfIRValue dataStruct = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapType(dbgRawAllocDataType, BfIRPopulateType_Full), dataValues);
  6167. allocDataValue = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(dbgRawAllocDataType), true, BfIRLinkageType_Internal, dataStruct, "__allocData_" + BfSafeMangler::Mangle(type));
  6168. mDbgRawAllocDataRefs.TryAdd(type, allocDataValue);
  6169. return allocDataValue;
  6170. }
  6171. BfIRValue BfModule::AllocFromType(BfType* type, const BfAllocTarget& allocTarget, BfIRValue appendSizeValue, BfIRValue arraySize, int arrayDim, BfAllocFlags allocFlags, int alignOverride)
  6172. {
  6173. BP_ZONE("AllocFromType");
  6174. BfScopeData* scopeData = allocTarget.mScopeData;
  6175. auto typeInstance = type->ToTypeInstance();
  6176. if ((typeInstance == NULL) && (type->IsGenericParam()))
  6177. typeInstance = mContext->mBfObjectType;
  6178. bool isHeapAlloc = scopeData == NULL;
  6179. bool isScopeAlloc = scopeData != NULL;
  6180. bool isLoopedAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsLooped(scopeData));
  6181. bool isDynAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsDyn(scopeData));
  6182. bool isRawArrayAlloc = (allocFlags & BfAllocFlags_RawArray) != 0;
  6183. bool zeroMemory = (allocFlags & BfAllocFlags_ZeroMemory) != 0;
  6184. bool noDtorCall = (allocFlags & BfAllocFlags_NoDtorCall) != 0;
  6185. if ((type->IsValuelessType()) && ((!arraySize) || (isRawArrayAlloc)))
  6186. {
  6187. BfPointerType* ptrType = CreatePointerType(type);
  6188. auto val = mBfIRBuilder->CreateIntToPtr(mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1), mBfIRBuilder->MapType(ptrType));
  6189. return val;
  6190. }
  6191. if (typeInstance != NULL)
  6192. mBfIRBuilder->PopulateType(typeInstance);
  6193. bool hasCustomAllocator = (allocTarget.mCustomAllocator) || (allocTarget.mScopedInvocationTarget != NULL);
  6194. if ((!hasCustomAllocator) && (mBfIRBuilder->mIgnoreWrites))
  6195. {
  6196. if (arraySize)
  6197. {
  6198. if (isRawArrayAlloc)
  6199. {
  6200. BfPointerType* ptrType = CreatePointerType(type);
  6201. return GetDefaultValue(ptrType);
  6202. }
  6203. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  6204. return GetDefaultValue(arrayType);
  6205. }
  6206. if (type->IsValueType())
  6207. {
  6208. BfPointerType* ptrType = CreatePointerType(type);
  6209. return GetDefaultValue(ptrType);
  6210. }
  6211. return mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type));
  6212. }
  6213. AddDependency(type, mCurTypeInstance, BfDependencyMap::DependencyFlag_Allocates);
  6214. BfIRValue sizeValue;
  6215. BfIRType allocType = mBfIRBuilder->MapType(type);
  6216. int allocSize = type->mSize;
  6217. int allocAlign = type->mAlign;
  6218. if (typeInstance != NULL)
  6219. {
  6220. if (!mBfIRBuilder->mIgnoreWrites)
  6221. typeInstance->mHasBeenInstantiated = true;
  6222. allocSize = typeInstance->mInstSize;
  6223. allocAlign = typeInstance->mInstAlign;
  6224. //if (typeInstance->IsEnum())
  6225. //allocType = typeInstance->mIRType;
  6226. allocType = mBfIRBuilder->MapTypeInst(typeInstance);
  6227. }
  6228. if (alignOverride != -1)
  6229. allocAlign = alignOverride;
  6230. // The "dynSize" cases:
  6231. // If we are not dyn, but we are a variable size and could be looped over multiple times then we attempt to reuse
  6232. // the last stack space. We won't use StackSave and StackRestore because a scoped alloc that occurs after this but
  6233. // needs to be retained after the current scopeData (ie: scopeData::), then it would cause these allocs to accumulate even
  6234. // though we'd expect their stack space to be released
  6235. auto _CreateDynAlloc = [&](const BfIRValue& sizeValue, int align)
  6236. {
  6237. MarkDynStack(scopeData);
  6238. BfType* intType = GetPrimitiveType(BfTypeCode_IntPtr);
  6239. // For dynamically sized scoped allocs, we need to check the previous size to see if we need to realloc
  6240. BfType* voidType = GetPrimitiveType(BfTypeCode_None);
  6241. BfType* voidPtrType = CreatePointerType(voidType);
  6242. if (!mCurMethodState->mDynStackRevIdx)
  6243. {
  6244. mCurMethodState->mDynStackRevIdx = CreateAlloca(intType, false, "curDynStackRevIdx");
  6245. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  6246. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  6247. auto storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), mCurMethodState->mDynStackRevIdx);
  6248. mBfIRBuilder->ClearDebugLocation(storeInst);
  6249. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  6250. }
  6251. auto byteType = GetPrimitiveType(BfTypeCode_Int8);
  6252. auto bytePtrType = CreatePointerType(byteType);
  6253. auto dynSizeAllocaInst = CreateAlloca(intType, false, "dynSize");
  6254. auto dynStackRevIdx = CreateAlloca(intType, false, "dynStackRevIdx");
  6255. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  6256. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  6257. auto storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), dynSizeAllocaInst);
  6258. mBfIRBuilder->ClearDebugLocation(storeInst);
  6259. storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), dynStackRevIdx);
  6260. mBfIRBuilder->ClearDebugLocation(storeInst);
  6261. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  6262. auto dynPtrAllocaInst = CreateAlloca(bytePtrType, false, "dynPtr");
  6263. if (IsTargetingBeefBackend())
  6264. {
  6265. // Since we don't allocate a debug variable for this, with LifetimeExtends, the easiest way
  6266. // to ensure there isn't any register collision during looping is just to not allow it to
  6267. // bind to a register at all
  6268. mBfIRBuilder->SetAllocaForceMem(dynSizeAllocaInst);
  6269. mBfIRBuilder->SetAllocaForceMem(dynPtrAllocaInst);
  6270. }
  6271. auto resizeBB = mBfIRBuilder->CreateBlock("dynAlloc.resize");
  6272. auto endBB = mBfIRBuilder->CreateBlock("dynAlloc.end");
  6273. auto verCheckBB = mBfIRBuilder->CreateBlock("dynAlloc.verCheck");
  6274. auto curDynStackRevIdx = mBfIRBuilder->CreateLoad(mCurMethodState->mDynStackRevIdx);
  6275. auto prevSize = mBfIRBuilder->CreateLoad(dynSizeAllocaInst);
  6276. auto isGreater = mBfIRBuilder->CreateCmpGT(sizeValue, prevSize, true);
  6277. mBfIRBuilder->CreateCondBr(isGreater, resizeBB, verCheckBB);
  6278. mBfIRBuilder->AddBlock(verCheckBB);
  6279. mBfIRBuilder->SetInsertPoint(verCheckBB);
  6280. auto prevDynStackRevIdx = mBfIRBuilder->CreateLoad(dynStackRevIdx);
  6281. auto dynStackChanged = mBfIRBuilder->CreateCmpNE(prevDynStackRevIdx, curDynStackRevIdx);
  6282. mBfIRBuilder->CreateCondBr(dynStackChanged, resizeBB, endBB);
  6283. mBfIRBuilder->AddBlock(resizeBB);
  6284. mBfIRBuilder->SetInsertPoint(resizeBB);
  6285. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  6286. mBfIRBuilder->SetAllocaAlignment(allocaInst, align);
  6287. mBfIRBuilder->CreateStore(allocaInst, dynPtrAllocaInst);
  6288. mBfIRBuilder->CreateStore(sizeValue, dynSizeAllocaInst);
  6289. mBfIRBuilder->CreateStore(curDynStackRevIdx, dynStackRevIdx);
  6290. mBfIRBuilder->CreateBr(endBB);
  6291. mBfIRBuilder->AddBlock(endBB);
  6292. mBfIRBuilder->SetInsertPoint(endBB);
  6293. return mBfIRBuilder->CreateLoad(dynPtrAllocaInst);
  6294. };
  6295. if (isScopeAlloc)
  6296. {
  6297. if (arraySize)
  6298. {
  6299. bool isConstantArraySize = arraySize.IsConst();
  6300. if (isRawArrayAlloc)
  6301. {
  6302. BfPointerType* ptrType = CreatePointerType(type);
  6303. if ((!isDynAlloc) && (!isConstantArraySize) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  6304. {
  6305. BfIRValue sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  6306. auto loadedPtr = _CreateDynAlloc(sizeValue, type->mAlign);
  6307. InitTypeInst(BfTypedValue(loadedPtr, ptrType), scopeData, zeroMemory, sizeValue);
  6308. return mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(type)));
  6309. }
  6310. else
  6311. {
  6312. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  6313. isDynAlloc = (isDynAlloc) || (!arraySize.IsConst());
  6314. if (!isDynAlloc)
  6315. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  6316. else
  6317. {
  6318. MarkDynStack(scopeData);
  6319. SaveStackState(scopeData);
  6320. }
  6321. int typeSize = type->GetStride();
  6322. BfIRValue allocaInst;
  6323. BfIRValue result;
  6324. if ((typeInstance == NULL) || (typeInstance->mIsCRepr))
  6325. {
  6326. sizeValue = mBfIRBuilder->CreateMul(GetConstValue(typeSize), arraySize);
  6327. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type), arraySize);
  6328. result = allocaInst;
  6329. }
  6330. else
  6331. {
  6332. if (typeInstance->IsStruct())
  6333. typeSize = typeInstance->GetInstStride();
  6334. auto byteType = GetPrimitiveStructType(BfTypeCode_Int8);
  6335. sizeValue = mBfIRBuilder->CreateMul(GetConstValue(typeSize), arraySize);
  6336. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  6337. auto ptrType = CreatePointerType(typeInstance);
  6338. result = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(ptrType));
  6339. if (!isDynAlloc)
  6340. mBfIRBuilder->ClearDebugLocation(result);
  6341. }
  6342. if (!isDynAlloc)
  6343. mBfIRBuilder->ClearDebugLocation(allocaInst);
  6344. mBfIRBuilder->SetAllocaAlignment(allocaInst, type->mAlign);
  6345. if (!isDynAlloc)
  6346. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  6347. auto typedVal = BfTypedValue(result, type, BfTypedValueKind_Addr);
  6348. if (arraySize.IsConst())
  6349. {
  6350. auto constant = mBfIRBuilder->GetConstant(arraySize);
  6351. if (constant->mInt64 == 0)
  6352. noDtorCall = true;
  6353. }
  6354. if (!noDtorCall)
  6355. {
  6356. bool isConstSize = arraySize.IsConst();
  6357. BfIRBlock clearBlock;
  6358. BfIRBlock contBlock;
  6359. if (!isConstSize)
  6360. {
  6361. clearBlock = mBfIRBuilder->CreateBlock("clear");
  6362. contBlock = mBfIRBuilder->CreateBlock("clearCont");
  6363. mBfIRBuilder->CreateCondBr(mBfIRBuilder->CreateCmpNE(arraySize, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0)), clearBlock, contBlock);
  6364. mBfIRBuilder->AddBlock(clearBlock);
  6365. mBfIRBuilder->SetInsertPoint(clearBlock);
  6366. }
  6367. AddStackAlloc(typedVal, NULL, scopeData, false, true);
  6368. if (!isConstSize)
  6369. {
  6370. mBfIRBuilder->CreateBr(contBlock);
  6371. mBfIRBuilder->AddBlock(contBlock);
  6372. mBfIRBuilder->SetInsertPoint(contBlock);
  6373. }
  6374. }
  6375. //InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  6376. return result;
  6377. }
  6378. }
  6379. else
  6380. {
  6381. if ((!isDynAlloc) && (!arraySize.IsConst()) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  6382. {
  6383. // Generate and check new size
  6384. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  6385. auto firstElementField = &arrayType->mFieldInstances.back();
  6386. int arrayClassSize = firstElementField->mDataOffset;
  6387. sizeValue = GetConstValue(arrayClassSize);
  6388. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  6389. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  6390. auto loadedPtr = _CreateDynAlloc(sizeValue, arrayType->mAlign);
  6391. auto typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->MapType(arrayType)), arrayType);
  6392. if (!noDtorCall)
  6393. AddStackAlloc(typedVal, NULL, scopeData, false, true);
  6394. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  6395. return typedVal.mValue;
  6396. }
  6397. else
  6398. {
  6399. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  6400. auto firstElementField = &arrayType->mFieldInstances.back();
  6401. int arrayClassSize = firstElementField->mDataOffset;
  6402. sizeValue = GetConstValue(arrayClassSize);
  6403. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  6404. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  6405. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  6406. isDynAlloc = (isDynAlloc) || (!sizeValue.IsConst());
  6407. if (!isDynAlloc)
  6408. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  6409. else
  6410. {
  6411. MarkDynStack(scopeData);
  6412. SaveStackState(scopeData);
  6413. }
  6414. BfType* byteType = GetPrimitiveType(BfTypeCode_Int8);
  6415. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  6416. if (!isDynAlloc)
  6417. mBfIRBuilder->ClearDebugLocation(allocaInst);
  6418. mBfIRBuilder->SetAllocaAlignment(allocaInst, arrayType->mAlign);
  6419. auto typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(arrayType)), arrayType);
  6420. mBfIRBuilder->ClearDebugLocation_Last();
  6421. if (!isDynAlloc)
  6422. mBfIRBuilder->SetInsertPoint(prevBlock);
  6423. if (!noDtorCall)
  6424. AddStackAlloc(typedVal, NULL, scopeData, false, true);
  6425. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  6426. return typedVal.mValue;
  6427. }
  6428. }
  6429. }
  6430. else if (appendSizeValue)
  6431. {
  6432. // It may seem that we should check IsLooped against only the requested scope, BUT- if later on we perform
  6433. // a scoped alloc that crosses our boundary then we won't be able to reclaim the stack space, so we always
  6434. // use the "dynSize" version conservatively
  6435. if ((!isDynAlloc) && (!appendSizeValue.IsConst()) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  6436. {
  6437. // Generate and check new size
  6438. sizeValue = GetConstValue(typeInstance->mInstSize);
  6439. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  6440. auto loadedPtr = _CreateDynAlloc(sizeValue, typeInstance->mAlign);
  6441. auto typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->MapTypeInstPtr(typeInstance)), typeInstance);
  6442. if (!noDtorCall)
  6443. AddStackAlloc(typedVal, NULL, scopeData, mCurMethodState->mInConditionalBlock, true);
  6444. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  6445. return typedVal.mValue;
  6446. }
  6447. else // stack alloc, unlooped, with append
  6448. {
  6449. sizeValue = GetConstValue(typeInstance->mInstSize);
  6450. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  6451. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  6452. bool wasDynAlloc = isDynAlloc;
  6453. isDynAlloc = (isDynAlloc) || (!sizeValue.IsConst());
  6454. if (!isDynAlloc)
  6455. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  6456. else
  6457. {
  6458. MarkDynStack(scopeData);
  6459. SaveStackState(scopeData);
  6460. }
  6461. auto sbyteType = GetPrimitiveType(BfTypeCode_Int8);
  6462. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(sbyteType), sizeValue);
  6463. if (!isDynAlloc)
  6464. {
  6465. mBfIRBuilder->ClearDebugLocation(allocaInst);
  6466. }
  6467. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  6468. bool mayBeLarge = false;
  6469. if (sizeValue.IsConst())
  6470. {
  6471. auto constantInt = mBfIRBuilder->GetConstant(sizeValue);
  6472. if (constantInt->mInt64 >= 4096)
  6473. mayBeLarge = true;
  6474. }
  6475. else
  6476. mayBeLarge = true;
  6477. if (((type->IsObject() && (!mayBeLarge))) ||
  6478. // If we create a memset that can fill in backwards (or at least 4k chunked backward) then we can remove the '!mayBeLarge' cond
  6479. ((zeroMemory) && (!mayBeLarge)))
  6480. {
  6481. mBfIRBuilder->SetAllocaNoChkStkHint(allocaInst);
  6482. }
  6483. BfIRValue castedVal;
  6484. if (!isDynAlloc)
  6485. {
  6486. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  6487. castedVal = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapTypeInstPtr(typeInstance));
  6488. mBfIRBuilder->ClearDebugLocation(castedVal);
  6489. mBfIRBuilder->SetInsertPoint(prevBlock);
  6490. if (WantsLifetimes())
  6491. {
  6492. mBfIRBuilder->CreateLifetimeStart(allocaInst);
  6493. scopeData->mDeferredLifetimeEnds.push_back(allocaInst);
  6494. }
  6495. }
  6496. else
  6497. {
  6498. castedVal = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapTypeInstPtr(typeInstance));
  6499. }
  6500. auto typedVal = BfTypedValue(castedVal, typeInstance);
  6501. if (!noDtorCall)
  6502. {
  6503. bool doCondAlloca = false;
  6504. if (!IsTargetingBeefBackend())
  6505. doCondAlloca = !wasDynAlloc && isDynAlloc && mCurMethodState->mInConditionalBlock;
  6506. AddStackAlloc(typedVal, NULL, scopeData, doCondAlloca, true);
  6507. }
  6508. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  6509. return typedVal.mValue;
  6510. }
  6511. }
  6512. else // "Normal" stack alloc
  6513. {
  6514. BF_ASSERT(!sizeValue);
  6515. //TODO: If sizeValue is a constant then do this in the head IR builder
  6516. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  6517. if (!isLoopedAlloc)
  6518. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  6519. else
  6520. {
  6521. MarkDynStack(scopeData);
  6522. SaveStackState(scopeData);
  6523. }
  6524. auto allocaInst = mBfIRBuilder->CreateAlloca(allocType);
  6525. if (!isLoopedAlloc)
  6526. mBfIRBuilder->ClearDebugLocation(allocaInst);
  6527. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  6528. bool mayBeLarge = allocSize >= 4096;
  6529. if (((typeInstance != NULL) && (typeInstance->IsObject()) && (!mayBeLarge)) ||
  6530. // If we create a memset that can fill in backwards (or at least 4k chunked backward) then we can remove the '!mayBeLarge' cond
  6531. ((zeroMemory) && (!mayBeLarge)))
  6532. {
  6533. // With an object, we know we will at least set the vdata pointer which will probe the start of the new address,
  6534. // and memset is always safe
  6535. mBfIRBuilder->SetAllocaNoChkStkHint(allocaInst);
  6536. }
  6537. auto typedVal = BfTypedValue(allocaInst, type);
  6538. if (!isLoopedAlloc)
  6539. {
  6540. mBfIRBuilder->ClearDebugLocation(allocaInst);
  6541. mBfIRBuilder->SetInsertPoint(prevBlock);
  6542. if (WantsLifetimes())
  6543. {
  6544. mBfIRBuilder->CreateLifetimeStart(allocaInst);
  6545. scopeData->mDeferredLifetimeEnds.push_back(allocaInst);
  6546. }
  6547. }
  6548. if (!noDtorCall)
  6549. AddStackAlloc(typedVal, NULL, scopeData, false, true);
  6550. if (typeInstance != NULL)
  6551. {
  6552. InitTypeInst(typedVal, scopeData, zeroMemory, GetConstValue(typeInstance->mInstSize));
  6553. }
  6554. else
  6555. {
  6556. mBfIRBuilder->CreateMemSet(allocaInst, GetConstValue8(0), GetConstValue(allocSize), allocAlign);
  6557. }
  6558. return allocaInst;
  6559. }
  6560. }
  6561. else if (arraySize)
  6562. {
  6563. if (isRawArrayAlloc)
  6564. {
  6565. sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  6566. return AllocBytes(allocTarget.mRefNode, allocTarget, type, sizeValue, GetConstValue(allocAlign), allocFlags);
  6567. }
  6568. else
  6569. {
  6570. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  6571. typeInstance = arrayType;
  6572. BfIRValue arraySizeMinusOne = mBfIRBuilder->CreateSub(arraySize, GetConstValue(1));
  6573. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySizeMinusOne);
  6574. appendSizeValue = elementDataSize;
  6575. if (!type->IsSizeAligned())
  6576. {
  6577. appendSizeValue = mBfIRBuilder->CreateAdd(appendSizeValue, GetConstValue(type->GetStride() - type->mSize));
  6578. }
  6579. }
  6580. }
  6581. if ((typeInstance != NULL) && (typeInstance->IsObject()))
  6582. {
  6583. auto vDataRef = GetClassVDataPtr(typeInstance);
  6584. BfIRValue result;
  6585. bool isResultInitialized = false;
  6586. int stackCount = mCompiler->mOptions.mAllocStackCount;
  6587. if (typeInstance->mTypeOptionsIdx != -1)
  6588. {
  6589. auto typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  6590. stackCount = BfTypeOptions::Apply(stackCount, typeOptions->mAllocStackTraceDepth);
  6591. }
  6592. if (!sizeValue)
  6593. sizeValue = GetConstValue(typeInstance->mInstSize);
  6594. if (appendSizeValue)
  6595. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  6596. BfIRValue origSizeValue = sizeValue;
  6597. bool isAllocEx = hasCustomAllocator && (stackCount > 1);
  6598. if (isAllocEx)
  6599. {
  6600. auto prepareStackTraceMethod = GetInternalMethod("Dbg_PrepareStackTrace");
  6601. if (prepareStackTraceMethod)
  6602. {
  6603. SizedArray<BfIRValue, 2> irArgs;
  6604. irArgs.Add(sizeValue);
  6605. irArgs.Add(GetConstValue(stackCount));
  6606. auto addlBytes = mBfIRBuilder->CreateCall(prepareStackTraceMethod.mFunc, irArgs);
  6607. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, addlBytes);
  6608. }
  6609. }
  6610. if (allocTarget.mCustomAllocator)
  6611. {
  6612. auto customAlloc = allocTarget.mCustomAllocator.mType->ToTypeInstance();
  6613. // Use AllocObject if we have it, otherwise we just use AllocBytes further down
  6614. if ((customAlloc != NULL) && (GetRawMethodByName(customAlloc, "AllocObject", -1, true, true) != NULL))
  6615. {
  6616. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  6617. mBfIRBuilder->PopulateType(classVDataType);
  6618. auto typeInstType = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef)->ToTypeInstance();
  6619. mBfIRBuilder->PopulateType(typeInstType);
  6620. auto typePtrPtr = mBfIRBuilder->CreateInBoundsGEP(vDataRef, 0, 1); // mType
  6621. auto typePtr = mBfIRBuilder->CreateLoad(typePtrPtr);
  6622. auto typeInstPtr = mBfIRBuilder->CreateBitCast(typePtr, mBfIRBuilder->MapTypeInstPtr(typeInstType));
  6623. BfTypedValueExpression typedValueExpr;
  6624. typedValueExpr.Init(BfTypedValue(typeInstPtr, typeInstType));
  6625. typedValueExpr.mRefNode = allocTarget.mRefNode;
  6626. BfExprEvaluator exprEvaluator(this);
  6627. SizedArray<BfExpression*, 2> argExprs;
  6628. argExprs.push_back(&typedValueExpr);
  6629. BfTypedValueExpression sizeValueExpr;
  6630. sizeValueExpr.Init(BfTypedValue(sizeValue, GetPrimitiveType(BfTypeCode_IntPtr)));
  6631. sizeValueExpr.mRefNode = allocTarget.mRefNode;
  6632. argExprs.push_back(&sizeValueExpr);
  6633. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  6634. BfResolvedArgs argValues(&sizedArgExprs);
  6635. exprEvaluator.ResolveArgValues(argValues);
  6636. exprEvaluator.mNoBind = true;
  6637. BfTypedValue allocResult = exprEvaluator.MatchMethod(allocTarget.mRefNode, NULL, allocTarget.mCustomAllocator, false, false, "AllocObject", argValues, NULL);
  6638. if (allocResult)
  6639. {
  6640. if ((allocResult.mType->IsVoidPtr()) || (allocResult.mType == mContext->mBfObjectType))
  6641. result = mBfIRBuilder->CreateBitCast(allocResult.mValue, mBfIRBuilder->MapType(typeInstance));
  6642. else
  6643. result = CastToValue(allocTarget.mRefNode, allocResult, typeInstance, BfCastFlags_Explicit);
  6644. isResultInitialized = true;
  6645. }
  6646. }
  6647. }
  6648. if (!result)
  6649. {
  6650. if (hasCustomAllocator)
  6651. result = AllocBytes(allocTarget.mRefNode, allocTarget, typeInstance, sizeValue, GetConstValue(typeInstance->mInstAlign), (BfAllocFlags)(BfAllocFlags_ZeroMemory | BfAllocFlags_NoDefaultToMalloc));
  6652. }
  6653. if (result)
  6654. {
  6655. if (mCompiler->mOptions.mObjectHasDebugFlags)
  6656. {
  6657. auto objectPtr = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapTypeInstPtr(mContext->mBfObjectType));
  6658. SizedArray<BfIRValue, 4> llvmArgs;
  6659. llvmArgs.push_back(objectPtr);
  6660. llvmArgs.push_back(origSizeValue);
  6661. llvmArgs.push_back(vDataRef);
  6662. auto objectCreatedMethod = GetInternalMethod(isAllocEx ?
  6663. (isResultInitialized ? "Dbg_ObjectCreatedEx" : "Dbg_ObjectAllocatedEx") :
  6664. (isResultInitialized ? "Dbg_ObjectCreated" : "Dbg_ObjectAllocated"));
  6665. mBfIRBuilder->CreateCall(objectCreatedMethod.mFunc, llvmArgs);
  6666. }
  6667. else
  6668. {
  6669. auto ptrType = mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr);
  6670. auto vDataPtr = mBfIRBuilder->CreateBitCast(vDataRef, ptrType);
  6671. auto vDataMemberPtr = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->GetPointerTo(ptrType));
  6672. mBfIRBuilder->CreateStore(vDataPtr, vDataMemberPtr);
  6673. }
  6674. }
  6675. else
  6676. {
  6677. if ((mBfIRBuilder->mIgnoreWrites) || (mCompiler->mIsResolveOnly))
  6678. return GetDefaultValue(typeInstance);
  6679. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  6680. auto vData = mBfIRBuilder->CreateBitCast(vDataRef, mBfIRBuilder->MapTypeInstPtr(classVDataType->ToTypeInstance()));
  6681. if (mCompiler->mOptions.mObjectHasDebugFlags)
  6682. {
  6683. SizedArray<BfIRValue, 4> llvmArgs;
  6684. llvmArgs.push_back(vData);
  6685. llvmArgs.push_back(sizeValue);
  6686. llvmArgs.push_back(GetConstValue(typeInstance->mAlign));
  6687. llvmArgs.push_back(GetConstValue(stackCount));
  6688. auto moduleMethodInstance = GetInternalMethod("Dbg_ObjectAlloc", 4);
  6689. BfIRValue objectVal = mBfIRBuilder->CreateCall(moduleMethodInstance.mFunc, llvmArgs);
  6690. result = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(typeInstance));
  6691. }
  6692. else
  6693. {
  6694. SizedArray<BfIRValue, 4> llvmArgs;
  6695. llvmArgs.push_back(sizeValue);
  6696. BfIRFunction irFunc;
  6697. if (mCompiler->mOptions.mDebugAlloc)
  6698. {
  6699. auto moduleMethodInstance = GetInternalMethod("Dbg_RawObjectAlloc", 1);
  6700. irFunc = moduleMethodInstance.mFunc;
  6701. }
  6702. if (!irFunc)
  6703. irFunc = GetBuiltInFunc(BfBuiltInFuncType_Malloc);
  6704. BfIRValue objectVal = mBfIRBuilder->CreateCall(irFunc, llvmArgs);
  6705. auto objResult = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(mContext->mBfObjectType, BfIRPopulateType_Full));
  6706. auto vdataPtr = mBfIRBuilder->CreateInBoundsGEP(objResult, 0, 0);
  6707. mBfIRBuilder->CreateStore(vData, vdataPtr);
  6708. result = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(typeInstance));
  6709. }
  6710. }
  6711. if ((zeroMemory) && (arraySize))
  6712. {
  6713. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  6714. typeInstance = arrayType;
  6715. auto firstElementField = &arrayType->mFieldInstances.back();
  6716. int arrayClassSize = firstElementField->mDataOffset;
  6717. BfIRValue elementDataSize;
  6718. bool skipZero = false;
  6719. if (arraySize.IsConst())
  6720. {
  6721. BfIRValue arraySizeMinusOne = mBfIRBuilder->CreateSub(arraySize, GetConstValue(1));
  6722. elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySizeMinusOne);
  6723. elementDataSize = mBfIRBuilder->CreateAdd(elementDataSize, GetConstValue(type->mSize));
  6724. auto constVal = mBfIRBuilder->GetConstant(elementDataSize);
  6725. if (constVal->mInt64 <= 0)
  6726. skipZero = true;
  6727. }
  6728. else
  6729. {
  6730. // For non const, don't use an unpadded last element - saves us checking against negative numbers going into memset for the zero-length case
  6731. elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  6732. }
  6733. if (!skipZero)
  6734. {
  6735. auto i8Type = GetPrimitiveType(BfTypeCode_Int8);
  6736. auto ptrType = CreatePointerType(i8Type);
  6737. auto ptrVal = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapType(ptrType));
  6738. ptrVal = mBfIRBuilder->CreateInBoundsGEP(ptrVal, arrayClassSize);
  6739. mBfIRBuilder->CreateMemSet(ptrVal, GetConstValue8(0), elementDataSize, type->mAlign);
  6740. appendSizeValue = elementDataSize;
  6741. }
  6742. }
  6743. return result;
  6744. }
  6745. else
  6746. {
  6747. if (!sizeValue)
  6748. sizeValue = GetConstValue(allocSize);
  6749. return AllocBytes(allocTarget.mRefNode, allocTarget, type, sizeValue, GetConstValue(allocAlign), zeroMemory ? BfAllocFlags_ZeroMemory : BfAllocFlags_None);
  6750. }
  6751. }
  6752. void BfModule::ValidateAllocation(BfType* type, BfAstNode* refNode)
  6753. {
  6754. if ((type == NULL) || (refNode == NULL))
  6755. return;
  6756. auto typeInstance = type->ToTypeInstance();
  6757. if ((typeInstance != NULL) && (typeInstance->mTypeDef->mIsOpaque))
  6758. Fail(StrFormat("Unable to allocate opaque type '%s'", TypeToString(type).c_str()), refNode);
  6759. }
  6760. void BfModule::EmitAlign(BfIRValue& appendCurIdx, int align)
  6761. {
  6762. appendCurIdx = mBfIRBuilder->CreateAdd(appendCurIdx, GetConstValue(align - 1));
  6763. appendCurIdx = mBfIRBuilder->CreateAnd(appendCurIdx, GetConstValue(~(align - 1)));
  6764. }
  6765. void BfModule::EmitAppendAlign(int align, int sizeMultiple)
  6766. {
  6767. if (sizeMultiple == 0)
  6768. sizeMultiple = align;
  6769. if ((mCurMethodState->mCurAppendAlign != 0) && (mCurMethodState->mCurAppendAlign % align != 0))
  6770. {
  6771. if (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Ctor)
  6772. {
  6773. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  6774. BF_ASSERT(localVar->mName == "appendIdx");
  6775. auto appendIdxVal = BfTypedValue(localVar->mValue, localVar->mResolvedType, true);
  6776. BfIRValue appendCurIdx = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  6777. if (align > 1)
  6778. {
  6779. appendCurIdx = mBfIRBuilder->CreateAdd(appendCurIdx, GetConstValue(align - 1));
  6780. appendCurIdx = mBfIRBuilder->CreateAnd(appendCurIdx, GetConstValue(~(align - 1)));
  6781. }
  6782. mBfIRBuilder->CreateStore(appendCurIdx, appendIdxVal.mValue);
  6783. }
  6784. else
  6785. {
  6786. BF_ASSERT(mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend);
  6787. BfIRValue appendCurIdxPtr = mCurMethodState->mRetVal.mValue;
  6788. BfIRValue appendCurIdx = mBfIRBuilder->CreateLoad(appendCurIdxPtr);
  6789. appendCurIdx = mBfIRBuilder->CreateAdd(appendCurIdx, GetConstValue(align - 1));
  6790. appendCurIdx = mBfIRBuilder->CreateAnd(appendCurIdx, GetConstValue(~(align - 1)));
  6791. mBfIRBuilder->CreateStore(appendCurIdx, appendCurIdxPtr);
  6792. }
  6793. }
  6794. if (mCurMethodState->mCurAppendAlign == 0)
  6795. mCurMethodState->mCurAppendAlign = sizeMultiple;
  6796. else
  6797. {
  6798. if (sizeMultiple % align == 0)
  6799. mCurMethodState->mCurAppendAlign = align;
  6800. else
  6801. mCurMethodState->mCurAppendAlign = sizeMultiple % align;
  6802. }
  6803. }
  6804. BfIRValue BfModule::AppendAllocFromType(BfType* type, BfIRValue appendSizeValue, int appendAllocAlign, BfIRValue arraySize, int arrayDim, bool isRawArrayAlloc, bool zeroMemory)
  6805. {
  6806. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  6807. BF_ASSERT(localVar->mName == "appendIdx");
  6808. BfTypedValue appendIdxVal(localVar->mValue, localVar->mResolvedType, true);
  6809. BfIRValue retValue;
  6810. BfTypeInstance* retTypeInstance = NULL;
  6811. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  6812. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  6813. if (arraySize)
  6814. {
  6815. if (isRawArrayAlloc)
  6816. {
  6817. EmitAppendAlign(type->mAlign);
  6818. BfPointerType* ptrType = CreatePointerType(type);
  6819. BfIRValue sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->mSize), arraySize);
  6820. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  6821. if (mSystem->mPtrSize != 4)
  6822. sizeValue = mBfIRBuilder->CreateNumericCast(sizeValue, true, (intPtrType->mSize == 4) ? BfTypeCode_Int32 : BfTypeCode_Int64);
  6823. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  6824. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  6825. if (zeroMemory)
  6826. {
  6827. auto ptr = mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(voidPtrType));
  6828. mBfIRBuilder->CreateMemSet(ptr, GetConstValue8(0), sizeValue, type->mAlign);
  6829. }
  6830. return mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(ptrType));
  6831. }
  6832. else
  6833. {
  6834. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  6835. EmitAppendAlign(arrayType->mAlign, type->mSize);
  6836. auto firstElementField = &arrayType->mFieldInstances.back();
  6837. int arrayClassSize = arrayType->mInstSize - firstElementField->mDataSize;
  6838. BfIRValue sizeValue = GetConstValue(arrayClassSize);
  6839. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->mSize), arraySize);
  6840. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  6841. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  6842. if (mSystem->mPtrSize != 4)
  6843. sizeValue = mBfIRBuilder->CreateNumericCast(sizeValue, true, (intPtrType->mSize == 4) ? BfTypeCode_Int32 : BfTypeCode_Int64);
  6844. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  6845. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  6846. if (zeroMemory)
  6847. {
  6848. // Only zero out the actual elements
  6849. int dataOffset = arrayType->mFieldInstances.back().mDataOffset;
  6850. auto newOffset = mBfIRBuilder->CreateAdd(curIdxVal, GetConstValue(dataOffset));
  6851. auto newSize = mBfIRBuilder->CreateSub(sizeValue, GetConstValue(dataOffset));
  6852. auto ptr = mBfIRBuilder->CreateIntToPtr(newOffset, mBfIRBuilder->MapType(voidPtrType));
  6853. mBfIRBuilder->CreateMemSet(ptr, GetConstValue8(0), newSize, type->mAlign);
  6854. }
  6855. retTypeInstance = arrayType;
  6856. retValue = mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(arrayType));
  6857. }
  6858. }
  6859. else
  6860. {
  6861. auto typeInst = type->ToTypeInstance();
  6862. BfIRValue sizeValue;
  6863. BfIRType toType;
  6864. if (typeInst != NULL)
  6865. {
  6866. EmitAppendAlign(typeInst->mInstAlign, typeInst->mInstSize);
  6867. sizeValue = GetConstValue(typeInst->mInstSize);
  6868. toType = mBfIRBuilder->MapTypeInstPtr(typeInst);
  6869. }
  6870. else
  6871. {
  6872. EmitAppendAlign(type->mAlign, type->mSize);
  6873. sizeValue = GetConstValue(type->mSize);
  6874. auto toPtrType = CreatePointerType(type);
  6875. toType = mBfIRBuilder->MapType(toPtrType);
  6876. }
  6877. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  6878. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  6879. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  6880. retTypeInstance = typeInst;
  6881. retValue = mBfIRBuilder->CreateIntToPtr(curIdxVal, toType);
  6882. }
  6883. if ((retTypeInstance != NULL) && (retTypeInstance->IsObject()))
  6884. {
  6885. mBfIRBuilder->PopulateType(retTypeInstance);
  6886. auto int8Type = mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8);
  6887. auto ptrType = mBfIRBuilder->GetPointerTo(int8Type);
  6888. auto ptrPtrType = mBfIRBuilder->GetPointerTo(ptrType);
  6889. auto curThis = GetThis();
  6890. BfIRValue newFlags;
  6891. if (mCompiler->mOptions.mObjectHasDebugFlags)
  6892. {
  6893. auto thisFlagsPtr = mBfIRBuilder->CreateBitCast(curThis.mValue, ptrType);
  6894. auto thisFlags = mBfIRBuilder->CreateLoad(thisFlagsPtr);
  6895. auto maskedThisFlags = mBfIRBuilder->CreateAnd(thisFlags, GetConstValue8(BfObjectFlag_StackAlloc)); // Take 'stack' flag from 'this'
  6896. newFlags = mBfIRBuilder->CreateOr(maskedThisFlags, GetConstValue8(BfObjectFlag_AppendAlloc));
  6897. }
  6898. auto vObjectAddr = mBfIRBuilder->CreateInBoundsGEP(retValue, 0, 0);
  6899. auto vDataRef = CreateClassVDataGlobal(retTypeInstance);
  6900. auto destAddr = mBfIRBuilder->CreateBitCast(vObjectAddr, ptrPtrType);
  6901. auto srcVal = mBfIRBuilder->CreateBitCast(vDataRef, ptrType);
  6902. mBfIRBuilder->CreateStore(srcVal, destAddr);
  6903. if (mCompiler->mOptions.mObjectHasDebugFlags)
  6904. {
  6905. auto flagsPtr = mBfIRBuilder->CreateBitCast(destAddr, ptrType);
  6906. mBfIRBuilder->CreateStore(newFlags, flagsPtr);
  6907. }
  6908. }
  6909. if (appendSizeValue)
  6910. {
  6911. EmitAppendAlign(appendAllocAlign);
  6912. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  6913. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, appendSizeValue);
  6914. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  6915. }
  6916. return retValue;
  6917. }
  6918. bool BfModule::IsOptimized()
  6919. {
  6920. if (mProject == NULL)
  6921. return false;
  6922. int optLevel = GetModuleOptions().mOptLevel;
  6923. return (optLevel >= BfOptLevel_O1) && (optLevel <= BfOptLevel_O3);
  6924. }
  6925. bool BfModule::IsTargetingBeefBackend()
  6926. {
  6927. if (mProject == NULL)
  6928. return false;
  6929. return GetModuleOptions().mOptLevel == BfOptLevel_OgPlus;
  6930. }
  6931. bool BfModule::WantsLifetimes()
  6932. {
  6933. if (mProject == NULL)
  6934. return false;
  6935. return GetModuleOptions().mOptLevel == BfOptLevel_OgPlus;
  6936. }
  6937. bool BfModule::HasCompiledOutput()
  6938. {
  6939. return (!mSystem->mIsResolveOnly) && (mIsReified);
  6940. }
  6941. // We will skip the object access check for any occurances of this value
  6942. void BfModule::SkipObjectAccessCheck(BfTypedValue typedVal)
  6943. {
  6944. if ((mBfIRBuilder->mIgnoreWrites) || (!typedVal.mType->IsObjectOrInterface()) || (mCurMethodState == NULL) || (mCurMethodState->mIgnoreObjectAccessCheck))
  6945. return;
  6946. if (!mCompiler->mOptions.mObjectHasDebugFlags)
  6947. return;
  6948. if ((typedVal.mValue.mFlags & BfIRValueFlags_Value) == 0)
  6949. return;
  6950. mCurMethodState->mSkipObjectAccessChecks.Add(typedVal.mValue.mId);
  6951. }
  6952. void BfModule::EmitObjectAccessCheck(BfTypedValue typedVal)
  6953. {
  6954. if ((mBfIRBuilder->mIgnoreWrites) || (!typedVal.mType->IsObjectOrInterface()) || (mCurMethodState == NULL) || (mCurMethodState->mIgnoreObjectAccessCheck))
  6955. return;
  6956. if (!mCompiler->mOptions.mObjectHasDebugFlags)
  6957. return;
  6958. bool emitObjectAccessCheck = mCompiler->mOptions.mEmitObjectAccessCheck;
  6959. auto typeOptions = GetTypeOptions();
  6960. if (typeOptions != NULL)
  6961. emitObjectAccessCheck = BfTypeOptions::Apply(emitObjectAccessCheck, typeOptions->mEmitObjectAccessCheck);
  6962. if (!emitObjectAccessCheck)
  6963. return;
  6964. if ((typedVal.mValue.mFlags & BfIRValueFlags_Value) != 0)
  6965. {
  6966. if (mCurMethodState->mSkipObjectAccessChecks.Contains(typedVal.mValue.mId))
  6967. return;
  6968. }
  6969. if (typedVal.IsAddr())
  6970. typedVal = LoadValue(typedVal);
  6971. mBfIRBuilder->CreateObjectAccessCheck(typedVal.mValue, !IsOptimized());
  6972. }
  6973. void BfModule::EmitEnsureInstructionAt()
  6974. {
  6975. if (mProject == NULL)
  6976. return;
  6977. if ((mBfIRBuilder->mIgnoreWrites) || (!mHasFullDebugInfo) || (IsOptimized()) || (mCompiler->mOptions.mOmitDebugHelpers))
  6978. return;
  6979. mBfIRBuilder->CreateEnsureInstructionAt();
  6980. }
  6981. void BfModule::EmitDynamicCastCheck(const BfTypedValue& targetValue, BfType* targetType, BfIRBlock trueBlock, BfIRBlock falseBlock, bool nullSucceeds)
  6982. {
  6983. if (mBfIRBuilder->mIgnoreWrites)
  6984. return; // Nothing needed here
  6985. auto irb = mBfIRBuilder;
  6986. auto checkBB = irb->CreateBlock("as.check");
  6987. auto isNull = irb->CreateIsNull(targetValue.mValue);
  6988. mBfIRBuilder->CreateCondBr(isNull, nullSucceeds ? trueBlock : falseBlock, checkBB);
  6989. auto intType = GetPrimitiveType(BfTypeCode_IntPtr);
  6990. auto intPtrType = CreatePointerType(intType);
  6991. auto intPtrPtrType = CreatePointerType(intPtrType);
  6992. auto int32Type = GetPrimitiveType(BfTypeCode_Int32);
  6993. auto int32PtrType = CreatePointerType(int32Type);
  6994. auto typeTypeInstance = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef)->ToTypeInstance();
  6995. if (mCompiler->mOptions.mAllowHotSwapping)
  6996. {
  6997. BfExprEvaluator exprEvaluator(this);
  6998. AddBasicBlock(checkBB);
  6999. auto objectParam = mBfIRBuilder->CreateBitCast(targetValue.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType));
  7000. auto moduleMethodInstance = GetMethodByName(mContext->mBfObjectType, targetType->IsInterface() ? "DynamicCastToInterface" : "DynamicCastToTypeId");
  7001. SizedArray<BfIRValue, 4> irArgs;
  7002. irArgs.push_back(objectParam);
  7003. irArgs.push_back(GetConstValue32(targetType->mTypeId));
  7004. auto callResult = exprEvaluator.CreateCall(moduleMethodInstance.mMethodInstance, moduleMethodInstance.mFunc, false, irArgs);
  7005. auto resultType = ResolveTypeDef(mSystem->mTypeBool);
  7006. auto cmpResult = mBfIRBuilder->CreateCmpNE(callResult.mValue, GetDefaultValue(callResult.mType));
  7007. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  7008. }
  7009. else
  7010. {
  7011. AddBasicBlock(checkBB);
  7012. BfIRValue vDataPtr = irb->CreateBitCast(targetValue.mValue, irb->MapType(intPtrType));
  7013. vDataPtr = irb->CreateLoad(vDataPtr);
  7014. if (mCompiler->mOptions.mObjectHasDebugFlags)
  7015. vDataPtr = irb->CreateAnd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, (uint64)~0xFFULL));
  7016. if (targetType->IsInterface())
  7017. {
  7018. auto targetTypeInst = targetType->ToTypeInstance();
  7019. AddDependency(targetType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  7020. // Skip past mType, but since a 'GetDynCastVDataCount()' data is included in the sSlotOfs, we need to remove that
  7021. //int inheritanceIdOfs = mSystem->mPtrSize - (mCompiler->GetDynCastVDataCount())*4;
  7022. //vDataPtr = irb->CreateAdd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, inheritanceIdOfs));
  7023. vDataPtr = irb->CreateAdd(vDataPtr, irb->GetConfigConst(BfIRConfigConst_DynSlotOfs, BfTypeCode_IntPtr));
  7024. BfIRValue slotOfs = GetInterfaceSlotNum(targetType->ToTypeInstance());
  7025. BfIRValue slotByteOfs = irb->CreateMul(slotOfs, irb->CreateConst(BfTypeCode_Int32, 4));
  7026. slotByteOfs = irb->CreateNumericCast(slotByteOfs, false, BfTypeCode_IntPtr);
  7027. vDataPtr = irb->CreateAdd(vDataPtr, slotByteOfs);
  7028. vDataPtr = irb->CreateIntToPtr(vDataPtr, irb->MapType(int32PtrType));
  7029. BfIRValue typeId = irb->CreateLoad(vDataPtr);
  7030. BfIRValue cmpResult = irb->CreateCmpEQ(typeId, irb->CreateConst(BfTypeCode_Int32, targetType->mTypeId));
  7031. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  7032. }
  7033. else
  7034. {
  7035. if (!targetType->IsTypeInstance())
  7036. targetType = GetWrappedStructType(targetType);
  7037. AddDependency(targetType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  7038. int inheritanceIdOfs = mSystem->mPtrSize;
  7039. vDataPtr = irb->CreateAdd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, inheritanceIdOfs));
  7040. vDataPtr = irb->CreateIntToPtr(vDataPtr, irb->MapType(int32PtrType));
  7041. BfIRValue objInheritanceId = irb->CreateLoad(vDataPtr);
  7042. BfIRValue typeDataRef = CreateTypeDataRef(targetType);
  7043. BfIRValue typeInstDataRef = irb->CreateBitCast(typeDataRef, irb->MapType(typeTypeInstance, BfIRPopulateType_Full));
  7044. auto fieldInst = &typeTypeInstance->mFieldInstances[9];
  7045. BF_ASSERT(fieldInst->GetFieldDef()->mName == "mInheritanceId");
  7046. BfIRValue gepValue = irb->CreateInBoundsGEP(typeInstDataRef, 0, fieldInst->mDataIdx);
  7047. BfIRValue wantInheritanceId = irb->CreateLoad(gepValue);
  7048. fieldInst = &typeTypeInstance->mFieldInstances[10];
  7049. BF_ASSERT(fieldInst->GetFieldDef()->mName == "mInheritanceCount");
  7050. gepValue = irb->CreateInBoundsGEP(typeInstDataRef, 0, fieldInst->mDataIdx);
  7051. BfIRValue inheritanceCount = irb->CreateLoad(gepValue);
  7052. BfIRValue idDiff = irb->CreateSub(objInheritanceId, wantInheritanceId);
  7053. BfIRValue cmpResult = irb->CreateCmpLTE(idDiff, inheritanceCount, false);
  7054. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  7055. }
  7056. }
  7057. }
  7058. void BfModule::EmitDynamicCastCheck(BfTypedValue typedVal, BfType* type, bool allowNull)
  7059. {
  7060. bool emitDynamicCastCheck = mCompiler->mOptions.mEmitDynamicCastCheck;
  7061. auto typeOptions = GetTypeOptions();
  7062. if (typeOptions != NULL)
  7063. emitDynamicCastCheck = BfTypeOptions::Apply(emitDynamicCastCheck, typeOptions->mEmitDynamicCastCheck);
  7064. if (emitDynamicCastCheck)
  7065. {
  7066. int wantTypeId = 0;
  7067. if (!type->IsGenericParam())
  7068. wantTypeId = type->mTypeId;
  7069. BfIRBlock failBlock = mBfIRBuilder->CreateBlock("dynFail");
  7070. BfIRBlock endBlock = mBfIRBuilder->CreateBlock("dynEnd");
  7071. EmitDynamicCastCheck(typedVal, type, endBlock, failBlock, allowNull ? true : false);
  7072. AddBasicBlock(failBlock);
  7073. SizedArray<BfIRValue, 8> llvmArgs;
  7074. auto bitAddr = mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType));
  7075. llvmArgs.push_back(bitAddr);
  7076. llvmArgs.push_back(GetConstValue32(wantTypeId));
  7077. auto objDynCheck = GetInternalMethod("ObjectDynCheckFailed");
  7078. BF_ASSERT(objDynCheck);
  7079. if (objDynCheck)
  7080. {
  7081. auto callInst = mBfIRBuilder->CreateCall(objDynCheck.mFunc, llvmArgs);
  7082. }
  7083. mBfIRBuilder->CreateBr(endBlock);
  7084. AddBasicBlock(endBlock);
  7085. }
  7086. }
  7087. BfTypedValue BfModule::BoxValue(BfAstNode* srcNode, BfTypedValue typedVal, BfType* toType, const BfAllocTarget& allocTarget, bool callDtor)
  7088. {
  7089. BP_ZONE("BoxValue");
  7090. BfTypeInstance* fromStructTypeInstance = typedVal.mType->ToTypeInstance();
  7091. if (typedVal.mType->IsNullable())
  7092. {
  7093. typedVal = MakeAddressable(typedVal);
  7094. auto innerType = typedVal.mType->GetUnderlyingType();
  7095. if (!innerType->IsValueType())
  7096. {
  7097. Fail("Only value types can be boxed", srcNode);
  7098. return BfTypedValue();
  7099. }
  7100. auto prevBB = mBfIRBuilder->GetInsertBlock();
  7101. auto boxBB = mBfIRBuilder->CreateBlock("boxedN.notNull");
  7102. auto endBB = mBfIRBuilder->CreateBlock("boxedN.end");
  7103. mBfIRBuilder->PopulateType(typedVal.mType);
  7104. auto hasValueAddr = mBfIRBuilder->CreateInBoundsGEP(typedVal.mValue, 0, innerType->IsValuelessType() ? 1 : 2); // has_value
  7105. auto hasValue = mBfIRBuilder->CreateLoad(hasValueAddr);
  7106. mBfIRBuilder->CreateCondBr(hasValue, boxBB, endBB);
  7107. auto boxedType = CreateBoxedType(innerType);
  7108. AddDependency(boxedType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  7109. auto resultType = toType;
  7110. if (resultType == NULL)
  7111. resultType = boxedType;
  7112. mBfIRBuilder->AddBlock(boxBB);
  7113. mBfIRBuilder->SetInsertPoint(boxBB);
  7114. BfScopeData newScope;
  7115. newScope.mOuterIsConditional = true;
  7116. mCurMethodState->AddScope(&newScope);
  7117. NewScopeState();
  7118. BfIRValue nullableValueAddr;
  7119. BfIRValue loadedVal;
  7120. if (innerType->IsValuelessType())
  7121. {
  7122. loadedVal = mBfIRBuilder->GetFakeVal();
  7123. }
  7124. else
  7125. {
  7126. nullableValueAddr = mBfIRBuilder->CreateInBoundsGEP(typedVal.mValue, 0, 1); // value
  7127. loadedVal = mBfIRBuilder->CreateLoad(nullableValueAddr);
  7128. }
  7129. auto boxedVal = BoxValue(srcNode, BfTypedValue(loadedVal, fromStructTypeInstance->GetUnderlyingType()), resultType, allocTarget, callDtor);
  7130. RestoreScopeState();
  7131. if (!boxedVal)
  7132. return BfTypedValue();
  7133. mBfIRBuilder->CreateBr(endBB);
  7134. auto boxBBEnd = mBfIRBuilder->GetInsertBlock();
  7135. mBfIRBuilder->AddBlock(endBB);
  7136. mBfIRBuilder->SetInsertPoint(endBB);
  7137. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapType(resultType), 2);
  7138. mBfIRBuilder->AddPhiIncoming(phi, boxedVal.mValue, boxBBEnd);
  7139. mBfIRBuilder->AddPhiIncoming(phi, GetDefaultValue(resultType), prevBB);
  7140. return BfTypedValue(phi, resultType);
  7141. }
  7142. bool alreadyCheckedCast = false;
  7143. BfTypeInstance* toTypeInstance = NULL;
  7144. if (toType != NULL)
  7145. toTypeInstance = toType->ToTypeInstance();
  7146. bool isStructPtr = typedVal.mType->IsStructPtr();
  7147. if (fromStructTypeInstance == NULL)
  7148. {
  7149. auto primType = (BfPrimitiveType*)typedVal.mType;
  7150. fromStructTypeInstance = GetWrappedStructType(typedVal.mType);
  7151. if (isStructPtr)
  7152. {
  7153. if ((toTypeInstance != NULL) && (TypeIsSubTypeOf(fromStructTypeInstance, toTypeInstance)))
  7154. alreadyCheckedCast = true;
  7155. fromStructTypeInstance = typedVal.mType->GetUnderlyingType()->ToTypeInstance();
  7156. }
  7157. }
  7158. if (fromStructTypeInstance == NULL)
  7159. return BfTypedValue();
  7160. // Need to box it
  7161. auto boxedType = CreateBoxedType(typedVal.mType);
  7162. bool isBoxedType = (fromStructTypeInstance != NULL) && (toType->IsBoxed()) && (boxedType == toType);
  7163. if ((toType == NULL) || (toType == mContext->mBfObjectType) || (isBoxedType) || (alreadyCheckedCast) || (TypeIsSubTypeOf(fromStructTypeInstance, toTypeInstance)))
  7164. {
  7165. if (typedVal.mType->IsPointer())
  7166. {
  7167. NOP;
  7168. }
  7169. mBfIRBuilder->PopulateType(boxedType);
  7170. AddDependency(boxedType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  7171. auto allocaInst = AllocFromType(boxedType, allocTarget, BfIRValue(), BfIRValue(), 0, callDtor ? BfAllocFlags_None : BfAllocFlags_NoDtorCall);
  7172. BfTypedValue boxedTypedValue(allocaInst, boxedType);
  7173. mBfIRBuilder->SetName(allocaInst, "boxed." + fromStructTypeInstance->mTypeDef->mName->ToString());
  7174. if (boxedType->IsUnspecializedType())
  7175. {
  7176. BF_ASSERT(mCurMethodInstance->mIsUnspecialized);
  7177. }
  7178. else
  7179. {
  7180. PopulateType(fromStructTypeInstance);
  7181. if (!fromStructTypeInstance->IsValuelessType())
  7182. {
  7183. typedVal = LoadValue(typedVal);
  7184. auto valPtr = mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 1);
  7185. if ((typedVal.mType != fromStructTypeInstance) && (!isStructPtr))
  7186. {
  7187. auto ptrType = CreatePointerType(typedVal.mType);
  7188. valPtr = mBfIRBuilder->CreateBitCast(valPtr, mBfIRBuilder->MapType(ptrType));
  7189. }
  7190. if (typedVal.IsSplat())
  7191. {
  7192. AggregateSplatIntoAddr(typedVal, valPtr);
  7193. }
  7194. else
  7195. mBfIRBuilder->CreateStore(typedVal.mValue, valPtr);
  7196. }
  7197. }
  7198. if (toType == NULL)
  7199. {
  7200. return BfTypedValue(allocaInst, boxedType);
  7201. }
  7202. else
  7203. {
  7204. auto castedValue = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(toType));
  7205. return BfTypedValue(castedValue, toType);
  7206. }
  7207. }
  7208. return BfTypedValue();
  7209. }
  7210. bool BfModule::GetBasePropertyDef(BfPropertyDef*& propDef, BfTypeInstance*& typeInst)
  7211. {
  7212. BfTypeInstance* checkTypeInst = typeInst;
  7213. while (checkTypeInst != NULL)
  7214. {
  7215. for (auto checkProp : checkTypeInst->mTypeDef->mProperties)
  7216. {
  7217. if (checkProp->mName == propDef->mName)
  7218. {
  7219. auto checkPropDeclaration = BfNodeDynCast<BfPropertyDeclaration>(checkProp->mFieldDeclaration);
  7220. if ((checkPropDeclaration == NULL) || (checkPropDeclaration->mVirtualSpecifier == NULL) || (checkPropDeclaration->mVirtualSpecifier->GetToken() == BfToken_Virtual))
  7221. {
  7222. propDef = checkProp;
  7223. typeInst = checkTypeInst;
  7224. return true;
  7225. }
  7226. }
  7227. }
  7228. checkTypeInst = checkTypeInst->mBaseType;
  7229. }
  7230. return false;
  7231. }
  7232. BfMethodInstance* BfModule::GetRawMethodInstanceAtIdx(BfTypeInstance* typeInstance, int methodIdx, const char* assertName)
  7233. {
  7234. if (!typeInstance->mResolvingVarField)
  7235. {
  7236. if (typeInstance->IsIncomplete())
  7237. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7238. }
  7239. else
  7240. {
  7241. if (methodIdx >= (int)typeInstance->mMethodInstanceGroups.size())
  7242. {
  7243. AssertErrorState();
  7244. return NULL;
  7245. }
  7246. }
  7247. if (assertName != NULL)
  7248. {
  7249. BF_ASSERT(typeInstance->mTypeDef->mMethods[methodIdx]->mName == assertName);
  7250. }
  7251. auto& methodGroup = typeInstance->mMethodInstanceGroups[methodIdx];
  7252. if (methodGroup.mDefault == NULL)
  7253. {
  7254. if (!mCompiler->mIsResolveOnly)
  7255. {
  7256. BF_ASSERT((methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) || (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl));
  7257. methodGroup.mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingDecl;
  7258. // Get it from the owning module so we don't create a reference prematurely...
  7259. auto declModule = typeInstance->mModule;
  7260. return declModule->GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector(), (BfGetMethodInstanceFlags)(BfGetMethodInstanceFlag_UnspecializedPass | BfGetMethodInstanceFlag_Unreified)).mMethodInstance;
  7261. }
  7262. else
  7263. {
  7264. auto declModule = typeInstance->mModule;
  7265. return declModule->GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector(), (BfGetMethodInstanceFlags)(BfGetMethodInstanceFlag_UnspecializedPass)).mMethodInstance;
  7266. }
  7267. }
  7268. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  7269. //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
  7270. // be from a call to the NON-raw version
  7271. // if (!methodInstance->mMethodInstanceGroup->IsImplemented())
  7272. // {
  7273. // methodInstance->mIsReified = mIsReified;
  7274. // if (methodInstance->mMethodProcessRequest == NULL)
  7275. // typeInstance->mModule->AddMethodToWorkList(methodInstance);
  7276. // }
  7277. return methodInstance;
  7278. }
  7279. BfMethodInstance* BfModule::GetRawMethodInstance(BfTypeInstance* typeInstance, BfMethodDef* methodDef)
  7280. {
  7281. if (methodDef->mIsLocalMethod)
  7282. {
  7283. return GetMethodInstance(typeInstance, methodDef, BfTypeVector()).mMethodInstance;
  7284. }
  7285. return GetRawMethodInstanceAtIdx(typeInstance, methodDef->mIdx);
  7286. }
  7287. BfMethodInstance* BfModule::GetRawMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase, bool allowMixin)
  7288. {
  7289. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7290. while (typeInstance != NULL)
  7291. {
  7292. typeInstance->mTypeDef->PopulateMemberSets();
  7293. BfMemberSetEntry* entry = NULL;
  7294. BfMethodDef* methodDef = NULL;
  7295. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  7296. methodDef = (BfMethodDef*)entry->mMemberDef;
  7297. while (methodDef != NULL)
  7298. {
  7299. if (((allowMixin) || (methodDef->mMethodType != BfMethodType_Mixin)) &&
  7300. (methodDef->mGenericParams.size() == 0) &&
  7301. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  7302. return GetRawMethodInstance(typeInstance, methodDef);
  7303. methodDef = methodDef->mNextWithSameName;
  7304. }
  7305. if (!checkBase)
  7306. break;
  7307. typeInstance = typeInstance->mBaseType;
  7308. }
  7309. return NULL;
  7310. }
  7311. BfMethodInstance* BfModule::GetUnspecializedMethodInstance(BfMethodInstance* methodInstance)
  7312. {
  7313. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mMethodGenericArguments.size() != 0))
  7314. methodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  7315. auto owner = methodInstance->mMethodInstanceGroup->mOwner;
  7316. if (!owner->IsGenericTypeInstance())
  7317. return methodInstance;
  7318. auto genericType = (BfGenericTypeInstance*)owner;
  7319. if (genericType->IsUnspecializedType())
  7320. return methodInstance;
  7321. auto unspecializedType = ResolveTypeDef(genericType->mTypeDef);
  7322. if (unspecializedType == NULL)
  7323. {
  7324. AssertErrorState();
  7325. return methodInstance;
  7326. }
  7327. if (unspecializedType == NULL)
  7328. return methodInstance;
  7329. auto unspecializedTypeInst = unspecializedType->ToTypeInstance();
  7330. return GetRawMethodInstanceAtIdx(unspecializedTypeInst, methodInstance->mMethodDef->mIdx);
  7331. }
  7332. int BfModule::GetGenericParamAndReturnCount(BfMethodInstance* methodInstance)
  7333. {
  7334. int genericCount = 0;
  7335. auto unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance);
  7336. for (int paramIdx = 0; paramIdx < unspecializedMethodInstance->GetParamCount(); paramIdx++)
  7337. {
  7338. auto param = unspecializedMethodInstance->GetParamType(paramIdx);
  7339. if (param->IsGenericParam())
  7340. genericCount++;
  7341. }
  7342. if (unspecializedMethodInstance->mReturnType->IsGenericParam())
  7343. genericCount++;
  7344. return genericCount;
  7345. }
  7346. BfModule* BfModule::GetSpecializedMethodModule(const Array<BfProject*>& projectList)
  7347. {
  7348. BF_ASSERT(!mIsScratchModule);
  7349. BF_ASSERT(mIsReified);
  7350. BfModule* mainModule = this;
  7351. if (mParentModule != NULL)
  7352. mainModule = mParentModule;
  7353. BfModule* specModule = NULL;
  7354. BfModule** specModulePtr = NULL;
  7355. if (mainModule->mSpecializedMethodModules.TryGetValue(projectList, &specModulePtr))
  7356. {
  7357. return *specModulePtr;
  7358. }
  7359. else
  7360. {
  7361. String specModuleName = mModuleName;
  7362. for (auto bfProject : projectList)
  7363. specModuleName += StrFormat("@%s", bfProject->mName.c_str());
  7364. specModule = new BfModule(mContext, specModuleName);
  7365. specModule->mProject = mainModule->mProject;
  7366. specModule->mParentModule = mainModule;
  7367. specModule->mIsSpecializedMethodModuleRoot = true;
  7368. specModule->Init();
  7369. mainModule->mSpecializedMethodModules[projectList] = specModule;
  7370. }
  7371. return specModule;
  7372. }
  7373. BfIRValue BfModule::CreateFunctionFrom(BfMethodInstance* methodInstance, bool tryExisting, bool isInlined)
  7374. {
  7375. if (mCompiler->IsSkippingExtraResolveChecks())
  7376. return BfIRValue();
  7377. if (methodInstance->mMethodInstanceGroup->mOwner->IsInterface())
  7378. {
  7379. //BF_ASSERT(!methodInstance->mIRFunction);
  7380. return BfIRValue();
  7381. }
  7382. auto methodDef = methodInstance->mMethodDef;
  7383. StringT<128> methodName;
  7384. BfMangler::Mangle(methodName, mCompiler->GetMangleKind(), methodInstance);
  7385. if (isInlined != methodInstance->mAlwaysInline)
  7386. {
  7387. if (isInlined)
  7388. methodName += "__INLINE";
  7389. else
  7390. methodName += "__NOINLINE";
  7391. }
  7392. if (tryExisting)
  7393. {
  7394. auto func = mBfIRBuilder->GetFunction(methodName);
  7395. if (func)
  7396. return func;
  7397. }
  7398. if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  7399. {
  7400. if (methodDeclaration->mExternSpecifier != NULL)
  7401. {
  7402. auto intrinsic = GetIntrinsic(methodInstance);
  7403. if (intrinsic)
  7404. return intrinsic;
  7405. // If we have multiple entries with the same name, they could have different arguments and will generate other errors...
  7406. /*auto func = mBfIRBuilder->GetFunction(methodName);
  7407. if (func)
  7408. return func;*/
  7409. }
  7410. }
  7411. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  7412. {
  7413. return CreateDllImportGlobalVar(methodInstance, false);
  7414. }
  7415. BfIRType returnType;
  7416. SizedArray<BfIRType, 8> paramTypes;
  7417. methodInstance->GetIRFunctionInfo(this, returnType, paramTypes);
  7418. auto funcType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes);
  7419. auto func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, methodName);
  7420. auto callingConv = GetCallingConvention(methodInstance->GetOwner(), methodDef);
  7421. if (callingConv != BfIRCallingConv_CDecl)
  7422. mBfIRBuilder->SetFuncCallingConv(func, callingConv);
  7423. SetupIRMethod(methodInstance, func, isInlined);
  7424. // auto srcModule = methodInstance->GetOwner()->GetModule();
  7425. // if ((srcModule != NULL) && (srcModule->mProject != mProject))
  7426. // {
  7427. // if (srcModule->mProject->mTargetType == BfTargetType_BeefDynLib)
  7428. // {
  7429. // mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_DllImport);
  7430. // }
  7431. // }
  7432. return func;
  7433. }
  7434. BfModuleMethodInstance BfModule::GetMethodInstanceAtIdx(BfTypeInstance* typeInstance, int methodIdx, const char* assertName)
  7435. {
  7436. if (assertName != NULL)
  7437. {
  7438. BF_ASSERT(typeInstance->mTypeDef->mMethods[methodIdx]->mName == assertName);
  7439. }
  7440. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7441. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  7442. if ((methodInstance != NULL) && (mIsReified) && (!methodInstance->mIsReified))
  7443. {
  7444. // Can't use it, not reified
  7445. methodInstance = NULL;
  7446. }
  7447. if ((methodInstance != NULL) && (mBfIRBuilder != NULL) && (mBfIRBuilder->mIgnoreWrites) &&
  7448. (methodInstance->mMethodInstanceGroup->IsImplemented()))
  7449. {
  7450. BfIRFunction func(mBfIRBuilder->GetFakeVal());
  7451. return BfModuleMethodInstance(methodInstance, func);
  7452. }
  7453. return GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector());
  7454. }
  7455. BfModuleMethodInstance BfModule::GetMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  7456. {
  7457. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7458. while (typeInstance != NULL)
  7459. {
  7460. typeInstance->mTypeDef->PopulateMemberSets();
  7461. BfMemberSetEntry* entry = NULL;
  7462. BfMethodDef* methodDef = NULL;
  7463. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  7464. methodDef = (BfMethodDef*)entry->mMemberDef;
  7465. while (methodDef != NULL)
  7466. {
  7467. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  7468. (methodDef->mGenericParams.size() == 0) &&
  7469. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  7470. return GetMethodInstanceAtIdx(typeInstance, methodDef->mIdx);
  7471. methodDef = methodDef->mNextWithSameName;
  7472. }
  7473. if (!checkBase)
  7474. break;
  7475. typeInstance = typeInstance->mBaseType;
  7476. }
  7477. return BfModuleMethodInstance();
  7478. }
  7479. BfModuleMethodInstance BfModule::GetMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, const Array<BfType*>& paramTypes, bool checkBase)
  7480. {
  7481. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7482. while (typeInstance != NULL)
  7483. {
  7484. typeInstance->mTypeDef->PopulateMemberSets();
  7485. BfMemberSetEntry* entry = NULL;
  7486. BfMethodDef* methodDef = NULL;
  7487. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  7488. methodDef = (BfMethodDef*)entry->mMemberDef;
  7489. while (methodDef != NULL)
  7490. {
  7491. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  7492. (methodDef->mGenericParams.size() == 0) &&
  7493. (paramTypes.size() == methodDef->mParams.size()))
  7494. {
  7495. auto moduleMethodInstance = GetMethodInstanceAtIdx(typeInstance, methodDef->mIdx);
  7496. if (moduleMethodInstance.mMethodInstance != NULL)
  7497. {
  7498. bool matches = true;
  7499. for (int paramIdx = 0; paramIdx < (int)paramTypes.size(); paramIdx++)
  7500. {
  7501. if (moduleMethodInstance.mMethodInstance->GetParamType(paramIdx) != paramTypes[paramIdx])
  7502. matches = false;
  7503. }
  7504. if (matches)
  7505. return moduleMethodInstance;
  7506. }
  7507. }
  7508. methodDef = methodDef->mNextWithSameName;
  7509. }
  7510. if (!checkBase)
  7511. break;
  7512. typeInstance = typeInstance->mBaseType;
  7513. }
  7514. return BfModuleMethodInstance();
  7515. }
  7516. BfModuleMethodInstance BfModule::GetInternalMethod(const StringImpl& methodName, int paramCount)
  7517. {
  7518. auto internalType = ResolveTypeDef(mCompiler->mInternalTypeDef);
  7519. PopulateType(internalType);
  7520. auto moduleMethodInstance = GetMethodByName(internalType->ToTypeInstance(), methodName, paramCount);
  7521. if (!moduleMethodInstance)
  7522. {
  7523. Fail(StrFormat("Failed to find System.Internal method '%s'", methodName.c_str()));
  7524. }
  7525. return moduleMethodInstance;
  7526. }
  7527. bool BfModule::IsMethodImplementedAndReified(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  7528. {
  7529. while (typeInstance != NULL)
  7530. {
  7531. typeInstance->mTypeDef->PopulateMemberSets();
  7532. BfMemberSetEntry* entry = NULL;
  7533. BfMethodDef* methodDef = NULL;
  7534. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  7535. methodDef = (BfMethodDef*)entry->mMemberDef;
  7536. while (methodDef != NULL)
  7537. {
  7538. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  7539. (methodDef->mGenericParams.size() == 0) &&
  7540. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  7541. {
  7542. auto& methodInstanceGroup = typeInstance->mMethodInstanceGroups[methodDef->mIdx];
  7543. if (!methodInstanceGroup.IsImplemented())
  7544. return false;
  7545. if (methodInstanceGroup.mDefault == NULL)
  7546. return false;
  7547. return methodInstanceGroup.mDefault->mIsReified;
  7548. }
  7549. methodDef = methodDef->mNextWithSameName;
  7550. }
  7551. if (!checkBase)
  7552. break;
  7553. typeInstance = typeInstance->mBaseType;
  7554. }
  7555. return false;
  7556. }
  7557. bool BfModule::HasMixin(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  7558. {
  7559. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7560. while (typeInstance != NULL)
  7561. {
  7562. typeInstance->mTypeDef->PopulateMemberSets();
  7563. BfMemberSetEntry* entry = NULL;
  7564. BfMethodDef* methodDef = NULL;
  7565. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  7566. methodDef = (BfMethodDef*)entry->mMemberDef;
  7567. while (methodDef != NULL)
  7568. {
  7569. if ((methodDef->mMethodType == BfMethodType_Mixin) &&
  7570. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  7571. return true;
  7572. methodDef = methodDef->mNextWithSameName;
  7573. }
  7574. if (!checkBase)
  7575. break;
  7576. typeInstance = typeInstance->mBaseType;
  7577. }
  7578. return BfModuleMethodInstance();
  7579. }
  7580. BfFieldInstance* BfModule::GetFieldByName(BfTypeInstance* typeInstance, const StringImpl& fieldName)
  7581. {
  7582. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7583. typeInstance->mTypeDef->PopulateMemberSets();
  7584. BfMemberSetEntry* entry = NULL;
  7585. BfFieldDef* fieldDef = NULL;
  7586. if (typeInstance->mTypeDef->mFieldSet.TryGetWith(fieldName, &entry))
  7587. {
  7588. fieldDef = (BfFieldDef*)entry->mMemberDef;
  7589. return &typeInstance->mFieldInstances[fieldDef->mIdx];
  7590. }
  7591. // for (auto& fieldInst : typeInstance->mFieldInstances)
  7592. // {
  7593. // auto fieldDef = fieldInst.GetFieldDef();
  7594. // if ((fieldDef != NULL) && (fieldDef->mName == fieldName))
  7595. // return &fieldInst;
  7596. // }
  7597. return NULL;
  7598. }
  7599. String BfModule::MethodToString(BfMethodInstance* methodInst, BfMethodNameFlags methodNameFlags, BfTypeVector* methodGenericArgs)
  7600. {
  7601. auto methodDef = methodInst->mMethodDef;
  7602. bool allowResolveGenericParamNames = ((methodNameFlags & BfMethodNameFlag_ResolveGenericParamNames) != 0);
  7603. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  7604. if ((mCurTypeInstance == NULL) || (!mCurTypeInstance->IsUnspecializedTypeVariation()))
  7605. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  7606. BfType* type = methodInst->mMethodInstanceGroup->mOwner;
  7607. if ((methodGenericArgs != NULL) && (type->IsUnspecializedType()))
  7608. type = ResolveGenericType(type, *methodGenericArgs);
  7609. String methodName;
  7610. if ((methodNameFlags & BfMethodNameFlag_OmitTypeName) == 0)
  7611. {
  7612. methodName = TypeToString(type, typeNameFlags);
  7613. if (methodName == "$")
  7614. methodName = "";
  7615. else
  7616. methodName += ".";
  7617. }
  7618. String accessorString;
  7619. StringT<64> methodDefName = methodInst->mMethodDef->mName;
  7620. if (methodInst->mMethodDef->mIsLocalMethod)
  7621. {
  7622. int atPos = (int)methodDefName.IndexOf('$');
  7623. methodDefName.RemoveToEnd(atPos);
  7624. methodDefName.Replace("@", ".");
  7625. }
  7626. else
  7627. {
  7628. int atPos = (int)methodDefName.IndexOf('$');
  7629. if (atPos != -1)
  7630. {
  7631. accessorString = methodDefName.Substring(0, atPos);
  7632. if ((accessorString == "get") || (accessorString == "set"))
  7633. {
  7634. methodDefName = methodDefName.Substring(atPos + 1);
  7635. }
  7636. else
  7637. accessorString = "";
  7638. }
  7639. }
  7640. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mForeignType != NULL))
  7641. {
  7642. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  7643. if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  7644. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  7645. methodName += TypeToString(methodInst->mMethodInfoEx->mForeignType, typeNameFlags);
  7646. methodName += ".";
  7647. }
  7648. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mExplicitInterface != NULL))
  7649. {
  7650. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  7651. if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  7652. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  7653. methodName += TypeToString(methodInst->mMethodInfoEx->mExplicitInterface, typeNameFlags);
  7654. methodName += ".";
  7655. }
  7656. if (methodDef->mMethodType == BfMethodType_Operator)
  7657. {
  7658. BfOperatorDef* operatorDef = (BfOperatorDef*)methodDef;
  7659. if (operatorDef->mOperatorDeclaration->mIsConvOperator)
  7660. {
  7661. // Don't add explicit/implicit part, since that's not available in GCC mangling
  7662. /*if (operatorDef->mOperatorDeclaration->mExplicitToken != NULL)
  7663. {
  7664. if (operatorDef->mOperatorDeclaration->mExplicitToken->GetToken() == BfToken_Explicit)
  7665. methodName += "explicit ";
  7666. else if (operatorDef->mOperatorDeclaration->mExplicitToken->GetToken() == BfToken_Explicit)
  7667. methodName += "explicit ";
  7668. }*/
  7669. methodName += "operator ";
  7670. if (methodInst->mReturnType != NULL)
  7671. methodName += TypeToString(methodInst->mReturnType);
  7672. }
  7673. else
  7674. {
  7675. methodName += "operator";
  7676. if (operatorDef->mOperatorDeclaration->mOpTypeToken != NULL)
  7677. methodName += BfTokenToString(operatorDef->mOperatorDeclaration->mOpTypeToken->GetToken());
  7678. }
  7679. }
  7680. else if (methodDef->mMethodType == BfMethodType_Ctor)
  7681. {
  7682. if (methodDef->mIsStatic)
  7683. methodName += "__BfStaticCtor";
  7684. else
  7685. methodName += "this";
  7686. accessorString = "";
  7687. }
  7688. else if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  7689. {
  7690. methodDef->GetRefNode()->ToString(methodName);
  7691. methodName += " get accessor";
  7692. return methodName;
  7693. }
  7694. else if (methodDef->mMethodType == BfMethodType_PropertySetter)
  7695. {
  7696. methodDef->GetRefNode()->ToString(methodName);
  7697. methodName += " set accessor";
  7698. return methodName;
  7699. }
  7700. else
  7701. methodName += methodDefName;
  7702. BfTypeVector newMethodGenericArgs;
  7703. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mMethodGenericArguments.size() != 0))
  7704. {
  7705. methodName += "<";
  7706. for (int i = 0; i < (int) methodInst->mMethodInfoEx->mMethodGenericArguments.size(); i++)
  7707. {
  7708. if (i > 0)
  7709. methodName += ", ";
  7710. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  7711. //Why did we have this methodInst->mIsUnspecializedVariation check? Sometimes we do need to show errors calling methods that refer back to our types
  7712. //if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  7713. if (allowResolveGenericParamNames)
  7714. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  7715. BfType* type = methodInst->mMethodInfoEx->mMethodGenericArguments[i];
  7716. if ((methodGenericArgs != NULL) && (type->IsUnspecializedType()))
  7717. {
  7718. bool hasEmpty = false;
  7719. for (auto arg : *methodGenericArgs)
  7720. {
  7721. if (arg == NULL)
  7722. hasEmpty = true;
  7723. }
  7724. if (hasEmpty)
  7725. {
  7726. for (int genericIdx = 0; genericIdx < (int)methodGenericArgs->size(); genericIdx++)
  7727. {
  7728. auto arg = (*methodGenericArgs)[genericIdx];
  7729. if (arg != NULL)
  7730. newMethodGenericArgs.push_back(arg);
  7731. else
  7732. {
  7733. auto genericParamInst = methodInst->mMethodInfoEx->mGenericParams[genericIdx];
  7734. if (genericParamInst->mTypeConstraint != NULL)
  7735. newMethodGenericArgs.push_back(genericParamInst->mTypeConstraint);
  7736. else
  7737. newMethodGenericArgs.push_back(mContext->mBfObjectType); // Default
  7738. }
  7739. }
  7740. methodGenericArgs = &newMethodGenericArgs;
  7741. }
  7742. if (type->IsUnspecializedType())
  7743. type = ResolveGenericType(type, *methodGenericArgs);
  7744. }
  7745. methodName += TypeToString(type, typeNameFlags);
  7746. }
  7747. methodName += ">";
  7748. }
  7749. if (accessorString.length() == 0)
  7750. {
  7751. int dispParamIdx = 0;
  7752. methodName += "(";
  7753. for (int paramIdx = 0; paramIdx < (int) methodInst->GetParamCount(); paramIdx++)
  7754. {
  7755. int paramKind = methodInst->GetParamKind(paramIdx);
  7756. if (paramKind == BfParamKind_ImplicitCapture)
  7757. continue;
  7758. if (dispParamIdx > 0)
  7759. methodName += ", ";
  7760. if (paramKind == BfParamKind_Params)
  7761. methodName += "params ";
  7762. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  7763. BfType* type = methodInst->GetParamType(paramIdx);
  7764. if ((methodGenericArgs != NULL) && (type->IsUnspecializedType()))
  7765. type = ResolveGenericType(type, *methodGenericArgs);
  7766. methodName += TypeToString(type, typeNameFlags);
  7767. methodName += " ";
  7768. methodName += methodInst->GetParamName(paramIdx);
  7769. dispParamIdx++;
  7770. }
  7771. methodName += ")";
  7772. }
  7773. if (accessorString.length() != 0)
  7774. {
  7775. methodName += " " + accessorString;
  7776. }
  7777. return methodName;
  7778. }
  7779. static void AddAttributeTargetName(BfAttributeTargets& flagsLeft, BfAttributeTargets checkFlag, String& str, String addString)
  7780. {
  7781. if ((flagsLeft & checkFlag) == 0)
  7782. return;
  7783. if (!str.empty())
  7784. {
  7785. if (flagsLeft == checkFlag)
  7786. {
  7787. if ((int)str.IndexOf(',') != -1)
  7788. str += ", and ";
  7789. else
  7790. str += " and ";
  7791. }
  7792. else
  7793. str += ", ";
  7794. }
  7795. str += addString;
  7796. flagsLeft = (BfAttributeTargets)(flagsLeft & ~checkFlag);
  7797. }
  7798. static String GetAttributesTargetListString(BfAttributeTargets attrTarget)
  7799. {
  7800. String resultStr;
  7801. auto flagsLeft = attrTarget;
  7802. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Assembly, resultStr, "assembly declarations");
  7803. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Module, resultStr, "module declarations");
  7804. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Class, resultStr, "class declarations");
  7805. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Struct, resultStr, "struct declarations");
  7806. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Enum, resultStr, "enum declarations");
  7807. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Constructor, resultStr, "constructor declarations");
  7808. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Method, resultStr, "method declarations");
  7809. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Property, resultStr, "property declarations");
  7810. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Field, resultStr, "field declarations");
  7811. AddAttributeTargetName(flagsLeft, BfAttributeTargets_StaticField, resultStr, "static field declarations");
  7812. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Interface, resultStr, "interface declarations");
  7813. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Parameter, resultStr, "parameter declarations");
  7814. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Delegate, resultStr, "delegate declarations");
  7815. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Function, resultStr, "function declarations");
  7816. AddAttributeTargetName(flagsLeft, BfAttributeTargets_ReturnValue, resultStr, "return value");
  7817. AddAttributeTargetName(flagsLeft, BfAttributeTargets_GenericParameter, resultStr, "generic parameters");
  7818. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Invocation, resultStr, "invocations");
  7819. AddAttributeTargetName(flagsLeft, BfAttributeTargets_MemberAccess, resultStr, "member access");
  7820. if (resultStr.IsEmpty())
  7821. return "<nothing>";
  7822. return resultStr;
  7823. }
  7824. void BfModule::CurrentAddToConstHolder(BfIRValue& irVal)
  7825. {
  7826. auto constant = mBfIRBuilder->GetConstant(irVal);
  7827. int stringPoolIdx = GetStringPoolIdx(irVal, mBfIRBuilder);
  7828. if (stringPoolIdx != -1)
  7829. {
  7830. irVal = mCurTypeInstance->GetOrCreateConstHolder()->CreateConst(BfTypeCode_Int32, stringPoolIdx);
  7831. return;
  7832. }
  7833. if (constant->mConstType == BfConstType_Array)
  7834. {
  7835. auto constArray = (BfConstantArray*)constant;
  7836. SizedArray<BfIRValue, 8> newVals;
  7837. for (auto val : constArray->mValues)
  7838. {
  7839. auto newVal = val;
  7840. CurrentAddToConstHolder(newVal);
  7841. newVals.push_back(newVal);
  7842. }
  7843. irVal = mCurTypeInstance->mConstHolder->CreateConstArray(constArray->mType, newVals);
  7844. return;
  7845. }
  7846. auto origConst = irVal;
  7847. if ((constant->mConstType == BfConstType_BitCast) || (constant->mConstType == BfConstType_BitCastNull))
  7848. {
  7849. auto bitcast = (BfConstantBitCast*)constant;
  7850. constant = mBfIRBuilder->GetConstantById(bitcast->mTarget);
  7851. }
  7852. irVal = mCurTypeInstance->CreateConst(constant, mBfIRBuilder);
  7853. }
  7854. void BfModule::ClearConstData()
  7855. {
  7856. mBfIRBuilder->ClearConstData();
  7857. mStringObjectPool.Clear();
  7858. mStringCharPtrPool.Clear();
  7859. mStringPoolRefs.Clear();
  7860. }
  7861. BfTypedValue BfModule::GetTypedValueFromConstant(BfConstant* constant, BfIRConstHolder* constHolder, BfType* wantType)
  7862. {
  7863. bool isString = false;
  7864. isString = (wantType->IsObject()) && (wantType->ToTypeInstance()->mTypeDef == mCompiler->mStringTypeDef);
  7865. if (wantType->IsPointer())
  7866. isString = true;
  7867. if (!isString)
  7868. {
  7869. switch (constant->mTypeCode)
  7870. {
  7871. case BfTypeCode_Boolean:
  7872. case BfTypeCode_Int8:
  7873. case BfTypeCode_UInt8:
  7874. case BfTypeCode_Int16:
  7875. case BfTypeCode_UInt16:
  7876. case BfTypeCode_Int32:
  7877. case BfTypeCode_UInt32:
  7878. case BfTypeCode_Int64:
  7879. case BfTypeCode_UInt64:
  7880. case BfTypeCode_IntPtr:
  7881. case BfTypeCode_UIntPtr:
  7882. case BfTypeCode_IntUnknown:
  7883. case BfTypeCode_UIntUnknown:
  7884. case BfTypeCode_Char8:
  7885. case BfTypeCode_Char16:
  7886. case BfTypeCode_Char32:
  7887. case BfTypeCode_Single:
  7888. case BfTypeCode_Double:
  7889. {
  7890. auto constVal = mBfIRBuilder->CreateConst(constant, constHolder);
  7891. auto typedValue = BfTypedValue(constVal, GetPrimitiveType(constant->mTypeCode));
  7892. if (typedValue.mType == wantType)
  7893. return typedValue;
  7894. if (wantType->IsTypedPrimitive())
  7895. {
  7896. if (typedValue.mType == wantType->GetUnderlyingType())
  7897. {
  7898. typedValue.mType = wantType;
  7899. return typedValue;
  7900. }
  7901. }
  7902. auto castedTypedValue = Cast(NULL, typedValue, wantType, (BfCastFlags)(BfCastFlags_SilentFail | BfCastFlags_Explicit));
  7903. BF_ASSERT(castedTypedValue);
  7904. return castedTypedValue;
  7905. }
  7906. break;
  7907. }
  7908. }
  7909. BfIRValue irValue = ConstantToCurrent(constant, constHolder, wantType);
  7910. BF_ASSERT(irValue);
  7911. if (!irValue)
  7912. return BfTypedValue();
  7913. return BfTypedValue(irValue, wantType, false);
  7914. }
  7915. BfIRValue BfModule::ConstantToCurrent(BfConstant* constant, BfIRConstHolder* constHolder, BfType* wantType)
  7916. {
  7917. if (constant->mTypeCode == BfTypeCode_NullPtr)
  7918. {
  7919. return GetDefaultValue(wantType);
  7920. }
  7921. bool isString = false;
  7922. isString = (wantType->IsObject()) && (wantType->ToTypeInstance()->mTypeDef == mCompiler->mStringTypeDef);
  7923. if (((wantType->IsPointer()) || (isString)) && (mBfIRBuilder->IsInt(constant->mTypeCode)))
  7924. {
  7925. const StringImpl& str = mContext->mStringObjectIdMap[constant->mInt32].mString;
  7926. BfIRValue stringObjConst = GetStringObjectValue(str);
  7927. if (wantType->IsObject())
  7928. return stringObjConst;
  7929. return GetStringCharPtr(stringObjConst);
  7930. }
  7931. if (constant->mConstType == BfConstType_Array)
  7932. {
  7933. auto elementType = wantType->GetUnderlyingType();
  7934. auto constArray = (BfConstantArray*)constant;
  7935. SizedArray<BfIRValue, 8> newVals;
  7936. for (auto val : constArray->mValues)
  7937. {
  7938. newVals.push_back(ConstantToCurrent(constHolder->GetConstant(val), constHolder, elementType));
  7939. }
  7940. return mBfIRBuilder->CreateConstArray(mBfIRBuilder->MapType(wantType), newVals);
  7941. }
  7942. return mBfIRBuilder->CreateConst(constant, constHolder);
  7943. }
  7944. void BfModule::ValidateCustomAttributes(BfCustomAttributes* customAttributes, BfAttributeTargets attrTarget)
  7945. {
  7946. if (attrTarget == BfAttributeTargets_SkipValidate)
  7947. return;
  7948. for (auto& customAttribute : customAttributes->mAttributes)
  7949. {
  7950. if (!customAttribute.mAwaitingValidation)
  7951. continue;
  7952. if ((customAttribute.mType->mAttributeData->mAttributeTargets & attrTarget) == 0)
  7953. {
  7954. Fail(StrFormat("Attribute '%s' is not valid on this declaration type. It is only valid on %s.",
  7955. customAttribute.mRef->ToString().c_str(), GetAttributesTargetListString(customAttribute.mType->mAttributeData->mAttributeTargets).c_str()), customAttribute.mRef->mAttributeTypeRef); // CS0592
  7956. }
  7957. customAttribute.mAwaitingValidation = false;
  7958. }
  7959. }
  7960. void BfModule::GetCustomAttributes(BfCustomAttributes* customAttributes, BfAttributeDirective* attributesDirective, BfAttributeTargets attrTarget)
  7961. {
  7962. if ((attributesDirective != NULL) && (mCompiler->mResolvePassData != NULL) &&
  7963. (attributesDirective->IsFromParser(mCompiler->mResolvePassData->mParser)) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  7964. {
  7965. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(attributesDirective);
  7966. }
  7967. SetAndRestoreValue<bool> prevIsCapturingMethodMatchInfo;
  7968. if (mCompiler->IsAutocomplete())
  7969. prevIsCapturingMethodMatchInfo.Init(mCompiler->mResolvePassData->mAutoComplete->mIsCapturingMethodMatchInfo, false);
  7970. BfTypeInstance* baseAttrTypeInst = mContext->mUnreifiedModule->ResolveTypeDef(mCompiler->mAttributeTypeDef)->ToTypeInstance();
  7971. BfAttributeTargets targetOverride = (BfAttributeTargets)0;
  7972. BfAutoComplete* autoComplete = NULL;
  7973. if (mCompiler->mResolvePassData != NULL)
  7974. autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  7975. for (; attributesDirective != NULL; attributesDirective = attributesDirective->mNextAttribute)
  7976. {
  7977. BfAutoParentNodeEntry autoParentNodeEntry(this, attributesDirective);
  7978. BfCustomAttribute customAttribute;
  7979. customAttribute.mAwaitingValidation = true;
  7980. customAttribute.mRef = attributesDirective;
  7981. if (attributesDirective->mAttrOpenToken != NULL)
  7982. targetOverride = (BfAttributeTargets)0;
  7983. if (attributesDirective->mAttributeTypeRef == NULL)
  7984. {
  7985. AssertErrorState();
  7986. continue;
  7987. }
  7988. String attrName = attributesDirective->mAttributeTypeRef->ToString();
  7989. BfType* attrType = NULL;
  7990. BfAtomComposite nameComposite;
  7991. BfTypeDef* attrTypeDef = NULL;
  7992. if (mSystem->ParseAtomComposite(attrName + "Attribute", nameComposite))
  7993. {
  7994. BfTypeLookupError error;
  7995. error.mRefNode = attributesDirective->mAttributeTypeRef;
  7996. attrTypeDef = FindTypeDefRaw(nameComposite, 0, mCurTypeInstance, GetActiveTypeDef(NULL, true), &error);
  7997. }
  7998. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  7999. {
  8000. mCompiler->mResolvePassData->mAutoComplete->CheckAttributeTypeRef(attributesDirective->mAttributeTypeRef);
  8001. if (attrTypeDef != NULL)
  8002. mCompiler->mResolvePassData->HandleTypeReference(attributesDirective->mAttributeTypeRef, attrTypeDef);
  8003. }
  8004. if (attrTypeDef == NULL)
  8005. {
  8006. TypeRefNotFound(attributesDirective->mAttributeTypeRef, "Attribute");
  8007. continue;
  8008. }
  8009. bool isBypassedAttr = false;
  8010. if (attrTypeDef != NULL)
  8011. {
  8012. attrType = mContext->mUnreifiedModule->ResolveTypeDef(attrTypeDef, BfPopulateType_Identity);
  8013. // 'Object' has some dependencies on some attributes, but those attributes are classes so we have a circular dependency issue
  8014. // We solve it by having a 'bypass' for known attributes that Object depends on
  8015. if ((attributesDirective->mArguments.empty()) && (autoComplete == NULL) && (attrType != NULL) && (attrType->IsTypeInstance()))
  8016. {
  8017. if (attrTypeDef == mCompiler->mCReprAttributeTypeDef)
  8018. {
  8019. BfTypeInstance* attrTypeInst = attrType->ToTypeInstance();
  8020. for (auto methodDef : attrTypeDef->mMethods)
  8021. {
  8022. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mProtection == BfProtection_Public))
  8023. {
  8024. customAttribute.mType = attrType->ToTypeInstance();
  8025. customAttribute.mCtor = methodDef;
  8026. isBypassedAttr = true;
  8027. break;
  8028. }
  8029. }
  8030. }
  8031. }
  8032. if (isBypassedAttr)
  8033. {
  8034. customAttribute.mAwaitingValidation = false;
  8035. customAttributes->mAttributes.push_back(customAttribute);
  8036. continue;
  8037. }
  8038. if (mContext->mCurTypeState != NULL)
  8039. {
  8040. SetAndRestoreValue<BfTypeReference*> prevTypeRef(mContext->mCurTypeState->mCurAttributeTypeRef, attributesDirective->mAttributeTypeRef);
  8041. mContext->mUnreifiedModule->ResolveTypeResult(attributesDirective->mAttributeTypeRef, attrType, BfPopulateType_BaseType, (BfResolveTypeRefFlags)0);
  8042. }
  8043. else
  8044. {
  8045. mContext->mUnreifiedModule->ResolveTypeResult(attributesDirective->mAttributeTypeRef, attrType, BfPopulateType_BaseType, (BfResolveTypeRefFlags)0);
  8046. }
  8047. }
  8048. // Don't allow this
  8049. /*else if (mContext->mCurTypeState != NULL)
  8050. {
  8051. SetAndRestoreValue<BfTypeReference*> prevTypeRef(mContext->mCurTypeState->mCurAttributeTypeRef, attributesDirective->mAttributeTypeRef);
  8052. attrType = mContext->mUnreifiedModule->ResolveTypeRef(attributesDirective->mAttributeTypeRef, BfPopulateType_DataAndMethods);
  8053. }
  8054. else
  8055. {
  8056. attrType = mContext->mUnreifiedModule->ResolveTypeRef(attributesDirective->mAttributeTypeRef);
  8057. }*/
  8058. BfTypeInstance* attrTypeInst = NULL;
  8059. if (attrType == NULL)
  8060. continue;
  8061. mContext->mUnreifiedModule->PopulateType(attrType, BfPopulateType_DataAndMethods);
  8062. attrTypeInst = attrType->ToTypeInstance();
  8063. if ((attrTypeInst == NULL) || (!TypeIsSubTypeOf(attrTypeInst, baseAttrTypeInst)) || (attrTypeInst->mAttributeData == NULL))
  8064. {
  8065. Fail(StrFormat("'%s' is not an attribute class", TypeToString(attrType).c_str()), attributesDirective->mAttributeTypeRef); //CS0616
  8066. continue;
  8067. }
  8068. if (mCurTypeInstance != NULL)
  8069. AddDependency(attrTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  8070. customAttribute.mType = attrTypeInst;
  8071. BfConstResolver constResolver(this);
  8072. bool inPropSet = false;
  8073. SizedArray<BfResolvedArg, 2> argValues;
  8074. for (BfExpression* arg : attributesDirective->mArguments)
  8075. {
  8076. if (arg == NULL)
  8077. {
  8078. continue;
  8079. }
  8080. if (autoComplete != NULL)
  8081. autoComplete->mShowAttributeProperties = attrTypeInst;
  8082. if (auto assignExpr = BfNodeDynCast<BfAssignmentExpression>(arg))
  8083. {
  8084. inPropSet = true;
  8085. if (autoComplete != NULL)
  8086. autoComplete->CheckNode(assignExpr->mLeft);
  8087. String findName = assignExpr->mLeft->ToString();
  8088. BfPropertyDef* bestProp = NULL;
  8089. BfTypeInstance* bestPropTypeInst = NULL;
  8090. BfFieldDef* bestField = NULL;
  8091. BfTypeInstance* bestFieldTypeInst = NULL;
  8092. auto checkTypeInst = attrTypeInst;
  8093. while (checkTypeInst != NULL)
  8094. {
  8095. mContext->mUnreifiedModule->PopulateType(checkTypeInst, BfPopulateType_Data);
  8096. for (auto prop : checkTypeInst->mTypeDef->mProperties)
  8097. {
  8098. if (prop->mName == findName)
  8099. {
  8100. if ((bestProp == NULL) || (bestProp->mProtection != BfProtection_Public))
  8101. {
  8102. bestProp = prop;
  8103. bestPropTypeInst = checkTypeInst;
  8104. }
  8105. }
  8106. }
  8107. for (auto field : checkTypeInst->mTypeDef->mFields)
  8108. {
  8109. if (field->mName == findName)
  8110. {
  8111. if ((bestField == NULL) || (bestField->mProtection != BfProtection_Public))
  8112. {
  8113. bestField = field;
  8114. bestFieldTypeInst = checkTypeInst;
  8115. }
  8116. }
  8117. }
  8118. if ((bestProp != NULL) || (bestField != NULL))
  8119. break;
  8120. checkTypeInst = checkTypeInst->mBaseType;
  8121. }
  8122. bool handledExpr = false;
  8123. if (bestField != NULL)
  8124. {
  8125. handledExpr = true;
  8126. if (mCompiler->mResolvePassData != NULL)
  8127. {
  8128. mCompiler->mResolvePassData->HandleFieldReference(assignExpr->mLeft, attrTypeDef, bestField);
  8129. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(assignExpr->mLeft)))
  8130. {
  8131. autoComplete->mDefField = bestField;
  8132. autoComplete->mDefType = attrTypeDef;
  8133. }
  8134. }
  8135. if (bestField->mProtection != BfProtection_Public)
  8136. Fail(StrFormat("'%s.%s' is inaccessible due to its protection level", TypeToString(bestFieldTypeInst).c_str(), findName.c_str()), assignExpr->mLeft); // CS0122
  8137. AddDependency(bestFieldTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  8138. BfCustomAttributeSetField setField;
  8139. setField.mFieldRef = BfFieldRef(bestFieldTypeInst, bestField);
  8140. auto& fieldTypeInst = checkTypeInst->mFieldInstances[bestField->mIdx];
  8141. if (assignExpr->mRight != NULL)
  8142. {
  8143. BfTypedValue result = constResolver.Resolve(assignExpr->mRight, fieldTypeInst.mResolvedType);
  8144. if (result)
  8145. {
  8146. CurrentAddToConstHolder(result.mValue);
  8147. setField.mParam = result;
  8148. customAttribute.mSetField.push_back(setField);
  8149. }
  8150. }
  8151. }
  8152. else if (bestProp == NULL)
  8153. {
  8154. Fail(StrFormat("'%s' does not contain a field or property named '%s'", TypeToString(attrTypeInst).c_str(), findName.c_str()), assignExpr->mLeft);
  8155. }
  8156. else
  8157. {
  8158. BfMethodDef* setMethod = NULL;
  8159. for (auto methodDef : bestProp->mMethods)
  8160. {
  8161. if (methodDef->mMethodType == BfMethodType_PropertySetter)
  8162. {
  8163. setMethod = methodDef;
  8164. break;
  8165. }
  8166. }
  8167. if (setMethod == NULL)
  8168. {
  8169. Fail("Property has no setter", assignExpr->mLeft);
  8170. }
  8171. else
  8172. {
  8173. if (mCompiler->mResolvePassData != NULL)
  8174. {
  8175. mCompiler->mResolvePassData->HandlePropertyReference(assignExpr->mLeft, attrTypeDef, bestProp);
  8176. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(assignExpr->mLeft)))
  8177. {
  8178. autoComplete->mDefProp = bestProp;
  8179. autoComplete->mDefType = attrTypeDef;
  8180. }
  8181. }
  8182. handledExpr = true;
  8183. if (bestProp->mProtection != BfProtection_Public)
  8184. Fail(StrFormat("'%s.%s' is inaccessible due to its protection level", TypeToString(bestPropTypeInst).c_str(), findName.c_str()), assignExpr->mLeft); // CS0122
  8185. BfResolvedArg resolvedArg;
  8186. AddDependency(bestPropTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  8187. BfCustomAttributeSetProperty setProperty;
  8188. setProperty.mPropertyRef = BfPropertyRef(bestPropTypeInst, bestProp);
  8189. // We don't actually need the mFunc, so get the ModuleMethodInstance from the native module
  8190. auto methodInstance = bestPropTypeInst->mModule->GetMethodInstance(bestPropTypeInst, setMethod, BfTypeVector());
  8191. if (methodInstance.mMethodInstance != NULL)
  8192. {
  8193. auto propType = methodInstance.mMethodInstance->GetParamType(0);
  8194. if (assignExpr->mRight != NULL)
  8195. {
  8196. BfTypedValue result = constResolver.Resolve(assignExpr->mRight, propType);
  8197. if (result)
  8198. {
  8199. BF_ASSERT(result.mType == propType);
  8200. CurrentAddToConstHolder(result.mValue);
  8201. setProperty.mParam = result;
  8202. customAttribute.mSetProperties.push_back(setProperty);
  8203. }
  8204. }
  8205. }
  8206. }
  8207. }
  8208. if ((!handledExpr) && (assignExpr->mRight != NULL))
  8209. constResolver.Resolve(assignExpr->mRight);
  8210. }
  8211. else
  8212. {
  8213. if (inPropSet)
  8214. {
  8215. Fail("Named attribute argument expected", arg); // CS1016
  8216. }
  8217. BfDeferEvalChecker deferEvalChecker;
  8218. arg->Accept(&deferEvalChecker);
  8219. bool deferParamEval = deferEvalChecker.mNeedsDeferEval;
  8220. BfResolvedArg resolvedArg;
  8221. resolvedArg.mExpression = arg;
  8222. if (deferParamEval)
  8223. {
  8224. resolvedArg.mArgFlags = BfArgFlag_DeferredEval;
  8225. }
  8226. else
  8227. resolvedArg.mTypedValue = constResolver.Resolve(arg);
  8228. if (!inPropSet)
  8229. argValues.push_back(resolvedArg);
  8230. }
  8231. if (autoComplete != NULL)
  8232. autoComplete->mShowAttributeProperties = NULL;
  8233. }
  8234. auto wasCapturingMethodInfo = false;
  8235. if (autoComplete != NULL)
  8236. {
  8237. wasCapturingMethodInfo = autoComplete->mIsCapturingMethodMatchInfo;
  8238. if (attributesDirective->mCtorOpenParen != NULL)
  8239. autoComplete->CheckInvocation(attributesDirective, attributesDirective->mCtorOpenParen, attributesDirective->mCtorCloseParen, attributesDirective->mCommas);
  8240. }
  8241. BfMethodMatcher methodMatcher(attributesDirective, this, "", argValues, NULL);
  8242. attrTypeDef = attrTypeInst->mTypeDef;
  8243. bool success = true;
  8244. bool isFailurePass = false;
  8245. for (int pass = 0; pass < 2; pass++)
  8246. {
  8247. bool isFailurePass = pass == 1;
  8248. for (auto checkMethod : attrTypeDef->mMethods)
  8249. {
  8250. if ((isFailurePass) && (checkMethod->mMethodDeclaration == NULL))
  8251. continue; // Don't match private default ctor if there's a user-defined one
  8252. if ((checkMethod->mIsStatic) || (checkMethod->mMethodType != BfMethodType_Ctor))
  8253. continue;
  8254. if ((!isFailurePass) && (!CheckProtection(checkMethod->mProtection, false, false)))
  8255. continue;
  8256. methodMatcher.CheckMethod(attrTypeInst, checkMethod, isFailurePass);
  8257. }
  8258. if ((methodMatcher.mBestMethodDef != NULL) || (methodMatcher.mBackupMethodDef != NULL))
  8259. break;
  8260. }
  8261. if (autoComplete != NULL)
  8262. {
  8263. if ((wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo))
  8264. {
  8265. autoComplete->mIsCapturingMethodMatchInfo = true;
  8266. BF_ASSERT(autoComplete->mMethodMatchInfo != NULL);
  8267. }
  8268. else
  8269. autoComplete->mIsCapturingMethodMatchInfo = false;
  8270. }
  8271. if (methodMatcher.mBestMethodDef == NULL)
  8272. methodMatcher.mBestMethodDef = methodMatcher.mBackupMethodDef;
  8273. BF_ASSERT(methodMatcher.mBestMethodDef != NULL);
  8274. customAttribute.mCtor = methodMatcher.mBestMethodDef;
  8275. if (methodMatcher.mBestMethodTypeInstance == mCurTypeInstance)
  8276. {
  8277. Fail("Custom attribute circular reference", attributesDirective);
  8278. }
  8279. if (mCurTypeInstance != NULL)
  8280. AddDependency(methodMatcher.mBestMethodTypeInstance, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  8281. if (!constResolver.PrepareMethodArguments(attributesDirective->mAttributeTypeRef, &methodMatcher, customAttribute.mCtorArgs))
  8282. success = false;
  8283. for (auto& arg : argValues)
  8284. {
  8285. if ((arg.mArgFlags & BfArgFlag_DeferredEval) != 0)
  8286. {
  8287. if (auto expr = BfNodeDynCast<BfExpression>(arg.mExpression))
  8288. constResolver.Resolve(expr);
  8289. }
  8290. }
  8291. // Move all those to the constHolder
  8292. for (auto& ctorArg : customAttribute.mCtorArgs)
  8293. {
  8294. CurrentAddToConstHolder(ctorArg);
  8295. }
  8296. if (attributesDirective->mAttributeTargetSpecifier != NULL)
  8297. {
  8298. targetOverride = BfAttributeTargets_ReturnValue;
  8299. if (attrTarget != BfAttributeTargets_Method)
  8300. {
  8301. 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.",
  8302. GetAttributesTargetListString(targetOverride).c_str(), GetAttributesTargetListString(attrTarget).c_str()), attributesDirective->mAttributeTargetSpecifier); // CS0657
  8303. }
  8304. success = false;
  8305. }
  8306. if ((success) && (targetOverride != (BfAttributeTargets)0))
  8307. {
  8308. if ((targetOverride == BfAttributeTargets_ReturnValue) && (attrTarget == BfAttributeTargets_Method))
  8309. {
  8310. auto methodInfoEx = mCurMethodInstance->GetMethodInfoEx();
  8311. if (methodInfoEx->mMethodCustomAttributes == NULL)
  8312. methodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  8313. if (success)
  8314. {
  8315. if (methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes == NULL)
  8316. methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes = new BfCustomAttributes();
  8317. methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes->mAttributes.push_back(customAttribute);
  8318. }
  8319. }
  8320. else
  8321. {
  8322. // Failed - ignore
  8323. success = false;
  8324. }
  8325. }
  8326. if (success)
  8327. {
  8328. if (!attrTypeInst->mAttributeData->mAllowMultiple)
  8329. {
  8330. for (auto& prevCustomAttribute : customAttributes->mAttributes)
  8331. {
  8332. if (prevCustomAttribute.mType == attrTypeInst)
  8333. {
  8334. Fail(StrFormat("Duplicate '%s' attribute", attributesDirective->mAttributeTypeRef->ToString().c_str()), attributesDirective->mAttributeTypeRef); // CS0579
  8335. }
  8336. }
  8337. }
  8338. }
  8339. if (success)
  8340. {
  8341. customAttributes->mAttributes.push_back(customAttribute);
  8342. }
  8343. }
  8344. ValidateCustomAttributes(customAttributes, attrTarget);
  8345. }
  8346. BfCustomAttributes* BfModule::GetCustomAttributes(BfAttributeDirective* attributesDirective, BfAttributeTargets attrType)
  8347. {
  8348. BfCustomAttributes* customAttributes = new BfCustomAttributes();
  8349. GetCustomAttributes(customAttributes, attributesDirective, attrType);
  8350. return customAttributes;
  8351. }
  8352. void BfModule::ProcessTypeInstCustomAttributes(bool& isPacked, bool& isUnion, bool& isCRepr, bool& isOrdered)
  8353. {
  8354. if (mCurTypeInstance->mCustomAttributes != NULL)
  8355. {
  8356. for (auto& customAttribute : mCurTypeInstance->mCustomAttributes->mAttributes)
  8357. {
  8358. String typeName = TypeToString(customAttribute.mType);
  8359. if (typeName == "System.PackedAttribute")
  8360. {
  8361. isPacked = true;
  8362. }
  8363. else if (typeName == "System.UnionAttribute")
  8364. {
  8365. isUnion = true;
  8366. }
  8367. else if (typeName == "System.CReprAttribute")
  8368. {
  8369. isCRepr = true;
  8370. isOrdered = true;
  8371. }
  8372. else if (typeName == "System.OrderedAttribute")
  8373. {
  8374. isOrdered = true;
  8375. }
  8376. else if (typeName == "System.AlwaysIncludeAttribute")
  8377. {
  8378. for (auto setProp : customAttribute.mSetProperties)
  8379. {
  8380. BfPropertyDef* propertyDef = setProp.mPropertyRef;
  8381. if (propertyDef->mName == "AssumeInstantiated")
  8382. {
  8383. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  8384. if ((constant != NULL) && (constant->mBool))
  8385. mCurTypeInstance->mHasBeenInstantiated = true;
  8386. }
  8387. }
  8388. }
  8389. }
  8390. }
  8391. }
  8392. // Checking to see if we're an attribute or not
  8393. void BfModule::ProcessCustomAttributeData()
  8394. {
  8395. bool isAttribute = false;
  8396. auto checkTypeInst = mCurTypeInstance->mBaseType;
  8397. while (checkTypeInst != NULL)
  8398. {
  8399. if (checkTypeInst->mTypeDef == mCompiler->mAttributeTypeDef)
  8400. isAttribute = true;
  8401. checkTypeInst = checkTypeInst->mBaseType;
  8402. }
  8403. if (!isAttribute)
  8404. return;
  8405. auto attributeData = new BfAttributeData();
  8406. bool hasCustomAttribute = false;
  8407. if (mCurTypeInstance->mCustomAttributes != NULL)
  8408. {
  8409. for (auto& customAttribute : mCurTypeInstance->mCustomAttributes->mAttributes)
  8410. {
  8411. if (customAttribute.mType->mTypeDef == mCompiler->mAttributeUsageAttributeTypeDef)
  8412. {
  8413. if (customAttribute.mCtorArgs.size() > 0)
  8414. {
  8415. auto constant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  8416. if ((constant != NULL) && (mBfIRBuilder->IsInt(constant->mTypeCode)))
  8417. attributeData->mAttributeTargets = (BfAttributeTargets)constant->mInt32;
  8418. }
  8419. for (auto& setProp : customAttribute.mSetProperties)
  8420. {
  8421. BfPropertyDef* propDef = setProp.mPropertyRef;
  8422. if (propDef->mName == "AllowMultiple")
  8423. {
  8424. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  8425. if (constant != NULL)
  8426. attributeData->mAllowMultiple = constant->mBool;
  8427. }
  8428. else if (propDef->mName == "Inherited")
  8429. {
  8430. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  8431. if (constant != NULL)
  8432. attributeData->mInherited = constant->mBool;
  8433. }
  8434. else if (propDef->mName == "ValidOn")
  8435. {
  8436. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  8437. if (constant != NULL)
  8438. attributeData->mAttributeTargets = (BfAttributeTargets)constant->mInt32;
  8439. }
  8440. }
  8441. hasCustomAttribute = true;
  8442. }
  8443. }
  8444. }
  8445. if ((!hasCustomAttribute) && (mCurTypeInstance->mBaseType->mAttributeData != NULL))
  8446. {
  8447. attributeData->mAttributeTargets = mCurTypeInstance->mBaseType->mAttributeData->mAttributeTargets;
  8448. attributeData->mInherited = mCurTypeInstance->mBaseType->mAttributeData->mInherited;
  8449. attributeData->mAllowMultiple = mCurTypeInstance->mBaseType->mAttributeData->mAllowMultiple;
  8450. }
  8451. mCurTypeInstance->mAttributeData = attributeData;
  8452. }
  8453. bool BfModule::TryGetConstString(BfIRConstHolder* constHolder, BfIRValue irValue, StringImpl& str)
  8454. {
  8455. auto constant = constHolder->GetConstant(irValue);
  8456. if (constant == NULL)
  8457. return false;
  8458. if (!BfIRConstHolder::IsInt(constant->mTypeCode))
  8459. return false;
  8460. int stringId = constant->mInt32;
  8461. BfStringPoolEntry* entry = NULL;
  8462. if (mContext->mStringObjectIdMap.TryGetValue(stringId, &entry))
  8463. {
  8464. str = entry->mString;
  8465. }
  8466. else
  8467. {
  8468. BF_DBG_FATAL("Failed to find string by id");
  8469. }
  8470. return true;
  8471. }
  8472. BfVariant BfModule::TypedValueToVariant(BfAstNode* refNode, const BfTypedValue& value, bool allowUndef)
  8473. {
  8474. BfVariant variant;
  8475. variant.mTypeCode = BfTypeCode_None;
  8476. BfType* primType = NULL;
  8477. if (value.mType->IsPrimitiveType())
  8478. primType = (BfPrimitiveType*)value.mType;
  8479. else if (value.mType->IsTypedPrimitive())
  8480. primType = value.mType->GetUnderlyingType();
  8481. if (primType)
  8482. {
  8483. auto constant = mBfIRBuilder->GetConstant(value.mValue);
  8484. if (constant != NULL)
  8485. {
  8486. if ((allowUndef) && (constant->mConstType == BfConstType_Undef))
  8487. {
  8488. variant.mTypeCode = BfTypeCode_Let;
  8489. return variant;
  8490. }
  8491. switch (constant->mTypeCode)
  8492. {
  8493. case BfTypeCode_Int8:
  8494. case BfTypeCode_UInt8:
  8495. case BfTypeCode_Int16:
  8496. case BfTypeCode_UInt16:
  8497. case BfTypeCode_Int32:
  8498. case BfTypeCode_UInt32:
  8499. case BfTypeCode_Int64:
  8500. case BfTypeCode_UInt64:
  8501. case BfTypeCode_IntPtr:
  8502. case BfTypeCode_UIntPtr:
  8503. case BfTypeCode_IntUnknown:
  8504. case BfTypeCode_UIntUnknown:
  8505. case BfTypeCode_Single:
  8506. case BfTypeCode_Double:
  8507. case BfTypeCode_Char8:
  8508. case BfTypeCode_Char16:
  8509. case BfTypeCode_Char32:
  8510. variant.mTypeCode = constant->mTypeCode;
  8511. variant.mInt64 = constant->mInt64;
  8512. break;
  8513. default:
  8514. if (refNode != NULL)
  8515. Fail("Invalid const expression type", refNode);
  8516. break;
  8517. }
  8518. }
  8519. }
  8520. return variant;
  8521. }
  8522. BfTypedValue BfModule::RemoveRef(BfTypedValue typedValue)
  8523. {
  8524. if ((typedValue.mType != NULL) && (typedValue.mType->IsRef()))
  8525. {
  8526. auto elementType = typedValue.mType->GetUnderlyingType();
  8527. if (typedValue.IsAddr())
  8528. {
  8529. if (elementType->IsValuelessType())
  8530. {
  8531. BF_ASSERT(!typedValue.mValue);
  8532. typedValue = BfTypedValue(typedValue.mValue, elementType, true);
  8533. }
  8534. else
  8535. typedValue = BfTypedValue(mBfIRBuilder->CreateLoad(typedValue.mValue), elementType, true);
  8536. }
  8537. else
  8538. typedValue = BfTypedValue(typedValue.mValue, elementType, true);
  8539. if (typedValue.mType->IsValuelessType())
  8540. {
  8541. BF_ASSERT(typedValue.mValue.IsFake());
  8542. }
  8543. }
  8544. return typedValue;
  8545. }
  8546. BfTypedValue BfModule::LoadValue(BfTypedValue typedValue, BfAstNode* refNode, bool isVolatile)
  8547. {
  8548. if (!typedValue.IsAddr())
  8549. return typedValue;
  8550. if (typedValue.mType->IsValuelessType())
  8551. return BfTypedValue(mBfIRBuilder->GetFakeVal(), typedValue.mType, false);
  8552. BfIRValue loadedVal = typedValue.mValue;
  8553. if (loadedVal)
  8554. {
  8555. /*if (isVolatile)
  8556. mBfIRBuilder->CreateFence(BfIRFenceType_AcquireRelease);*/
  8557. PopulateType(typedValue.mType, BfPopulateType_Data);
  8558. loadedVal = mBfIRBuilder->CreateAlignedLoad(loadedVal, std::max(1, (int)typedValue.mType->mAlign), isVolatile);
  8559. }
  8560. return BfTypedValue(loadedVal, typedValue.mType, false);
  8561. }
  8562. BfTypedValue BfModule::LoadOrAggregateValue(BfTypedValue typedValue)
  8563. {
  8564. if (typedValue.IsSplat())
  8565. return AggregateSplat(typedValue);
  8566. if (typedValue.IsAddr())
  8567. return LoadValue(typedValue);
  8568. return typedValue;
  8569. }
  8570. BfTypedValue BfModule::AggregateSplat(BfTypedValue typedValue, BfIRValue* valueArrPtr)
  8571. {
  8572. if (!typedValue.IsSplat())
  8573. return typedValue;
  8574. if (typedValue.mType->IsValuelessType())
  8575. return typedValue;
  8576. int elementIdx = 0;
  8577. auto _ExtractValue = [&](BfType* checkType)
  8578. {
  8579. if (valueArrPtr != NULL)
  8580. return valueArrPtr[elementIdx++];
  8581. return ExtractSplatValue(typedValue, elementIdx++, checkType);
  8582. };
  8583. std::function<BfIRValue(BfType*)> checkTypeLambda = [&](BfType* checkType)
  8584. {
  8585. if (checkType->IsStruct())
  8586. {
  8587. BfIRValue curValue = mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(checkType, BfIRPopulateType_Full));
  8588. auto checkTypeInstance = checkType->ToTypeInstance();
  8589. if (checkTypeInstance->mBaseType != NULL)
  8590. {
  8591. mBfIRBuilder->PopulateType(checkTypeInstance->mBaseType, BfIRPopulateType_Full);
  8592. BfIRValue baseValue = checkTypeLambda(checkTypeInstance->mBaseType);
  8593. curValue = mBfIRBuilder->CreateInsertValue(curValue, baseValue, 0);
  8594. }
  8595. if (checkTypeInstance->mIsUnion)
  8596. {
  8597. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  8598. if (!unionInnerType->IsValuelessType())
  8599. {
  8600. BfIRValue fieldValue = checkTypeLambda(unionInnerType);
  8601. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, 1);
  8602. }
  8603. if (checkTypeInstance->IsEnum())
  8604. {
  8605. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  8606. BfIRValue fieldValue = checkTypeLambda(dscrType);
  8607. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, 2);
  8608. }
  8609. }
  8610. else
  8611. {
  8612. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  8613. {
  8614. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  8615. if (fieldInstance->mDataIdx >= 0)
  8616. {
  8617. BfIRValue fieldValue = checkTypeLambda(fieldInstance->GetResolvedType());
  8618. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, fieldInstance->mDataIdx);
  8619. }
  8620. }
  8621. }
  8622. return curValue;
  8623. }
  8624. else if (checkType->IsMethodRef())
  8625. {
  8626. BfMethodRefType* methodRefType = (BfMethodRefType*)checkType;
  8627. BfIRValue curValue = mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(checkType, BfIRPopulateType_Full));
  8628. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  8629. {
  8630. BfIRValue fieldValue;
  8631. auto checkType = methodRefType->GetCaptureType(dataIdx);
  8632. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  8633. {
  8634. fieldValue = checkTypeLambda(checkType);
  8635. }
  8636. else
  8637. {
  8638. fieldValue = _ExtractValue(checkType);
  8639. }
  8640. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, dataIdx);
  8641. }
  8642. return curValue;
  8643. }
  8644. else if (!checkType->IsValuelessType())
  8645. {
  8646. return _ExtractValue(checkType);
  8647. }
  8648. return BfIRValue();
  8649. };
  8650. BfIRValue value = checkTypeLambda(typedValue.mType);
  8651. return BfTypedValue(value, typedValue.mType, typedValue.IsThis() ? BfTypedValueKind_ThisValue : BfTypedValueKind_Value);
  8652. }
  8653. void BfModule::AggregateSplatIntoAddr(BfTypedValue typedValue, BfIRValue addrVal)
  8654. {
  8655. if (!typedValue.IsSplat())
  8656. return;
  8657. if (typedValue.mType->IsValuelessType())
  8658. return;
  8659. /*static int sCallIdx = 0;
  8660. if (!mCompiler->mIsResolveOnly)
  8661. sCallIdx++;
  8662. int callIdx = sCallIdx;*/
  8663. int elementIdx = 0;
  8664. std::function<void(BfType*, BfIRValue)> checkTypeLambda = [&](BfType* checkType, BfIRValue curAddrVal)
  8665. {
  8666. if (checkType->IsStruct())
  8667. {
  8668. auto checkTypeInstance = checkType->ToTypeInstance();
  8669. if (checkTypeInstance->mBaseType != NULL)
  8670. {
  8671. mBfIRBuilder->PopulateType(checkTypeInstance->mBaseType);
  8672. auto baseAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 0);
  8673. checkTypeLambda(checkTypeInstance->mBaseType, baseAddrVal);
  8674. }
  8675. if (checkTypeInstance->mIsUnion)
  8676. {
  8677. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  8678. if (!unionInnerType->IsValuelessType())
  8679. {
  8680. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 1);
  8681. checkTypeLambda(unionInnerType, fieldAddrVal);
  8682. }
  8683. if (checkTypeInstance->IsEnum())
  8684. {
  8685. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  8686. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 2);
  8687. checkTypeLambda(dscrType, fieldAddrVal);
  8688. }
  8689. }
  8690. else
  8691. {
  8692. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  8693. {
  8694. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  8695. if (fieldInstance->mDataIdx >= 0)
  8696. {
  8697. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, fieldInstance->mDataIdx);
  8698. checkTypeLambda(fieldInstance->mResolvedType, fieldAddrVal);
  8699. }
  8700. }
  8701. }
  8702. }
  8703. else if (checkType->IsMethodRef())
  8704. {
  8705. BfMethodRefType* methodRefType = (BfMethodRefType*)checkType;
  8706. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  8707. {
  8708. auto dataType = methodRefType->GetCaptureType(dataIdx);
  8709. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, dataIdx);
  8710. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  8711. {
  8712. checkTypeLambda(methodRefType->GetCaptureType(dataIdx), fieldAddrVal);
  8713. }
  8714. else
  8715. {
  8716. // static int sItrCount = 0;
  8717. // sItrCount++;
  8718. // int curItr = sItrCount;
  8719. // if (curItr == 1)
  8720. // {
  8721. // NOP;
  8722. // }
  8723. auto val = ExtractSplatValue(typedValue, elementIdx++, dataType);
  8724. mBfIRBuilder->CreateStore(val, fieldAddrVal);
  8725. }
  8726. }
  8727. }
  8728. else if (!checkType->IsValuelessType())
  8729. {
  8730. auto val = ExtractSplatValue(typedValue, elementIdx++, checkType);
  8731. mBfIRBuilder->CreateStore(val, curAddrVal);
  8732. }
  8733. };
  8734. checkTypeLambda(typedValue.mType, addrVal);
  8735. }
  8736. BfTypedValue BfModule::MakeAddressable(BfTypedValue typedVal)
  8737. {
  8738. bool wasReadOnly = typedVal.IsReadOnly();
  8739. if ((typedVal.mType->IsValueType()) &&
  8740. (!typedVal.mType->IsValuelessType()))
  8741. {
  8742. wasReadOnly = true; // Any non-addr is implicitly read-only
  8743. //static int gCallIdx = 0;
  8744. if (typedVal.IsAddr())
  8745. return typedVal;
  8746. BfType* type = typedVal.mType;
  8747. PopulateType(type);
  8748. auto tempVar = CreateAlloca(type);
  8749. if (typedVal.IsSplat())
  8750. AggregateSplatIntoAddr(typedVal, tempVar);
  8751. else
  8752. mBfIRBuilder->CreateAlignedStore(typedVal.mValue, tempVar, type->mAlign);
  8753. return BfTypedValue(tempVar, type,
  8754. typedVal.IsThis() ?
  8755. (wasReadOnly ? BfTypedValueKind_ReadOnlyThisAddr : BfTypedValueKind_ThisAddr) :
  8756. (wasReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr));
  8757. }
  8758. return LoadValue(typedVal);
  8759. }
  8760. BfTypedValue BfModule::RemoveReadOnly(BfTypedValue typedValue)
  8761. {
  8762. if (typedValue.mKind == BfTypedValueKind_ReadOnlyAddr)
  8763. typedValue.mKind = BfTypedValueKind_Addr;
  8764. return typedValue;
  8765. }
  8766. BfIRValue BfModule::ExtractSplatValue(BfTypedValue typedValue, int componentIdx, BfType* wantType, bool* isAddr)
  8767. {
  8768. BfIRValue val;
  8769. if (typedValue.mValue.IsArg())
  8770. {
  8771. val = mBfIRBuilder->GetArgument(typedValue.mValue.mId + componentIdx);
  8772. if (isAddr != NULL)
  8773. {
  8774. if (wantType != NULL)
  8775. *isAddr = wantType->IsComposite();
  8776. else
  8777. *isAddr = false;
  8778. }
  8779. else if (wantType->IsComposite())
  8780. val = mBfIRBuilder->CreateLoad(val);
  8781. }
  8782. if (!val)
  8783. {
  8784. auto checkMethodState = mCurMethodState;
  8785. while (checkMethodState != NULL)
  8786. {
  8787. for (int idx = 0; idx < (int)checkMethodState->mSplatDecompAddrs.size(); idx++)
  8788. {
  8789. auto decompAddr = checkMethodState->mSplatDecompAddrs[idx];
  8790. if (decompAddr == typedValue.mValue)
  8791. {
  8792. val = checkMethodState->mSplatDecompAddrs[idx + componentIdx];
  8793. if ((wantType->IsComposite()) && (typedValue.mType->IsMethodRef()))
  8794. {
  8795. // This is really backing for a POINTER to a composite inside a methodRef
  8796. val = mBfIRBuilder->CreateLoad(val);
  8797. }
  8798. if ((isAddr != NULL) && (typedValue.mKind != BfTypedValueKind_SplatHead_NeedsCasting))
  8799. {
  8800. *isAddr = true;
  8801. return val;
  8802. }
  8803. else
  8804. {
  8805. val = mBfIRBuilder->CreateLoad(val);
  8806. break;
  8807. }
  8808. }
  8809. }
  8810. if (val)
  8811. break;
  8812. checkMethodState = checkMethodState->mPrevMethodState;
  8813. }
  8814. }
  8815. if (val)
  8816. {
  8817. if (typedValue.mKind == BfTypedValueKind_SplatHead_NeedsCasting)
  8818. {
  8819. BF_ASSERT(wantType != NULL);
  8820. if (wantType != NULL)
  8821. return mBfIRBuilder->CreateBitCast(val, mBfIRBuilder->MapType(wantType));
  8822. }
  8823. return val;
  8824. }
  8825. BF_FATAL("Splat not found");
  8826. return BfIRValue();
  8827. }
  8828. BfTypedValue BfModule::ExtractValue(BfTypedValue typedValue, BfFieldInstance* fieldInstance, int fieldIdx)
  8829. {
  8830. int useFieldIdx = fieldIdx;
  8831. BfType* fieldType = NULL;
  8832. if (fieldInstance != NULL)
  8833. {
  8834. fieldType = fieldInstance->mResolvedType;
  8835. if (typedValue.mType->IsUnion())
  8836. {
  8837. if (fieldIdx == 1)
  8838. {
  8839. if (typedValue.IsSplat())
  8840. {
  8841. BfTypedValue innerVal = typedValue;
  8842. innerVal.mType = fieldType;
  8843. return innerVal;
  8844. }
  8845. }
  8846. }
  8847. }
  8848. else
  8849. {
  8850. if (typedValue.mType->IsPayloadEnum())
  8851. {
  8852. auto typeInst = typedValue.mType->ToTypeInstance();
  8853. if (fieldIdx == 1)
  8854. fieldType = typeInst->GetUnionInnerType();
  8855. else if (fieldIdx == 2)
  8856. {
  8857. fieldType = typeInst->GetDiscriminatorType(&useFieldIdx);
  8858. }
  8859. }
  8860. else if (typedValue.mType->IsUnion())
  8861. {
  8862. if (fieldIdx == 1)
  8863. {
  8864. fieldType = typedValue.mType->ToTypeInstance()->GetUnionInnerType();
  8865. if (typedValue.IsSplat())
  8866. {
  8867. BfTypedValue innerVal = typedValue;
  8868. innerVal.mType = fieldType;
  8869. return innerVal;
  8870. }
  8871. }
  8872. }
  8873. }
  8874. BF_ASSERT(typedValue.mType->IsStruct());
  8875. if (typedValue.IsSplat())
  8876. {
  8877. if (typedValue.mType->IsPayloadEnum())
  8878. {
  8879. if (fieldIdx == 1)
  8880. {
  8881. // Payload
  8882. auto typeInst = typedValue.mType->ToTypeInstance();
  8883. auto unionInnerType = typeInst->GetUnionInnerType();
  8884. bool isAddr = false;
  8885. BfIRValue irVal = ExtractSplatValue(typedValue, 0, unionInnerType, &isAddr);
  8886. return BfTypedValue(irVal, unionInnerType, BfTypedValueKind_SplatHead);
  8887. }
  8888. if (fieldIdx == 2)
  8889. {
  8890. // Discriminator
  8891. auto typeInst = typedValue.mType->ToTypeInstance();
  8892. auto unionInnerType = typeInst->GetUnionInnerType();
  8893. auto dscrType = typeInst->GetDiscriminatorType();
  8894. int argIdx = typedValue.mValue.mId;
  8895. int componentIdx = 0;
  8896. BfTypeUtils::SplatIterate([&](BfType* checkType) { componentIdx++; }, unionInnerType);
  8897. bool isAddr;
  8898. BfIRValue irVal = ExtractSplatValue(typedValue, componentIdx, dscrType, &isAddr);
  8899. return BfTypedValue(irVal, dscrType, isAddr);
  8900. }
  8901. }
  8902. int componentIdx = 0;
  8903. BfTypedValue retVal;
  8904. BfFieldInstance* wantFieldInstance = fieldInstance;
  8905. std::function<void(BfType*)> checkTypeLambda = [&](BfType* checkType)
  8906. {
  8907. if (checkType->IsStruct())
  8908. {
  8909. auto checkTypeInstance = checkType->ToTypeInstance();
  8910. if ((checkType->IsUnion()) || (checkType->IsEnum()))
  8911. {
  8912. //TODO: Why did we have this removed? It messed up an extraction from a nullable splattable
  8913. fieldType = checkTypeInstance->GetUnionInnerType();
  8914. checkTypeLambda(fieldType);
  8915. if (checkType->IsEnum())
  8916. {
  8917. // Past discriminator...
  8918. componentIdx++;
  8919. }
  8920. return;
  8921. }
  8922. if (checkTypeInstance->mBaseType != NULL)
  8923. checkTypeLambda(checkTypeInstance->mBaseType);
  8924. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  8925. {
  8926. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  8927. if (fieldInstance == wantFieldInstance)
  8928. {
  8929. bool isAddr = false;
  8930. BfIRValue val = ExtractSplatValue(typedValue, componentIdx, fieldInstance->mResolvedType, &isAddr);
  8931. retVal = BfTypedValue(val, fieldInstance->mResolvedType,
  8932. fieldInstance->mResolvedType->IsComposite() ? BfTypedValueKind_SplatHead :
  8933. isAddr ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Value);
  8934. if ((retVal.IsAddr()) && (!fieldInstance->mResolvedType->IsValueType()))
  8935. {
  8936. retVal = LoadValue(retVal);
  8937. }
  8938. break;
  8939. }
  8940. if (fieldInstance->mDataIdx >= 0)
  8941. checkTypeLambda(fieldInstance->GetResolvedType());
  8942. }
  8943. }
  8944. else if (!checkType->IsValuelessType())
  8945. {
  8946. componentIdx++;
  8947. //argIdx++;
  8948. }
  8949. };
  8950. checkTypeLambda(typedValue.mType);
  8951. BF_ASSERT(retVal);
  8952. return retVal;
  8953. }
  8954. if (typedValue.IsAddr())
  8955. {
  8956. BF_ASSERT(fieldType != NULL);
  8957. auto valRef = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, useFieldIdx);
  8958. return BfTypedValue(valRef, fieldType, BfTypedValueKind_ReadOnlyAddr);
  8959. }
  8960. else
  8961. {
  8962. BF_ASSERT(fieldType != NULL);
  8963. return BfTypedValue(mBfIRBuilder->CreateExtractValue(typedValue.mValue, useFieldIdx), fieldType, BfTypedValueKind_Value);
  8964. }
  8965. }
  8966. BfIRValue BfModule::ExtractValue(BfTypedValue typedValue, int dataIdx)
  8967. {
  8968. if (typedValue.IsAddr())
  8969. {
  8970. auto addrVal = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, dataIdx);
  8971. return mBfIRBuilder->CreateLoad(addrVal);
  8972. }
  8973. return mBfIRBuilder->CreateExtractValue(typedValue.mValue, dataIdx);
  8974. }
  8975. BfIRValue BfModule::CreateIndexedValue(BfType* elementType, BfIRValue value, BfIRValue indexValue, bool isElementIndex)
  8976. {
  8977. if (elementType->IsSizeAligned())
  8978. {
  8979. if (isElementIndex)
  8980. return mBfIRBuilder->CreateInBoundsGEP(value, GetConstValue(0), indexValue);
  8981. else
  8982. return mBfIRBuilder->CreateInBoundsGEP(value, indexValue);
  8983. }
  8984. auto ptrType = CreatePointerType(elementType);
  8985. auto ofsVal = mBfIRBuilder->CreateNumericCast(indexValue, true, BfTypeCode_IntPtr);
  8986. auto ofsScaledVal = mBfIRBuilder->CreateMul(ofsVal, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, elementType->GetStride()));
  8987. auto intVal = mBfIRBuilder->CreatePtrToInt(value, BfTypeCode_IntPtr);
  8988. auto newIntVal = mBfIRBuilder->CreateAdd(intVal, ofsScaledVal);
  8989. return mBfIRBuilder->CreateIntToPtr(newIntVal, mBfIRBuilder->MapType(ptrType));
  8990. }
  8991. BfIRValue BfModule::CreateIndexedValue(BfType* elementType, BfIRValue value, int indexValue, bool isElementIndex)
  8992. {
  8993. if (elementType->IsSizeAligned())
  8994. {
  8995. if (isElementIndex)
  8996. return mBfIRBuilder->CreateInBoundsGEP(value, 0, indexValue);
  8997. else
  8998. return mBfIRBuilder->CreateInBoundsGEP(value, indexValue);
  8999. }
  9000. return CreateIndexedValue(elementType, value, GetConstValue(indexValue), isElementIndex);
  9001. }
  9002. bool BfModule::CheckModifyValue(BfTypedValue& typedValue, BfAstNode* refNode, const char* modifyType)
  9003. {
  9004. if (modifyType == NULL)
  9005. modifyType = "modify";
  9006. if (typedValue.mType->IsVar())
  9007. return true;
  9008. if (typedValue.IsReadOnly())
  9009. {
  9010. Fail(StrFormat("Cannot %s read-only variable", modifyType), refNode);
  9011. return false;
  9012. }
  9013. if ((!typedValue.IsAddr()) && (!typedValue.mType->IsValuelessType()))
  9014. {
  9015. Fail(StrFormat("Cannot %s value", modifyType), refNode);
  9016. return false;
  9017. }
  9018. if (typedValue.mKind == BfTypedValueKind_TempAddr)
  9019. {
  9020. Fail(StrFormat("Cannot %s value", modifyType), refNode);
  9021. return false;
  9022. }
  9023. return true;
  9024. }
  9025. bool BfModule::CompareMethodSignatures(BfMethodInstance* methodA, BfMethodInstance* methodB)
  9026. {
  9027. if (methodA->mMethodDef->mIsLocalMethod)
  9028. {
  9029. int sepPosA = (int)BF_MIN(methodA->mMethodDef->mName.IndexOf('@'), methodA->mMethodDef->mName.length());
  9030. int sepPosB = (int)BF_MIN(methodB->mMethodDef->mName.IndexOf('@'), methodB->mMethodDef->mName.length());
  9031. if (sepPosA != sepPosB)
  9032. return false;
  9033. if (strncmp(methodA->mMethodDef->mName.c_str(), methodB->mMethodDef->mName.c_str(), sepPosA) != 0)
  9034. return false;
  9035. }
  9036. else if (methodA->mMethodDef->mName != methodB->mMethodDef->mName)
  9037. return false;
  9038. if (methodA->mMethodDef->mCheckedKind != methodB->mMethodDef->mCheckedKind)
  9039. return false;
  9040. if (methodA->mMethodDef->mMethodType == BfMethodType_Ctor)
  9041. {
  9042. if (methodA->mMethodDef->mIsStatic != methodB->mMethodDef->mIsStatic)
  9043. return false;
  9044. }
  9045. if (methodA->mMethodDef->mMethodType == BfMethodType_Operator)
  9046. {
  9047. if (methodB->mMethodDef->mMethodType != BfMethodType_Operator)
  9048. return false;
  9049. auto operatorA = (BfOperatorDef*)methodA->mMethodDef;
  9050. auto operatorB = (BfOperatorDef*)methodB->mMethodDef;
  9051. if (operatorA->mOperatorDeclaration->mBinOp != operatorB->mOperatorDeclaration->mBinOp)
  9052. return false;
  9053. if (operatorA->mOperatorDeclaration->mUnaryOp != operatorB->mOperatorDeclaration->mUnaryOp)
  9054. return false;
  9055. if (operatorA->mOperatorDeclaration->mIsConvOperator)
  9056. {
  9057. if (methodA->mReturnType != methodB->mReturnType)
  9058. return false;
  9059. }
  9060. }
  9061. int implicitParamCountA = methodA->GetImplicitParamCount();
  9062. int implicitParamCountB = methodB->GetImplicitParamCount();
  9063. if (methodA->GetParamCount() - implicitParamCountA != methodB->GetParamCount() - implicitParamCountB)
  9064. return false;
  9065. if (methodA->mHadGenericDelegateParams != methodB->mHadGenericDelegateParams)
  9066. return false;
  9067. for (int paramIdx = 0; paramIdx < (int)methodA->GetParamCount() - implicitParamCountA; paramIdx++)
  9068. {
  9069. if ((methodA->GetParamType(paramIdx + implicitParamCountA) != methodB->GetParamType(paramIdx + implicitParamCountB)) ||
  9070. (methodA->GetParamKind(paramIdx + implicitParamCountA) != methodB->GetParamKind(paramIdx + implicitParamCountB)))
  9071. return false;
  9072. }
  9073. // Compare generic params. Generic params are part of the method signature here
  9074. if (methodA->GetNumGenericParams() != methodB->GetNumGenericParams())
  9075. return false;
  9076. for (int genericParamIdx = 0; genericParamIdx < (int)methodA->GetNumGenericParams(); genericParamIdx++)
  9077. {
  9078. auto genericParamA = methodA->mMethodInfoEx->mGenericParams[genericParamIdx];
  9079. auto genericParamB = methodB->mMethodInfoEx->mGenericParams[genericParamIdx];
  9080. if (genericParamA->mGenericParamFlags != genericParamB->mGenericParamFlags)
  9081. return false;
  9082. if (genericParamA->mTypeConstraint != genericParamB->mTypeConstraint)
  9083. return false;
  9084. if (genericParamA->mInterfaceConstraints.size() != genericParamB->mInterfaceConstraints.size())
  9085. return false;
  9086. for (int interfaceIdx = 0; interfaceIdx < (int)genericParamA->mInterfaceConstraints.size(); interfaceIdx++)
  9087. if (genericParamA->mInterfaceConstraints[interfaceIdx] != genericParamB->mInterfaceConstraints[interfaceIdx])
  9088. return false;
  9089. }
  9090. return true;
  9091. }
  9092. bool BfModule::IsCompatibleInterfaceMethod(BfMethodInstance* iMethodInst, BfMethodInstance* methodInstance)
  9093. {
  9094. if (iMethodInst->mMethodDef->mName != methodInstance->mMethodDef->mName)
  9095. return false;
  9096. if (iMethodInst->mMethodDef->mIsOperator != methodInstance->mMethodDef->mIsOperator)
  9097. return false;
  9098. if (iMethodInst->mMethodDef->mIsOperator)
  9099. {
  9100. auto iOperatorDef = (BfOperatorDef*)iMethodInst->mMethodDef;
  9101. auto operatorDef = (BfOperatorDef*)methodInstance->mMethodDef;
  9102. if (iOperatorDef->mOperatorDeclaration->mUnaryOp != operatorDef->mOperatorDeclaration->mUnaryOp)
  9103. return false;
  9104. if (iOperatorDef->mOperatorDeclaration->mBinOp != operatorDef->mOperatorDeclaration->mBinOp)
  9105. return false;
  9106. }
  9107. if (iMethodInst->GetParamCount() != methodInstance->GetParamCount())
  9108. return false;
  9109. for (int paramIdx = 0; paramIdx < (int)iMethodInst->GetParamCount(); paramIdx++)
  9110. {
  9111. if (iMethodInst->GetParamKind(paramIdx) != methodInstance->GetParamKind(paramIdx))
  9112. return false;
  9113. BfType* iParamType = iMethodInst->GetParamType(paramIdx);
  9114. BfType* methodParamType = methodInstance->GetParamType(paramIdx);
  9115. if (iParamType->IsSelf())
  9116. {
  9117. if (methodParamType != methodInstance->GetOwner())
  9118. return false;
  9119. }
  9120. else if (!iParamType->IsGenericParam())
  9121. {
  9122. if (methodParamType != iParamType)
  9123. return false;
  9124. }
  9125. else
  9126. {
  9127. if (!methodParamType->IsGenericParam())
  9128. return false;
  9129. auto genericParamType = (BfGenericParamType*)methodParamType;
  9130. if (genericParamType->mGenericParamKind == BfGenericParamKind_Type)
  9131. return false;
  9132. auto genericParam = methodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  9133. bool hadInterface = false;
  9134. for (auto interfaceConstraint : genericParam->mInterfaceConstraints)
  9135. if (interfaceConstraint == iParamType)
  9136. hadInterface = true;
  9137. if (!hadInterface)
  9138. return false;
  9139. }
  9140. }
  9141. return true;
  9142. }
  9143. void BfModule::AddMethodReference(const BfMethodRef& methodRef, BfGetMethodInstanceFlags flags)
  9144. {
  9145. BfMethodInstance* methodInstance = methodRef;
  9146. if ((mCurTypeInstance != NULL) && (!mCompiler->IsAutocomplete()))
  9147. {
  9148. auto methodInstanceGroup = methodInstance->mMethodInstanceGroup;
  9149. if ((methodInstance->IsSpecializedGenericMethod()) || (methodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_AlwaysInclude))
  9150. {
  9151. BF_ASSERT(!methodRef.mTypeInstance->IsFunction());
  9152. BfMethodRef methodRef = methodInstance;
  9153. BfSpecializedMethodRefInfo* specializedMethodRefInfo = NULL;
  9154. bool isNew = mCurTypeInstance->mSpecializedMethodReferences.TryAdd(methodRef, NULL, &specializedMethodRefInfo);
  9155. if (((flags & BfGetMethodInstanceFlag_Unreified) == 0) &&
  9156. ((flags & BfGetMethodInstanceFlag_NoForceReification) == 0) &&
  9157. (mIsReified))
  9158. {
  9159. specializedMethodRefInfo->mHasReifiedRef = true;
  9160. }
  9161. }
  9162. }
  9163. }
  9164. BfModuleMethodInstance BfModule::ReferenceExternalMethodInstance(BfMethodInstance* methodInstance, BfGetMethodInstanceFlags flags)
  9165. {
  9166. if ((flags & BfGetMethodInstanceFlag_ResultNotUsed) != 0)
  9167. return BfModuleMethodInstance(methodInstance, BfIRValue());
  9168. if (mBfIRBuilder == NULL)
  9169. return BfModuleMethodInstance(methodInstance, BfIRValue());
  9170. if (methodInstance->GetOwner()->IsFunction())
  9171. {
  9172. // No actual ref needed- not an actual generated function
  9173. return BfModuleMethodInstance(methodInstance, BfIRValue());
  9174. }
  9175. bool isGenFunction = methodInstance->mMethodInstanceGroup->mMethodIdx < 0;
  9176. if (!isGenFunction)
  9177. AddMethodReference(methodInstance, flags);
  9178. if (mBfIRBuilder->mIgnoreWrites)
  9179. return BfModuleMethodInstance(methodInstance, mBfIRBuilder->GetFakeVal());
  9180. if (mCompiler->IsSkippingExtraResolveChecks())
  9181. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  9182. if (methodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)
  9183. {
  9184. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  9185. }
  9186. bool isInlined = (methodInstance->mAlwaysInline) || ((flags & BfGetMethodInstanceFlag_ForceInline) != 0);
  9187. BfMethodRef methodRef = methodInstance;
  9188. if (isInlined)
  9189. methodRef.mMethodRefFlags = (BfMethodRefFlags)(methodRef.mMethodRefFlags | BfMethodRefFlag_AlwaysInclude);
  9190. else
  9191. methodRef.mMethodRefFlags = BfMethodRefFlag_None;
  9192. if (!isGenFunction)
  9193. {
  9194. BfIRValue* irFuncPtr = NULL;
  9195. if (mFuncReferences.TryGetValue(methodRef, &irFuncPtr))
  9196. return BfModuleMethodInstance(methodInstance, *irFuncPtr);
  9197. }
  9198. if (mAwaitingInitFinish)
  9199. FinishInit();
  9200. BfIRValue func = CreateFunctionFrom(methodInstance, isGenFunction, isInlined);
  9201. if (!isGenFunction)
  9202. mFuncReferences[methodRef] = func;
  9203. BfLogSysM("Adding func reference. Module:%p MethodInst:%p NewLLVMFunc:%d OldLLVMFunc:%d\n", this, methodInstance, func.mId, methodInstance->mIRFunction.mId);
  9204. if ((isInlined) && (!mIsScratchModule))
  9205. {
  9206. // We can't just add a dependency to mCurTypeInstance because we may have nested inlined functions, and
  9207. // mCurTypeInstance will just reflect the owner of the method currently being inlined, not the top-level
  9208. // type instance
  9209. // Be smarter about this if we ever insert a lot of type instances into a single module - track in a field
  9210. BF_ASSERT(mOwnedTypeInstances.size() <= 1);
  9211. for (auto ownedTypeInst : mOwnedTypeInstances)
  9212. AddDependency(methodInstance->GetOwner(), ownedTypeInst, BfDependencyMap::DependencyFlag_InlinedCall);
  9213. if ((!mCompiler->mIsResolveOnly) && (mIsReified) && (!methodInstance->mIsUnspecialized))
  9214. {
  9215. mIncompleteMethodCount++;
  9216. BfInlineMethodRequest* inlineMethodRequest = mContext->mInlineMethodWorkList.Alloc();
  9217. inlineMethodRequest->mType = methodInstance->GetOwner();
  9218. inlineMethodRequest->mFromModule = this;
  9219. inlineMethodRequest->mFunc = func;
  9220. inlineMethodRequest->mFromModuleRevision = mRevision;
  9221. inlineMethodRequest->mMethodInstance = methodInstance;
  9222. BF_ASSERT(mIsModuleMutable);
  9223. BfLogSysM("mInlineMethodWorkList %p for method %p in module %p in ReferenceExternalMethodInstance\n", inlineMethodRequest, methodInstance, this);
  9224. }
  9225. }
  9226. return BfModuleMethodInstance(methodInstance, func);
  9227. }
  9228. BfModule* BfModule::GetOrCreateMethodModule(BfMethodInstance* methodInstance)
  9229. {
  9230. BfTypeInstance* typeInst = methodInstance->mMethodInstanceGroup->mOwner;
  9231. if (mBfIRBuilder == NULL)
  9232. {
  9233. // To allow for custom attribute data
  9234. PrepareForIRWriting(typeInst);
  9235. }
  9236. BfModule* declareModule = this;
  9237. // Get to the optionless branch head -- but this could still be a specialized method module, not the true root
  9238. while ((declareModule->mParentModule != NULL) && (!declareModule->mIsSpecializedMethodModuleRoot))
  9239. declareModule = declareModule->mParentModule;
  9240. // Check for attributes
  9241. if (typeInst == mContext->mBfObjectType)
  9242. {
  9243. auto methodDecl = methodInstance->mMethodDef->GetMethodDeclaration();
  9244. if (methodDecl != NULL)
  9245. {
  9246. auto attributesDirective = methodDecl->mAttributes;
  9247. if ((attributesDirective != NULL) && (mCompiler->mResolvePassData != NULL) &&
  9248. (attributesDirective->IsFromParser(mCompiler->mResolvePassData->mParser)) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  9249. {
  9250. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(attributesDirective);
  9251. }
  9252. }
  9253. }
  9254. else
  9255. {
  9256. // Only allow attributes on System.Object methods that can be handled inside the DefBuilder
  9257. GetMethodCustomAttributes(methodInstance);
  9258. }
  9259. BF_ASSERT(mModuleOptions == NULL);
  9260. if (methodInstance->GetCustomAttributes() != NULL)
  9261. {
  9262. auto project = typeInst->mTypeDef->mProject;
  9263. BfModuleOptions moduleOptions = declareModule->GetModuleOptions();
  9264. BfModuleOptions wantOptions = moduleOptions;
  9265. auto typeOptions = mSystem->GetTypeOptions(typeInst->mTypeOptionsIdx);
  9266. if (typeOptions != NULL)
  9267. {
  9268. wantOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)wantOptions.mOptLevel, (int)typeOptions->mOptimizationLevel);
  9269. wantOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mSIMDSetting, typeOptions->mSIMDSetting);
  9270. wantOptions.mEmitDebugInfo = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mEmitDebugInfo, typeOptions->mEmitDebugInfo);
  9271. }
  9272. if (!mCompiler->mAttributeTypeOptionMap.IsEmpty())
  9273. {
  9274. StringT<128> attrName;
  9275. for (auto& customAttrs : methodInstance->GetCustomAttributes()->mAttributes)
  9276. {
  9277. attrName.Clear();
  9278. customAttrs.mType->mTypeDef->mFullName.ToString(attrName);
  9279. Array<int>* arrPtr;
  9280. if (mCompiler->mAttributeTypeOptionMap.TryGetValue(attrName, &arrPtr))
  9281. {
  9282. for (auto optionsIdx : *arrPtr)
  9283. {
  9284. auto& typeOptions = mCompiler->mSystem->mTypeOptions[optionsIdx];
  9285. wantOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)wantOptions.mOptLevel, (int)typeOptions.mOptimizationLevel);
  9286. wantOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mSIMDSetting, typeOptions.mSIMDSetting);
  9287. wantOptions.mEmitDebugInfo = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mEmitDebugInfo, typeOptions.mEmitDebugInfo);
  9288. }
  9289. }
  9290. }
  9291. }
  9292. if ((HasCompiledOutput()) && (wantOptions != moduleOptions) && (!mIsScratchModule))
  9293. {
  9294. auto lastCheckModule = this;
  9295. auto checkModule = this->mNextAltModule;
  9296. while (checkModule != NULL)
  9297. {
  9298. if (*checkModule->mModuleOptions == wantOptions)
  9299. {
  9300. declareModule = checkModule;
  9301. break;
  9302. }
  9303. lastCheckModule = checkModule;
  9304. checkModule = checkModule->mNextAltModule;
  9305. }
  9306. // Not found?
  9307. if (declareModule == this)
  9308. {
  9309. String specModuleName = mModuleName + "@@";
  9310. if (wantOptions.mOptLevel != moduleOptions.mOptLevel)
  9311. specModuleName += StrFormat("O%d", wantOptions.mOptLevel);
  9312. if (wantOptions.mSIMDSetting != moduleOptions.mSIMDSetting)
  9313. specModuleName += StrFormat("SIMD%d", wantOptions.mSIMDSetting);
  9314. declareModule = new BfModule(mContext, specModuleName);
  9315. declareModule->mProject = project;
  9316. declareModule->mModuleOptions = new BfModuleOptions();
  9317. *declareModule->mModuleOptions = wantOptions;
  9318. declareModule->mParentModule = lastCheckModule;
  9319. declareModule->Init();
  9320. lastCheckModule->mNextAltModule = declareModule;
  9321. }
  9322. }
  9323. }
  9324. declareModule->PrepareForIRWriting(typeInst);
  9325. return declareModule;
  9326. }
  9327. BfModuleMethodInstance BfModule::GetMethodInstance(BfTypeInstance* typeInst, BfMethodDef* methodDef, const BfTypeVector& methodGenericArguments, BfGetMethodInstanceFlags flags, BfTypeInstance* foreignType)
  9328. {
  9329. if (((flags & BfGetMethodInstanceFlag_ForceInline) != 0) && (mCompiler->mIsResolveOnly))
  9330. {
  9331. // Don't bother inlining for resolve-only
  9332. flags = (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline);
  9333. }
  9334. bool processNow = false;
  9335. bool keepInCurrentModule = false;
  9336. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsUnspecialized))
  9337. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_NoForceReification);
  9338. if (!typeInst->IsTypeMemberIncluded(methodDef->mDeclaringType))
  9339. {
  9340. return BfModuleMethodInstance();
  9341. }
  9342. if (methodDef->mIsLocalMethod)
  9343. {
  9344. auto rootMethodState = mCurMethodState->GetRootMethodState();
  9345. BfLocalMethod* localMethod;
  9346. if (rootMethodState->mLocalMethodCache.TryGetValue(methodDef->mName, &localMethod))
  9347. {
  9348. // Handle the def in the correct method state
  9349. return GetLocalMethodInstance(localMethod, methodGenericArguments);
  9350. }
  9351. BF_FATAL("Cannot find local method");
  9352. return BfModuleMethodInstance();
  9353. }
  9354. #ifdef _DEBUG
  9355. for (auto arg : methodGenericArguments)
  9356. BF_ASSERT(!arg->IsVar());
  9357. #endif
  9358. BF_ASSERT(methodDef->mMethodType != BfMethodType_Ignore);
  9359. // We need to do the 'mNeedsMethodProcessing' check because we want to do a proper initial "awaiting reference" population
  9360. // on the methods before we handle an on-demand situation. This also ensures that our type options are set before doing
  9361. // a FinishInit
  9362. if ((typeInst->IsIncomplete()) &&
  9363. (!typeInst->mResolvingVarField) && (!typeInst->mTypeFailed))
  9364. {
  9365. // For autocomplete, we still may not actually generate methods. This shouldn't matter, and on-demand works differently
  9366. // for resolve-only because we don't differentiate between reified/unreified there
  9367. PopulateType(typeInst, BfPopulateType_Full);
  9368. }
  9369. bool tryModuleMethodLookup = false;
  9370. BfModuleMethodInstance moduleMethodInst;
  9371. BfModule* instModule = typeInst->mModule;
  9372. if (keepInCurrentModule)
  9373. {
  9374. // Stay here
  9375. instModule = this;
  9376. }
  9377. if (this == mContext->mUnreifiedModule)
  9378. {
  9379. // Stay in this 'resolve only' module here
  9380. }
  9381. else if (flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass)
  9382. {
  9383. BF_ASSERT(this == mContext->mUnreifiedModule);
  9384. }
  9385. else if (flags & BfGetMethodInstanceFlag_ExplicitSpecializedModule)
  9386. {
  9387. BF_ASSERT(instModule == mParentModule);
  9388. }
  9389. else if (instModule != this)
  9390. {
  9391. if ((!mIsReified) && (instModule->mIsReified))
  9392. {
  9393. BF_ASSERT(!mCompiler->mIsResolveOnly);
  9394. // A resolve-only module is specializing a method from a type in a reified module,
  9395. // we need to take care that this doesn't cause anything new to become reified
  9396. return mContext->mUnreifiedModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ExplicitResolveOnlyPass), foreignType);
  9397. }
  9398. else
  9399. {
  9400. if ((mIsReified) && (!instModule->mIsReified))
  9401. {
  9402. if (!instModule->mReifyQueued)
  9403. {
  9404. BF_ASSERT((mCompiler->mCompileState != BfCompiler::CompileState_Unreified) && (mCompiler->mCompileState != BfCompiler::CompileState_VData));
  9405. BfLogSysM("Queueing ReifyModule: %p\n", instModule);
  9406. mContext->mReifyModuleWorkList.Add(instModule);
  9407. instModule->mReifyQueued = true;
  9408. }
  9409. // This ensures that the method will actually be created when it gets reified
  9410. BfMethodSpecializationRequest* specializationRequest = mContext->mMethodSpecializationWorkList.Alloc();
  9411. specializationRequest->mFromModule = typeInst->mModule;
  9412. specializationRequest->mFromModuleRevision = typeInst->mModule->mRevision;
  9413. specializationRequest->mMethodDef = methodDef;
  9414. specializationRequest->mMethodGenericArguments = methodGenericArguments;
  9415. specializationRequest->mType = typeInst;
  9416. }
  9417. auto defFlags = (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline);
  9418. // Not extern
  9419. // Create the instance in the proper module and then create a reference in this one
  9420. moduleMethodInst = instModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, defFlags, foreignType);
  9421. tryModuleMethodLookup = true;
  9422. if ((mIsReified) && (!moduleMethodInst.mMethodInstance->mIsReified))
  9423. {
  9424. CheckHotMethod(moduleMethodInst.mMethodInstance, "");
  9425. }
  9426. }
  9427. }
  9428. if (tryModuleMethodLookup)
  9429. return ReferenceExternalMethodInstance(moduleMethodInst.mMethodInstance, flags);
  9430. if (((flags & BfGetMethodInstanceFlag_ForceInline) != 0) && (!methodDef->mAlwaysInline))
  9431. {
  9432. auto moduleMethodInstance = GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline), foreignType);
  9433. if (moduleMethodInstance)
  9434. return ReferenceExternalMethodInstance(moduleMethodInstance.mMethodInstance, flags);
  9435. return moduleMethodInst;
  9436. }
  9437. bool isReified = mIsReified /* || ((flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass) != 0)*/;
  9438. bool hadConcreteInterfaceGenericArgument = false;
  9439. if ((flags & BfGetMethodInstanceFlag_Unreified) != 0)
  9440. isReified = false;
  9441. if ((flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass) != 0)
  9442. {
  9443. isReified = false;
  9444. }
  9445. BfTypeVector sanitizedMethodGenericArguments;
  9446. Array<BfProject*> projectList;
  9447. bool isUnspecializedPass = (flags & BfGetMethodInstanceFlag_UnspecializedPass) != 0;
  9448. if ((isUnspecializedPass) && (methodDef->mGenericParams.size() == 0))
  9449. isUnspecializedPass = false;
  9450. // 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
  9451. bool isExternalExtensionMethod = false;
  9452. if ((!typeInst->IsUnspecializedType()) && (!isUnspecializedPass))
  9453. {
  9454. if (((flags & BfGetMethodInstanceFlag_ForeignMethodDef) == 0) && (methodDef->mDeclaringType->mProject != typeInst->mTypeDef->mProject))
  9455. {
  9456. auto specProject = methodDef->mDeclaringType->mProject;
  9457. isExternalExtensionMethod = true;
  9458. if (typeInst->IsGenericTypeInstance())
  9459. {
  9460. auto genericTypeInst = (BfGenericTypeInstance*)typeInst;
  9461. if (genericTypeInst->mProjectsReferenced.empty())
  9462. genericTypeInst->GenerateProjectsReferenced();
  9463. if (genericTypeInst->mProjectsReferenced.Contains(specProject))
  9464. {
  9465. // This is a generic type where a generic param is already confined to the project in question
  9466. isExternalExtensionMethod = false;
  9467. }
  9468. }
  9469. if (isExternalExtensionMethod)
  9470. {
  9471. BF_ASSERT(typeInst->mTypeDef->mIsCombinedPartial);
  9472. projectList.push_back(methodDef->mDeclaringType->mProject);
  9473. }
  9474. }
  9475. }
  9476. if ((!isUnspecializedPass) && (methodGenericArguments.size() != 0))
  9477. {
  9478. int typeProjectsCounts = 0;
  9479. if (typeInst->IsGenericTypeInstance())
  9480. {
  9481. auto genericTypeInst = (BfGenericTypeInstance*)typeInst;
  9482. if (genericTypeInst->mProjectsReferenced.empty())
  9483. genericTypeInst->GenerateProjectsReferenced();
  9484. typeProjectsCounts = (int)genericTypeInst->mProjectsReferenced.size();
  9485. projectList.Insert(0, &genericTypeInst->mProjectsReferenced[0], genericTypeInst->mProjectsReferenced.size());
  9486. }
  9487. else
  9488. {
  9489. typeProjectsCounts = 1;
  9490. projectList.Insert(0, typeInst->mTypeDef->mProject);
  9491. }
  9492. isUnspecializedPass = true;
  9493. for (int genericArgIdx = 0; genericArgIdx < (int) methodGenericArguments.size(); genericArgIdx++)
  9494. {
  9495. auto genericArgType = methodGenericArguments[genericArgIdx];
  9496. //BF_ASSERT(!genericArgType->IsRef());
  9497. if (genericArgType->IsConcreteInterfaceType())
  9498. {
  9499. hadConcreteInterfaceGenericArgument = true;
  9500. auto concreteInterfaceType = (BfConcreteInterfaceType*)genericArgType;
  9501. genericArgType = concreteInterfaceType->mInterface;
  9502. }
  9503. if (genericArgType->IsGenericParam())
  9504. {
  9505. auto genericParam = (BfGenericParamType*) genericArgType;
  9506. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  9507. isUnspecializedPass = false;
  9508. }
  9509. else
  9510. {
  9511. BfTypeUtils::GetProjectList(genericArgType, &projectList, typeProjectsCounts);
  9512. isUnspecializedPass = false;
  9513. }
  9514. sanitizedMethodGenericArguments.push_back(genericArgType);
  9515. }
  9516. if ((int)projectList.size() > typeProjectsCounts)
  9517. {
  9518. // Just leave the new items
  9519. projectList.RemoveRange(0, typeProjectsCounts);
  9520. std::sort(projectList.begin(), projectList.end(), [](BfProject* lhs, BfProject*rhs)
  9521. {
  9522. return lhs->mName < rhs->mName;
  9523. });
  9524. }
  9525. else
  9526. {
  9527. projectList.Clear();
  9528. }
  9529. }
  9530. const BfTypeVector& lookupMethodGenericArguments = isUnspecializedPass ? BfTypeVector() : sanitizedMethodGenericArguments;
  9531. BfMethodInstanceGroup* methodInstGroup = NULL;
  9532. if ((flags & BfGetMethodInstanceFlag_ForeignMethodDef) != 0)
  9533. {
  9534. BF_ASSERT(!typeInst->IsInterface());
  9535. //for (auto& checkGroup : typeInst->mMethodInstanceGroups)
  9536. for (int methodIdx = (int)typeInst->mTypeDef->mMethods.size(); methodIdx < (int)typeInst->mMethodInstanceGroups.size(); methodIdx++)
  9537. {
  9538. auto& checkGroup = typeInst->mMethodInstanceGroups[methodIdx];
  9539. // if (checkGroup.mDefault == NULL)
  9540. // {
  9541. // // This should only be for when we explicitly add a spot so we can set mOnDemandKind
  9542. // BF_ASSERT(methodIdx == typeInst->mMethodInstanceGroups.size() - 1);
  9543. // methodInstGroup = &checkGroup;
  9544. // break;
  9545. // }
  9546. if ((checkGroup.mDefault != NULL) && (checkGroup.mDefault->mMethodDef == methodDef))
  9547. {
  9548. methodInstGroup = &checkGroup;
  9549. break;
  9550. }
  9551. }
  9552. if (methodInstGroup == NULL)
  9553. {
  9554. // Allocate a new entry
  9555. typeInst->mMethodInstanceGroups.Resize(typeInst->mMethodInstanceGroups.size() + 1);
  9556. methodInstGroup = &typeInst->mMethodInstanceGroups.back();
  9557. methodInstGroup->mMethodIdx = (int)typeInst->mMethodInstanceGroups.size() - 1;
  9558. methodInstGroup->mOwner = typeInst;
  9559. // if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet)
  9560. // methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  9561. if (mCompiler->mOptions.mCompileOnDemandKind == BfCompileOnDemandKind_AlwaysInclude)
  9562. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  9563. else
  9564. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingDecl;
  9565. }
  9566. }
  9567. else
  9568. {
  9569. methodInstGroup = &typeInst->mMethodInstanceGroups[methodDef->mIdx];
  9570. }
  9571. if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet)
  9572. {
  9573. BfLogSysM("Forcing BfMethodOnDemandKind_NotSet to BfMethodOnDemandKind_AlwaysInclude for Method:%s in Type:%p\n", methodDef->mName.c_str(), typeInst);
  9574. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  9575. }
  9576. BfIRFunction prevIRFunc;
  9577. bool doingRedeclare = false;
  9578. BfMethodInstance* methodInstance = NULL;
  9579. auto _SetReified = [&]()
  9580. {
  9581. methodInstance->mIsReified = true;
  9582. };
  9583. if (lookupMethodGenericArguments.size() == 0)
  9584. {
  9585. methodInstance = methodInstGroup->mDefault;
  9586. if ((methodInstance != NULL) && (isReified) && (!methodInstance->mIsReified))
  9587. {
  9588. MarkDerivedDirty(typeInst);
  9589. if (mIsScratchModule)
  9590. {
  9591. BfLogSysM("Marking scratch module method instance as reified: %p\n", methodInstance);
  9592. _SetReified();
  9593. CheckHotMethod(methodInstance, "");
  9594. }
  9595. else if ((flags & BfGetMethodInstanceFlag_NoForceReification) != 0)
  9596. {
  9597. // We don't need to force reification if we're in an unspecialized generic- we can wait for
  9598. // the specializations to handle that for us
  9599. return BfModuleMethodInstance(methodInstance);
  9600. }
  9601. else if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_Referenced)
  9602. {
  9603. if (methodDef->mIsAbstract)
  9604. {
  9605. BfLogSysM("Reifying abstract unreified method instance: %p IRFunction:%d\n", methodInstance, methodInstance->mIRFunction.mId);
  9606. _SetReified();
  9607. }
  9608. else
  9609. {
  9610. BfLogSysM("Re-declaring processed but unreified method instance: %p IRFunction:%d\n", methodInstance, methodInstance->mIRFunction.mId);
  9611. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_NoDecl_AwaitingReference;
  9612. methodInstance->UndoDeclaration(!methodInstance->mIRFunction.IsFake());
  9613. doingRedeclare = true;
  9614. mOnDemandMethodCount++;
  9615. }
  9616. }
  9617. else
  9618. {
  9619. BfLogSysM("Marking unprocessed method instance as reified: %p\n", methodInstance);
  9620. // We haven't processed it yet
  9621. _SetReified();
  9622. CheckHotMethod(methodInstance, "");
  9623. if (methodInstance->mDeclModule == this)
  9624. {
  9625. if (methodInstance->mMethodProcessRequest != NULL)
  9626. {
  9627. // Disconnect method process request
  9628. BF_ASSERT(methodInstance->mMethodProcessRequest->mFromModule == this);
  9629. }
  9630. }
  9631. else
  9632. {
  9633. if (methodInstance->mMethodProcessRequest != NULL)
  9634. {
  9635. // Disconnect method process request
  9636. BF_ASSERT(methodInstance->mMethodProcessRequest->mFromModule == mContext->mUnreifiedModule);
  9637. methodInstance->mMethodProcessRequest->mMethodInstance = NULL;
  9638. methodInstance->mMethodProcessRequest = NULL;
  9639. }
  9640. if (methodInstance->mDeclModule == mContext->mUnreifiedModule)
  9641. {
  9642. // Add new request in proper module
  9643. methodInstance->mDeclModule = this;
  9644. }
  9645. else
  9646. {
  9647. if (methodInstance->mDeclModule == NULL)
  9648. {
  9649. //
  9650. }
  9651. else if (methodInstance->mDeclModule != this)
  9652. {
  9653. // Is from specialized module?
  9654. BF_ASSERT(methodInstance->mDeclModule->mParentModule == this);
  9655. }
  9656. }
  9657. if ((!methodInstance->mIRFunction) || (methodInstance->mIRFunction.IsFake()))
  9658. {
  9659. methodInstance->mIRFunction = BfIRFunction();
  9660. if (!mIsModuleMutable)
  9661. StartExtension();
  9662. if ((!mBfIRBuilder->mIgnoreWrites) && (methodInstance->mDeclModule != NULL))
  9663. {
  9664. StringT<128> mangledName;
  9665. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  9666. bool isIntrinsic = false;
  9667. SetupIRFunction(methodInstance, mangledName, false, &isIntrinsic);
  9668. BfLogSysM("Creating new IRFunction %d\n", methodInstance->mIRFunction.mId);
  9669. }
  9670. }
  9671. AddMethodToWorkList(methodInstance);
  9672. }
  9673. }
  9674. }
  9675. }
  9676. else
  9677. {
  9678. BF_ASSERT(lookupMethodGenericArguments.size() != 0);
  9679. if (methodInstGroup->mMethodSpecializationMap == NULL)
  9680. methodInstGroup->mMethodSpecializationMap = new BfMethodInstanceGroup::MapType();
  9681. BfMethodInstance** methodInstancePtr = NULL;
  9682. if (methodInstGroup->mMethodSpecializationMap->TryGetValue(lookupMethodGenericArguments, &methodInstancePtr))
  9683. {
  9684. methodInstance = *methodInstancePtr;
  9685. if ((isReified) && (!methodInstance->mIsReified))
  9686. {
  9687. MarkDerivedDirty(typeInst);
  9688. if (methodInstance->mHasBeenProcessed)
  9689. {
  9690. BfLogSysM("Deleting processed but unreified specialized method instance %p\n", methodInstance);
  9691. delete methodInstance;
  9692. methodInstGroup->mMethodSpecializationMap->Remove(lookupMethodGenericArguments);
  9693. methodInstance = NULL;
  9694. }
  9695. else if ((!methodInstance->mIRFunction) || (methodInstance->mIRFunction.IsFake()))
  9696. {
  9697. BfLogSysM("Deleting declared but uncreated specialized method instance %p\n", methodInstance);
  9698. delete methodInstance;
  9699. methodInstGroup->mMethodSpecializationMap->Remove(lookupMethodGenericArguments);
  9700. methodInstance = NULL;
  9701. }
  9702. else
  9703. {
  9704. BfLogSysM("Reifying declared but unreified method instance %p\n", methodInstance);
  9705. // We haven't processed it yet
  9706. _SetReified();
  9707. CheckHotMethod(methodInstance, "");
  9708. }
  9709. }
  9710. }
  9711. }
  9712. if ((methodInstance != NULL) && (!doingRedeclare))
  9713. {
  9714. if (methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference)
  9715. {
  9716. /*if ((!mCompiler->mIsResolveOnly) && (!isReified))
  9717. BF_ASSERT(!methodInstance->mIsReified);*/
  9718. if (methodInstance->mIsReified != isReified)
  9719. BfLogSysM("GetMethodInstance %p Decl_AwaitingReference setting reified to %d\n", methodInstance, isReified);
  9720. if ((!isReified) &&
  9721. ((methodInstance->mDeclModule == NULL) || (!methodInstance->mDeclModule->mIsModuleMutable)))
  9722. {
  9723. methodInstance->mDeclModule = mContext->mUnreifiedModule;
  9724. methodInstance->mIRFunction = BfIRFunction();
  9725. }
  9726. methodInstance->mIsReified = isReified;
  9727. if ((methodInstance->mHotMethod != NULL) && (!mCompiler->IsHotCompile()) && (isReified))
  9728. {
  9729. methodInstance->mHotMethod->mFlags = (BfHotDepDataFlags)(methodInstance->mHotMethod->mFlags | BfHotDepDataFlag_IsOriginalBuild);
  9730. }
  9731. if (!methodInstance->mMethodDef->mIsAbstract)
  9732. {
  9733. AddMethodToWorkList(methodInstance);
  9734. }
  9735. else
  9736. {
  9737. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Referenced;
  9738. }
  9739. }
  9740. if (mExtensionCount > 0)
  9741. {
  9742. if ((mIsModuleMutable) && (!methodInstance->mIRFunction) &&
  9743. ((projectList.IsEmpty() || ((flags & BfGetMethodInstanceFlag_ExplicitSpecializedModule) != 0))))
  9744. {
  9745. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, false);
  9746. if (mAwaitingInitFinish)
  9747. FinishInit();
  9748. // We need to refer to a function that was defined in a prior module
  9749. bool isInlined = (methodInstance->mAlwaysInline) || ((flags & BfGetMethodInstanceFlag_ForceInline) != 0);
  9750. methodInstance->mIRFunction = CreateFunctionFrom(methodInstance, false, isInlined);
  9751. BF_ASSERT((methodInstance->mDeclModule == this) || (methodInstance->mDeclModule == mContext->mUnreifiedModule) || (methodInstance->mDeclModule == NULL));
  9752. methodInstance->mDeclModule = this;
  9753. // Add this inlined def to ourselves
  9754. if ((methodInstance->mAlwaysInline) && (HasCompiledOutput()) && (!methodInstance->mIsUnspecialized))
  9755. {
  9756. mIncompleteMethodCount++;
  9757. BfInlineMethodRequest* inlineMethodRequest = mContext->mInlineMethodWorkList.Alloc();
  9758. inlineMethodRequest->mType = typeInst;
  9759. inlineMethodRequest->mFromModule = this;
  9760. inlineMethodRequest->mFunc = methodInstance->mIRFunction;
  9761. inlineMethodRequest->mFromModuleRevision = mRevision;
  9762. inlineMethodRequest->mMethodInstance = methodInstance;
  9763. BfLogSysM("mInlineMethodWorkList %p for method %p in module %p in GetMethodInstance\n", inlineMethodRequest, methodInstance, this);
  9764. BF_ASSERT(mIsModuleMutable);
  9765. }
  9766. }
  9767. }
  9768. if (mCompiler->IsSkippingExtraResolveChecks())
  9769. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  9770. else
  9771. {
  9772. if (methodInstance->mDeclModule != this)
  9773. return ReferenceExternalMethodInstance(methodInstance, flags);
  9774. if ((!methodInstance->mIRFunction) && (mIsModuleMutable) && (!mBfIRBuilder->mIgnoreWrites))
  9775. {
  9776. auto importKind = methodInstance->GetImportCallKind();
  9777. if (importKind != BfImportCallKind_None)
  9778. {
  9779. BfLogSysM("DllImportGlobalVar creating %p\n", methodInstance);
  9780. methodInstance->mIRFunction = mBfIRBuilder->GetFakeVal();
  9781. mFuncReferences[methodInstance] = CreateDllImportGlobalVar(methodInstance, true);;
  9782. }
  9783. }
  9784. return BfModuleMethodInstance(methodInstance);
  9785. }
  9786. }
  9787. if (!doingRedeclare)
  9788. {
  9789. BfModule* specModule = NULL;
  9790. if ((!keepInCurrentModule) && (projectList.size() > 0) && (!isUnspecializedPass) && (HasCompiledOutput()) && (!mIsScratchModule))
  9791. {
  9792. specModule = GetSpecializedMethodModule(projectList);
  9793. }
  9794. if ((specModule != NULL) && (specModule != this))
  9795. {
  9796. auto specMethodInstance = specModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ExplicitSpecializedModule));
  9797. if (mAwaitingInitFinish)
  9798. return BfModuleMethodInstance(specMethodInstance.mMethodInstance, BfIRFunction());
  9799. return ReferenceExternalMethodInstance(specMethodInstance.mMethodInstance, flags);
  9800. }
  9801. if ((!isUnspecializedPass) && (methodGenericArguments.size() != 0) && (methodInstGroup->mDefault == NULL))
  9802. {
  9803. // We are attempting to specialize but we don't have the unspecialized method yet. Generate that first.
  9804. GetMethodInstance(typeInst, methodDef, BfTypeVector(), BfGetMethodInstanceFlag_UnspecializedPass);
  9805. }
  9806. }
  9807. if (methodInstance == NULL)
  9808. {
  9809. if (lookupMethodGenericArguments.size() == 0)
  9810. {
  9811. BF_ASSERT(methodInstGroup->mDefault == NULL);
  9812. methodInstance = new BfMethodInstance();
  9813. methodInstGroup->mDefault = methodInstance;
  9814. BfLogSysM("Created Default MethodInst: %p TypeInst: %p Group: %p\n", methodInstance, typeInst, methodInstGroup);
  9815. }
  9816. else
  9817. {
  9818. BfMethodInstance** methodInstancePtr = NULL;
  9819. bool added = methodInstGroup->mMethodSpecializationMap->TryAdd(lookupMethodGenericArguments, NULL, &methodInstancePtr);
  9820. BF_ASSERT(added);
  9821. methodInstance = new BfMethodInstance();
  9822. *methodInstancePtr = methodInstance;
  9823. BfLogSysM("Created Specialized MethodInst: %p TypeInst: %p\n", methodInstance, typeInst);
  9824. }
  9825. if ((prevIRFunc) && (!prevIRFunc.IsFake()))
  9826. methodInstance->mIRFunction = prevIRFunc; // Take it over
  9827. }
  9828. /*// 24 bits for typeid, 20 for method id, 20 for specialization index
  9829. methodInstance->mMethodId = ((int64)typeInst->mTypeId) + ((int64)methodInstGroup->mMethodIdx << 24);
  9830. if (methodInstGroup->mMethodSpecializationMap != NULL)
  9831. methodInstance->mMethodId += ((int64)methodInstGroup->mMethodSpecializationMap->size() << 44);*/
  9832. methodInstance->mMethodDef = methodDef;
  9833. methodInstance->mAlwaysInline = methodDef->mAlwaysInline;
  9834. methodInstance->mMethodInstanceGroup = methodInstGroup;
  9835. methodInstance->mIsReified = isReified;
  9836. SetupMethodIdHash(methodInstance);
  9837. if (hadConcreteInterfaceGenericArgument)
  9838. methodInstance->mIgnoreBody = true;
  9839. if ((flags & BfGetMethodInstanceFlag_ForeignMethodDef) != 0)
  9840. {
  9841. methodInstance->mIsForeignMethodDef = true;
  9842. BF_ASSERT(foreignType != NULL);
  9843. methodInstance->GetMethodInfoEx()->mForeignType = foreignType;
  9844. }
  9845. if ((typeInst->mTypeDef == mCompiler->mValueTypeTypeDef) && (methodDef->mName == BF_METHODNAME_EQUALS))
  9846. {
  9847. if (!lookupMethodGenericArguments.empty())
  9848. {
  9849. auto compareType = lookupMethodGenericArguments[0];
  9850. PopulateType(compareType, BfPopulateType_Data);
  9851. if (compareType->IsSplattable())
  9852. methodInstance->mAlwaysInline = true;
  9853. }
  9854. }
  9855. if (methodDef->mDeclaringType->mTypeDeclaration != typeInst->mTypeDef->mTypeDeclaration)
  9856. {
  9857. // With extensions we can have multiple definitions of the same method
  9858. //methodInstance->mMangleWithIdx = true;
  9859. }
  9860. BfModule* declareModule = GetOrCreateMethodModule(methodInstance);
  9861. BF_ASSERT(typeInst == methodInstance->GetOwner());
  9862. auto methodDeclaration = methodDef->GetMethodDeclaration();
  9863. if (isUnspecializedPass)
  9864. {
  9865. for (int genericParamIdx = 0; genericParamIdx < (int) methodDef->mGenericParams.size(); genericParamIdx++)
  9866. {
  9867. auto genericParamType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  9868. methodInstance->GetMethodInfoEx()->mMethodGenericArguments.Add(genericParamType);
  9869. }
  9870. }
  9871. else if ((methodDeclaration != NULL) && (methodDeclaration->mGenericParams != NULL))
  9872. {
  9873. if (!sanitizedMethodGenericArguments.IsEmpty())
  9874. methodInstance->GetMethodInfoEx()->mMethodGenericArguments = sanitizedMethodGenericArguments;
  9875. if (methodDef->mGenericParams.size() != sanitizedMethodGenericArguments.size())
  9876. {
  9877. Fail("Internal error");
  9878. BF_FATAL("Generic method argument counts mismatch");
  9879. return NULL;
  9880. }
  9881. for (auto genericArg : sanitizedMethodGenericArguments)
  9882. {
  9883. if (genericArg->IsPrimitiveType())
  9884. genericArg = GetWrappedStructType(genericArg);
  9885. AddDependency(genericArg, typeInst, BfDependencyMap::DependencyFlag_MethodGenericArg);
  9886. if (genericArg->IsMethodRef())
  9887. {
  9888. auto methodRefType = (BfMethodRefType*)genericArg;
  9889. //AddDependency(genericArg, typeInst, BfDependencyMap::DependencyFlag_);
  9890. }
  9891. }
  9892. }
  9893. // Generic constraints
  9894. for (int genericParamIdx = 0; genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  9895. {
  9896. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, genericParamIdx);
  9897. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  9898. }
  9899. bool addToWorkList = !processNow;
  9900. if (mCompiler->GetAutoComplete() != NULL)
  9901. {
  9902. if (typeInst->IsSpecializedByAutoCompleteMethod())
  9903. addToWorkList = false;
  9904. }
  9905. BF_ASSERT(declareModule != NULL);
  9906. methodInstance->mDeclModule = declareModule;
  9907. if ((!methodInstance->mIsReified) && (mCompiler->mCompileState != BfCompiler::CompileState_Normal))
  9908. {
  9909. // We can be sure this method won't become reified later. Normally we can "go either way" with an unreified method
  9910. // of a reified module -
  9911. // If we declare it in the reified module then we can switch it to "reified" before actual processing without any extra work,
  9912. // BUT if we don't reify it then we have to remove the body after processing.
  9913. // 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
  9914. // the proper reified module.
  9915. declareModule = mContext->mUnreifiedModule;
  9916. }
  9917. else if ((!declareModule->mIsModuleMutable) && (!mCompiler->mIsResolveOnly))
  9918. {
  9919. BF_ASSERT(!methodInstance->mIsReified);
  9920. declareModule = mContext->mUnreifiedModule;
  9921. }
  9922. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  9923. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(declareModule->mCurTypeInstance, typeInst);
  9924. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  9925. declareModule->DoMethodDeclaration(methodDef->GetMethodDeclaration(), false, addToWorkList);
  9926. if (processNow)
  9927. {
  9928. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, NULL);
  9929. ProcessMethod(methodInstance);
  9930. }
  9931. if (mCompiler->IsSkippingExtraResolveChecks())
  9932. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  9933. return BfModuleMethodInstance(methodInstance);
  9934. }
  9935. BfModuleMethodInstance BfModule::GetMethodInstance(BfMethodInstance* methodInstance, BfGetMethodInstanceFlags flags)
  9936. {
  9937. BF_ASSERT((methodInstance->mMethodInfoEx == NULL) || (methodInstance->mMethodInfoEx->mGenericParams.IsEmpty()));
  9938. if (methodInstance->mIsForeignMethodDef)
  9939. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ForeignMethodDef);
  9940. return GetMethodInstance(methodInstance->GetOwner(), methodInstance->mMethodDef, BfTypeVector(), flags);
  9941. }
  9942. BfMethodInstance* BfModule::GetOuterMethodInstance(BfMethodInstance* methodInstance)
  9943. {
  9944. if (!methodInstance->mMethodDef->mIsLocalMethod)
  9945. return NULL;
  9946. auto outerLocal = methodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod->mOuterLocalMethod;
  9947. if (outerLocal == NULL)
  9948. return NULL;
  9949. BfTypeVector genericArgs;
  9950. for (int i = 0; i < (int)outerLocal->mMethodDef->mGenericParams.size(); i++)
  9951. genericArgs.Add(methodInstance->mMethodInfoEx->mMethodGenericArguments[i]);
  9952. return GetLocalMethodInstance(outerLocal, genericArgs).mMethodInstance;
  9953. }
  9954. void BfModule::SetupMethodIdHash(BfMethodInstance* methodInstance)
  9955. {
  9956. HashContext hashCtx;
  9957. std::function<void(BfMethodInstance*)> _MixinMethodInstance = [&](BfMethodInstance* methodInstance)
  9958. {
  9959. hashCtx.Mixin(methodInstance->GetOwner()->mTypeId);
  9960. hashCtx.Mixin(methodInstance->mMethodDef->mIdx);
  9961. if (methodInstance->GetNumGenericArguments() != 0)
  9962. {
  9963. hashCtx.Mixin((int32)methodInstance->mMethodInfoEx->mMethodGenericArguments.size());
  9964. for (auto methodGenericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  9965. hashCtx.Mixin(methodGenericArg->mTypeId);
  9966. }
  9967. };
  9968. _MixinMethodInstance(methodInstance);
  9969. if (methodInstance->mMethodDef->mIsLocalMethod)
  9970. {
  9971. auto outmostMethodInstance = mCurMethodState->GetRootMethodState()->mMethodInstance;
  9972. BF_ASSERT((outmostMethodInstance->mIdHash != 0) || (outmostMethodInstance->mIsAutocompleteMethod));
  9973. hashCtx.Mixin(outmostMethodInstance->mIdHash);
  9974. }
  9975. methodInstance->mIdHash = (int64)hashCtx.Finish64();
  9976. }
  9977. BfIRValue BfModule::GetInterfaceSlotNum(BfTypeInstance* ifaceType)
  9978. {
  9979. BfIRValue globalValue;
  9980. BfIRValue* globalValuePtr = NULL;
  9981. if (mInterfaceSlotRefs.TryGetValue(ifaceType, &globalValuePtr))
  9982. {
  9983. globalValue = *globalValuePtr;
  9984. }
  9985. if (!globalValue)
  9986. {
  9987. // This is necessary to reify the interface type
  9988. PopulateType(ifaceType);
  9989. StringT<128> slotVarName;
  9990. BfMangler::MangleStaticFieldName(slotVarName, mCompiler->GetMangleKind(), ifaceType, "sBfSlotOfs");
  9991. BfType* intType = GetPrimitiveType(BfTypeCode_Int32);
  9992. BfIRValue value;
  9993. if ((mCompiler->mHotState != NULL) && (ifaceType->mSlotNum >= 0))
  9994. {
  9995. /*// If this interface already existed before this hot compile but we never indirectly called any of its methods
  9996. // then the sBfSlotOfs could have gotten its symbol stripped, so actually define it here.
  9997. int virtSlotIdx = ifaceType->mSlotNum + 1;
  9998. value = GetConstValue32(virtSlotIdx);*/
  9999. mCompiler->mHotState->mSlotDefineTypeIds.Add(ifaceType->mTypeId);
  10000. ifaceType->mDirty = true; // Makes sure we create interface in vdata
  10001. }
  10002. globalValue = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(intType), true, BfIRLinkageType_External, value, slotVarName);
  10003. mInterfaceSlotRefs[ifaceType] = globalValue;
  10004. }
  10005. return mBfIRBuilder->CreateLoad(globalValue/*, "slotOfs"*/);
  10006. }
  10007. void BfModule::HadSlotCountDependency()
  10008. {
  10009. if (mCompiler->mIsResolveOnly)
  10010. return;
  10011. BF_ASSERT(!mBfIRBuilder->mIgnoreWrites);
  10012. BF_ASSERT((mUsedSlotCount == BF_MAX(mCompiler->mMaxInterfaceSlots, 0)) || (mUsedSlotCount == -1));
  10013. mUsedSlotCount = BF_MAX(mCompiler->mMaxInterfaceSlots, 0);
  10014. }
  10015. BfTypedValue BfModule::ReferenceStaticField(BfFieldInstance* fieldInstance)
  10016. {
  10017. if (mIsScratchModule)
  10018. {
  10019. // Just fake it for the extern and unspecialized modules
  10020. auto ptrType = CreatePointerType(fieldInstance->GetResolvedType());
  10021. return BfTypedValue(GetDefaultValue(ptrType), fieldInstance->GetResolvedType(), true);
  10022. }
  10023. BfIRValue globalValue;
  10024. auto fieldDef = fieldInstance->GetFieldDef();
  10025. if ((fieldDef->mIsConst) && (!fieldDef->mIsExtern))
  10026. {
  10027. if (fieldInstance->mConstIdx != -1)
  10028. {
  10029. auto constant = fieldInstance->mOwner->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  10030. return BfTypedValue(ConstantToCurrent(constant, fieldInstance->mOwner->mConstHolder, fieldInstance->GetResolvedType()), fieldInstance->GetResolvedType());
  10031. }
  10032. else
  10033. {
  10034. return GetDefaultTypedValue(fieldInstance->GetResolvedType());
  10035. }
  10036. }
  10037. BfIRValue* globalValuePtr = NULL;
  10038. if (mStaticFieldRefs.TryGetValue(fieldInstance, &globalValuePtr))
  10039. {
  10040. globalValue = *globalValuePtr;
  10041. BF_ASSERT(globalValue);
  10042. }
  10043. else
  10044. {
  10045. StringT<128> staticVarName;
  10046. BfMangler::Mangle(staticVarName, mCompiler->GetMangleKind(), fieldInstance);
  10047. auto typeType = fieldInstance->GetResolvedType();
  10048. if ((fieldDef->mIsExtern) && (fieldDef->mIsConst) && (typeType->IsPointer()))
  10049. {
  10050. typeType = typeType->GetUnderlyingType();
  10051. }
  10052. PopulateType(typeType);
  10053. if ((typeType != NULL) && (!typeType->IsValuelessType()))
  10054. {
  10055. globalValue = mBfIRBuilder->CreateGlobalVariable(
  10056. mBfIRBuilder->MapType(typeType),
  10057. false,
  10058. BfIRLinkageType_External,
  10059. BfIRValue(),
  10060. staticVarName,
  10061. IsThreadLocal(fieldInstance));
  10062. if (!mBfIRBuilder->mIgnoreWrites)
  10063. {
  10064. // Only store this if we actually did the creation
  10065. BF_ASSERT(globalValue);
  10066. mStaticFieldRefs[fieldInstance] = globalValue;
  10067. }
  10068. BfLogSysM("Mod:%p Type:%p ReferenceStaticField %p -> %p\n", this, fieldInstance->mOwner, fieldInstance, globalValue);
  10069. }
  10070. }
  10071. auto type = fieldInstance->GetResolvedType();
  10072. if (type->IsValuelessType())
  10073. return BfTypedValue(globalValue, type);
  10074. return BfTypedValue(globalValue, type, !fieldDef->mIsConst);
  10075. }
  10076. BfTypedValue BfModule::GetThis()
  10077. {
  10078. auto useMethodState = mCurMethodState;
  10079. while ((useMethodState != NULL) && (useMethodState->mClosureState != NULL) && (useMethodState->mClosureState->mCapturing))
  10080. {
  10081. useMethodState = useMethodState->mPrevMethodState;
  10082. }
  10083. if (useMethodState != NULL)
  10084. {
  10085. // Fake a 'this' for var field resolution
  10086. if (useMethodState->mTempKind == BfMethodState::TempKind_NonStatic)
  10087. {
  10088. auto thisType = mCurTypeInstance;
  10089. if (thisType->IsValueType())
  10090. return BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(thisType)), thisType, BfTypedValueKind_ThisAddr);
  10091. else
  10092. return BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInst(thisType)), thisType, BfTypedValueKind_ThisValue);
  10093. }
  10094. else if (useMethodState->mTempKind == BfMethodState::TempKind_Static)
  10095. {
  10096. return BfTypedValue();
  10097. }
  10098. }
  10099. else
  10100. {
  10101. //TODO: Do we allow useMethodState to be NULL anymore?
  10102. return BfTypedValue();
  10103. }
  10104. // if (useMethodState->HasNonStaticMixin())
  10105. // {
  10106. // auto checkMethodState = useMethodState;
  10107. // while (checkMethodState != NULL)
  10108. // {
  10109. // for (int localIdx = (int)checkMethodState->mLocals.size() - 1; localIdx >= 0; localIdx--)
  10110. // {
  10111. // auto varDecl = checkMethodState->mLocals[localIdx];
  10112. // if (varDecl->mName == "this")
  10113. // {
  10114. // varDecl->mReadFromId = useMethodState->GetRootMethodState()->mCurAccessId++;
  10115. // if (varDecl->mIsSplat)
  10116. // {
  10117. // return BfTypedValue(varDecl->mValue, varDecl->mResolvedType, BfTypedValueKind_ThisSplatHead);
  10118. // }
  10119. // else if ((varDecl->mResolvedType->IsValueType()) && (varDecl->mAddr))
  10120. // {
  10121. // return BfTypedValue(varDecl->mAddr, varDecl->mResolvedType, BfTypedValueKind_ThisAddr);
  10122. // }
  10123. // return BfTypedValue(varDecl->mValue, varDecl->mResolvedType, varDecl->mResolvedType->IsValueType() ? BfTypedValueKind_ThisAddr : BfTypedValueKind_ThisValue);
  10124. // }
  10125. // }
  10126. //
  10127. // checkMethodState = checkMethodState->mPrevMethodState;
  10128. // }
  10129. // }
  10130. // Check mixin state for 'this'
  10131. {
  10132. auto checkMethodState = useMethodState;
  10133. while (checkMethodState != NULL)
  10134. {
  10135. if (checkMethodState->mMixinState != NULL)
  10136. {
  10137. BfTypedValue thisValue = checkMethodState->mMixinState->mTarget;
  10138. if (thisValue)
  10139. {
  10140. checkMethodState->mMixinState->mLastTargetAccessId = useMethodState->GetRootMethodState()->mCurAccessId++;
  10141. if (!thisValue.mType->IsValueType())
  10142. thisValue = LoadValue(thisValue);
  10143. return thisValue;
  10144. }
  10145. }
  10146. checkMethodState = checkMethodState->mPrevMethodState;
  10147. }
  10148. }
  10149. auto curMethodInstance = mCurMethodInstance;
  10150. if (useMethodState->mMethodInstance != NULL)
  10151. curMethodInstance = useMethodState->mMethodInstance;
  10152. if ((curMethodInstance == NULL) /*|| (!mCurMethodInstance->mIRFunction)*/ || (curMethodInstance->mMethodDef->mIsStatic))
  10153. {
  10154. if ((useMethodState->mClosureState != NULL) && (!useMethodState->mClosureState->mConstLocals.empty()))
  10155. {
  10156. auto& constLocal = useMethodState->mClosureState->mConstLocals[0];
  10157. if (constLocal.mIsThis)
  10158. {
  10159. BF_ASSERT(constLocal.mResolvedType->IsValuelessType());
  10160. return BfTypedValue(mBfIRBuilder->GetFakeVal(), constLocal.mResolvedType);
  10161. }
  10162. }
  10163. return BfTypedValue();
  10164. }
  10165. bool preferValue = !IsTargetingBeefBackend();
  10166. if (useMethodState->mLocals.IsEmpty())
  10167. {
  10168. // 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
  10169. BF_ASSERT(useMethodState->mPrevMethodState != NULL);
  10170. return BfTypedValue();
  10171. }
  10172. auto thisLocal = useMethodState->mLocals[0];
  10173. BF_ASSERT(thisLocal->mIsThis);
  10174. BfIRValue thisValue;
  10175. if ((preferValue) || (!thisLocal->mAddr) /*|| (thisLocal->mIsSplat)*/)
  10176. thisValue = thisLocal->mValue;
  10177. else if ((thisLocal->mIsSplat) || (thisLocal->mIsLowered))
  10178. thisValue = thisLocal->mAddr;
  10179. else
  10180. thisValue = mBfIRBuilder->CreateLoad(thisLocal->mAddr);
  10181. useMethodState->mLocals[0]->mReadFromId = useMethodState->GetRootMethodState()->mCurAccessId++;
  10182. if (useMethodState->mClosureState != NULL)
  10183. {
  10184. auto closureTypeInst = useMethodState->mClosureState->mClosureType;
  10185. if (closureTypeInst != NULL)
  10186. {
  10187. if (closureTypeInst->mFieldInstances.size() > 0)
  10188. {
  10189. auto& field = closureTypeInst->mFieldInstances[0];
  10190. auto fieldDef = field.GetFieldDef();
  10191. if (fieldDef->mName == "__this")
  10192. {
  10193. if (mCurMethodState->mClosureState->mCapturing)
  10194. mCurMethodState->mClosureState->mReferencedOuterClosureMembers.Add(&field);
  10195. // This is a captured 'this'
  10196. BfTypedValue result = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(thisValue, 0, field.mDataIdx), field.mResolvedType, true);
  10197. if (field.mResolvedType->IsRef())
  10198. {
  10199. auto refType = (BfRefType*)field.mResolvedType;
  10200. auto underlyingType = refType->GetUnderlyingType();
  10201. result = BfTypedValue(mBfIRBuilder->CreateLoad(result.mValue), underlyingType, true);
  10202. }
  10203. if (field.mResolvedType->IsObject())
  10204. {
  10205. result = LoadValue(result);
  10206. result.mKind = BfTypedValueKind_ThisValue;
  10207. }
  10208. else
  10209. {
  10210. if (fieldDef->mIsReadOnly)
  10211. result.mKind = BfTypedValueKind_ReadOnlyThisAddr;
  10212. else
  10213. result.mKind = BfTypedValueKind_ThisAddr;
  10214. }
  10215. return result;
  10216. }
  10217. }
  10218. return BfTypedValue();
  10219. }
  10220. if (useMethodState->mClosureState->mCapturing)
  10221. {
  10222. auto thisType = useMethodState->mLocals[0]->mResolvedType;
  10223. if (thisType->IsValueType())
  10224. return BfTypedValue(CreateAlloca(thisType), thisType, BfTypedValueKind_ThisAddr);
  10225. else
  10226. return BfTypedValue(GetDefaultValue(thisType), thisType, BfTypedValueKind_ThisValue);
  10227. }
  10228. }
  10229. auto localDef = useMethodState->mLocals[0];
  10230. auto curMethodOwner = mCurMethodInstance->mMethodInstanceGroup->mOwner;
  10231. if ((curMethodOwner->IsStruct()) || (curMethodOwner->IsTypedPrimitive()))
  10232. {
  10233. if ((localDef->mResolvedType->IsTypedPrimitive()) && (!mCurMethodInstance->mMethodDef->mIsMutating))
  10234. {
  10235. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, BfTypedValueKind_ReadOnlyThisValue);
  10236. }
  10237. if (localDef->mIsSplat)
  10238. {
  10239. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, BfTypedValueKind_ThisSplatHead);
  10240. }
  10241. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, localDef->mIsReadOnly ? BfTypedValueKind_ReadOnlyThisAddr : BfTypedValueKind_ThisAddr);
  10242. }
  10243. return BfTypedValue(thisValue, mCurMethodInstance->mMethodInstanceGroup->mOwner, BfTypedValueKind_ThisValue);
  10244. }
  10245. BfLocalVariable* BfModule::GetThisVariable()
  10246. {
  10247. if (mCurMethodState == NULL)
  10248. return NULL;
  10249. auto methodState = mCurMethodState->GetNonCaptureState();
  10250. if ((methodState->mLocals.size() > 0) && (methodState->mLocals[0]->mIsThis))
  10251. return methodState->mLocals[0];
  10252. return NULL;
  10253. }
  10254. bool BfModule::IsInGeneric()
  10255. {
  10256. return (mCurMethodInstance->GetNumGenericArguments() != 0) || (mCurTypeInstance->IsGenericTypeInstance());
  10257. }
  10258. bool BfModule::IsInSpecializedGeneric()
  10259. {
  10260. if ((mCurMethodInstance == NULL) || (mCurMethodInstance->mIsUnspecialized))
  10261. return false;
  10262. return (mCurMethodInstance->GetNumGenericArguments() != 0) || (mCurTypeInstance->IsGenericTypeInstance());
  10263. }
  10264. bool BfModule::IsInSpecializedSection()
  10265. {
  10266. return IsInSpecializedGeneric() ||
  10267. ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL));
  10268. }
  10269. bool BfModule::IsInUnspecializedGeneric()
  10270. {
  10271. if (mCurMethodInstance != NULL)
  10272. return mCurMethodInstance->mIsUnspecialized;
  10273. return false;
  10274. }
  10275. //////////////////////////////////////////////////////////////////////////
  10276. BfIRValue BfModule::AllocLocalVariable(BfType* type, const StringImpl& name, bool doLifetimeEnd)
  10277. {
  10278. //if ((type->IsValuelessType()) || (type->IsMethodRef()))
  10279. if (type->IsValuelessType())
  10280. return mBfIRBuilder->GetFakeVal();
  10281. auto allocaInst = CreateAlloca(type, doLifetimeEnd, name.c_str());
  10282. if ((!doLifetimeEnd) && (WantsLifetimes()))
  10283. {
  10284. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  10285. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  10286. }
  10287. bool initLocalVariables = mCompiler->mOptions.mInitLocalVariables;
  10288. auto typeOptions = GetTypeOptions();
  10289. if (typeOptions != NULL)
  10290. initLocalVariables = BfTypeOptions::Apply(initLocalVariables, typeOptions->mInitLocalVariables);
  10291. // Local variable inits are implicitly handled in the Beef Backend
  10292. if ((initLocalVariables) && (!IsTargetingBeefBackend()))
  10293. {
  10294. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  10295. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  10296. auto storeInst = mBfIRBuilder->CreateAlignedStore(GetDefaultValue(type), allocaInst, type->mAlign);
  10297. mBfIRBuilder->ClearDebugLocation(storeInst);
  10298. mBfIRBuilder->SetInsertPoint(prevBlock);
  10299. }
  10300. return allocaInst;
  10301. }
  10302. void BfModule::DoAddLocalVariable(BfLocalVariable* localVar)
  10303. {
  10304. if (localVar->mResolvedType->IsVar())
  10305. {
  10306. BF_ASSERT((mCurMethodInstance->mIsUnspecialized) || (mCurMethodState->mClosureState != NULL) || (mHadVarUsage));
  10307. }
  10308. localVar->mLocalVarIdx = (int)mCurMethodState->mLocals.size();
  10309. mCurMethodState->mLocals.push_back(localVar);
  10310. BfLocalVarEntry* localVarEntryPtr;
  10311. if (!mCurMethodState->mLocalVarSet.TryAdd(BfLocalVarEntry(localVar), &localVarEntryPtr))
  10312. {
  10313. localVar->mShadowedLocal = localVarEntryPtr->mLocalVar;
  10314. localVarEntryPtr->mLocalVar = localVar;
  10315. }
  10316. }
  10317. BfLocalVariable* BfModule::AddLocalVariableDef(BfLocalVariable* localVarDef, bool addDebugInfo, bool doAliasValue, BfIRValue declareBefore, BfIRInitType initType)
  10318. {
  10319. if ((localVarDef->mValue) && (!localVarDef->mAddr) && (IsTargetingBeefBackend()))
  10320. {
  10321. if ((!localVarDef->mValue.IsConst()) && (!localVarDef->mValue.IsArg()) && (!localVarDef->mValue.IsFake()))
  10322. {
  10323. mBfIRBuilder->CreateValueScopeRetain(localVarDef->mValue);
  10324. mCurMethodState->mCurScope->mHadScopeValueRetain = true;
  10325. }
  10326. }
  10327. if ((addDebugInfo) && (mBfIRBuilder->DbgHasInfo()) &&
  10328. ((mCurMethodInstance == NULL) || (!mCurMethodInstance->mIsUnspecialized)) &&
  10329. (mHasFullDebugInfo) &&
  10330. ((mCurMethodState->mClosureState == NULL) || (!mCurMethodState->mClosureState->mCapturing)))
  10331. {
  10332. auto varType = localVarDef->mResolvedType;
  10333. if (localVarDef->mResolvedType->IsValuelessType())
  10334. {
  10335. }
  10336. else
  10337. {
  10338. bool isByAddr = false;
  10339. auto diValue = localVarDef->mValue;
  10340. if (localVarDef->mConstValue)
  10341. diValue = localVarDef->mConstValue;
  10342. else if (localVarDef->mAddr)
  10343. {
  10344. diValue = localVarDef->mAddr;
  10345. isByAddr = true;
  10346. }
  10347. auto diType = mBfIRBuilder->DbgGetType(localVarDef->mResolvedType);
  10348. bool didConstToMem = false;
  10349. bool isConstant = false;
  10350. if ((localVarDef->mIsReadOnly) && (localVarDef->mAddr))
  10351. diType = mBfIRBuilder->DbgCreateConstType(diType);
  10352. else if (localVarDef->mConstValue)
  10353. {
  10354. auto constant = mBfIRBuilder->GetConstant(localVarDef->mConstValue);
  10355. isConstant =
  10356. (constant->mConstType < BfConstType_GlobalVar) ||
  10357. (constant->mConstType == BfConstType_AggZero) ||
  10358. (constant->mConstType == BfConstType_Array);
  10359. if (isConstant)
  10360. {
  10361. if (localVarDef->mResolvedType->IsComposite())
  10362. {
  10363. mBfIRBuilder->PopulateType(localVarDef->mResolvedType);
  10364. auto constMem = mBfIRBuilder->ConstToMemory(localVarDef->mConstValue);
  10365. if (IsTargetingBeefBackend())
  10366. {
  10367. diValue = mBfIRBuilder->CreateAliasValue(constMem);
  10368. didConstToMem = true;
  10369. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  10370. }
  10371. else
  10372. {
  10373. isByAddr = true;
  10374. mBfIRBuilder->SaveDebugLocation();
  10375. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  10376. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  10377. mBfIRBuilder->ClearDebugLocation();
  10378. auto ptrType = CreatePointerType(localVarDef->mResolvedType);
  10379. auto addrVal = CreateAlloca(ptrType);
  10380. mBfIRBuilder->CreateStore(constMem, addrVal);
  10381. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  10382. diValue = addrVal;
  10383. didConstToMem = true;
  10384. mBfIRBuilder->SetInsertPoint(prevBlock);
  10385. mBfIRBuilder->RestoreDebugLocation();
  10386. }
  10387. }
  10388. if (mCompiler->mOptions.IsCodeView())
  10389. diType = mBfIRBuilder->DbgCreateConstType(diType);
  10390. }
  10391. }
  10392. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  10393. localVarDef->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, initType);
  10394. localVarDef->mDbgVarInst = diVariable;
  10395. if (mBfIRBuilder->HasDebugLocation())
  10396. {
  10397. if ((isConstant) && (!didConstToMem))
  10398. {
  10399. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(localVarDef->mConstValue, diVariable);
  10400. }
  10401. else
  10402. {
  10403. if ((IsTargetingBeefBackend()) && (doAliasValue))
  10404. {
  10405. diValue = mBfIRBuilder->CreateAliasValue(diValue);
  10406. mCurMethodState->mCurScope->mDeferredLifetimeEnds.Add(diValue);
  10407. }
  10408. if (isByAddr)
  10409. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertDeclare(diValue, diVariable, declareBefore);
  10410. else if (diValue)
  10411. {
  10412. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(diValue, diVariable);
  10413. }
  10414. else if (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU) // DWARF chokes on this:
  10415. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  10416. }
  10417. }
  10418. }
  10419. }
  10420. localVarDef->mDeclBlock = mBfIRBuilder->GetInsertBlock();
  10421. DoAddLocalVariable(localVarDef);
  10422. auto rootMethodState = mCurMethodState->GetRootMethodState();
  10423. if (localVarDef->mLocalVarId == -1)
  10424. {
  10425. BF_ASSERT(rootMethodState->mCurLocalVarId >= 0);
  10426. localVarDef->mLocalVarId = rootMethodState->mCurLocalVarId++;
  10427. }
  10428. if ((localVarDef->mNameNode != NULL) && (mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  10429. mCompiler->mResolvePassData->mAutoComplete->CheckLocalDef(localVarDef->mNameNode, localVarDef);
  10430. if ((localVarDef->mNameNode != NULL) && (mCurMethodInstance != NULL))
  10431. {
  10432. bool isClosureProcessing = (mCurMethodState->mClosureState != NULL) && (!mCurMethodState->mClosureState->mCapturing);
  10433. if ((!isClosureProcessing) && (mCompiler->mResolvePassData != NULL) && (localVarDef->mNameNode != NULL))
  10434. mCompiler->mResolvePassData->HandleLocalReference(localVarDef->mNameNode, rootMethodState->mMethodInstance->GetOwner()->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, localVarDef->mLocalVarId);
  10435. }
  10436. return localVarDef;
  10437. }
  10438. void BfModule::CreateDIRetVal()
  10439. {
  10440. if (!WantsDebugInfo())
  10441. return;
  10442. /*if (!mCurMethodState->mRetVal)
  10443. {
  10444. if (mCurMethodInstance->mMethodDef->mName != "Ziggle")
  10445. return;
  10446. }*/
  10447. if ((mCurMethodState->mRetVal) || (mCurMethodState->mRetValAddr))
  10448. {
  10449. BF_ASSERT((!mBfIRBuilder->mIgnoreWrites) || (mHadVarUsage));
  10450. BfType* dbgType = mCurMethodInstance->mReturnType;
  10451. BfIRValue dbgValue = mCurMethodState->mRetVal.mValue;
  10452. if (mCurMethodInstance->HasStructRet())
  10453. {
  10454. BF_ASSERT(mCurMethodState->mRetValAddr);
  10455. dbgType = CreatePointerType(dbgType);
  10456. dbgValue = mCurMethodState->mRetValAddr;
  10457. }
  10458. else
  10459. {
  10460. BF_ASSERT(!mCurMethodState->mRetValAddr);
  10461. }
  10462. mCurMethodState->mDIRetVal = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  10463. "__return", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(dbgType));
  10464. auto declareCall = mBfIRBuilder->DbgInsertDeclare(dbgValue, mCurMethodState->mDIRetVal);
  10465. }
  10466. }
  10467. void BfModule::CheckVariableDef(BfLocalVariable* variableDef)
  10468. {
  10469. BfLocalVarEntry* localVarEntryPtr = NULL;
  10470. if ((mCurMethodState != NULL) && (mCurMethodState->mLocalVarSet.TryGet(BfLocalVarEntry(variableDef), &localVarEntryPtr)))
  10471. {
  10472. auto checkLocal = localVarEntryPtr->mLocalVar;
  10473. if ((checkLocal->mLocalVarIdx >= mCurMethodState->GetLocalStartIdx()) && (!checkLocal->mIsShadow))
  10474. {
  10475. BfError* error;
  10476. if (checkLocal->mIsImplicitParam)
  10477. return; // Ignore 'redefinition'
  10478. if (checkLocal->IsParam())
  10479. error = Fail(StrFormat("A parameter named '%s' has already been declared.", variableDef->mName.c_str()), variableDef->mNameNode);
  10480. else if (checkLocal->mLocalVarIdx < mCurMethodState->mCurScope->mLocalVarStart)
  10481. error = Fail(StrFormat("A variable named '%s' has already been declared in this parent's scope.", variableDef->mName.c_str()), variableDef->mNameNode);
  10482. else
  10483. error = Fail(StrFormat("A variable named '%s' has already been declared in this scope.", variableDef->mName.c_str()), variableDef->mNameNode);
  10484. if ((checkLocal->mNameNode != NULL) && (error != NULL))
  10485. mCompiler->mPassInstance->MoreInfo("Previous declaration", checkLocal->mNameNode);
  10486. return;
  10487. }
  10488. }
  10489. }
  10490. BfScopeData* BfModule::FindScope(BfAstNode* scopeName, BfMixinState* fromMixinState, bool allowAcrossDeferredBlock)
  10491. {
  10492. bool inMixinDecl = (mCurMethodInstance != NULL) && (mCurMethodInstance->IsMixin());
  10493. if (auto tokenNode = BfNodeDynCast<BfTokenNode>(scopeName))
  10494. {
  10495. if (tokenNode->GetToken() == BfToken_Colon)
  10496. {
  10497. if ((!allowAcrossDeferredBlock) && (mCurMethodState->mInDeferredBlock))
  10498. {
  10499. Fail("Cannot access method scope across deferred block boundary", scopeName);
  10500. return NULL;
  10501. }
  10502. return &mCurMethodState->mHeadScope;
  10503. }
  10504. else if (tokenNode->GetToken() == BfToken_Mixin)
  10505. {
  10506. if (fromMixinState == NULL)
  10507. {
  10508. if (mCurMethodInstance->mMethodDef->mMethodType != BfMethodType_Mixin)
  10509. Fail("'mixin' scope specifier can only be used within a mixin declaration", scopeName);
  10510. return mCurMethodState->mCurScope;
  10511. }
  10512. fromMixinState->mUsedInvocationScope = true;
  10513. return fromMixinState->mTargetScope;
  10514. }
  10515. else if (tokenNode->GetToken() == BfToken_New)
  10516. return NULL;
  10517. }
  10518. if (auto identifier = BfNodeDynCast<BfIdentifierNode>(scopeName))
  10519. {
  10520. auto findLabel = scopeName->ToString();
  10521. bool crossedDeferredBlock = false;
  10522. auto checkScope = mCurMethodState->mCurScope;
  10523. while (checkScope != NULL)
  10524. {
  10525. if (checkScope->mIsDeferredBlock)
  10526. crossedDeferredBlock = true;
  10527. if (checkScope->mLabel == findLabel)
  10528. {
  10529. if ((crossedDeferredBlock) && (!allowAcrossDeferredBlock))
  10530. {
  10531. Fail(StrFormat("Cannot access scope '%s' across deferred block boundary", findLabel.c_str()), scopeName);
  10532. return NULL;
  10533. }
  10534. return checkScope;
  10535. }
  10536. checkScope = checkScope->mPrevScope;
  10537. }
  10538. if (!inMixinDecl)
  10539. Fail(StrFormat("Unable to locate label '%s'", findLabel.c_str()), scopeName);
  10540. }
  10541. if (auto scopeNode = BfNodeDynCast<BfScopeNode>(scopeName))
  10542. {
  10543. return FindScope(scopeNode->mTargetNode, allowAcrossDeferredBlock);
  10544. }
  10545. return mCurMethodState->mCurScope;
  10546. }
  10547. BfScopeData* BfModule::FindScope(BfAstNode* scopeName, bool allowAcrossDeferredBlock)
  10548. {
  10549. return FindScope(scopeName, mCurMethodState->mMixinState, allowAcrossDeferredBlock);
  10550. }
  10551. BfBreakData* BfModule::FindBreakData(BfAstNode* scopeName)
  10552. {
  10553. auto scopeData = FindScope(scopeName, false);
  10554. if (scopeData == NULL)
  10555. return NULL;
  10556. int scopeDepth = scopeData->GetDepth();
  10557. // Find the first break data that is at or below the depth of our requested scope
  10558. auto breakData = mCurMethodState->mBreakData;
  10559. while ((breakData != NULL) && (scopeDepth < breakData->mScope->GetDepth()))
  10560. {
  10561. if (breakData->mScope->mIsConditional)
  10562. return NULL;
  10563. breakData = breakData->mPrevBreakData;
  10564. }
  10565. return breakData;
  10566. }
  10567. void BfModule::EmitLifetimeEnds(BfScopeData* scopeData)
  10568. {
  10569. // LLVM is stricter about the placement of these (ie: they can't occur after a 'ret')
  10570. if (!IsTargetingBeefBackend())
  10571. return;
  10572. for (auto lifetimeEnd : scopeData->mDeferredLifetimeEnds)
  10573. {
  10574. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  10575. }
  10576. }
  10577. void BfModule::ClearLifetimeEnds()
  10578. {
  10579. auto scopeData = mCurMethodState->mCurScope;
  10580. while (scopeData != NULL)
  10581. {
  10582. scopeData->mDeferredLifetimeEnds.Clear();
  10583. scopeData = scopeData->mPrevScope;
  10584. }
  10585. }
  10586. bool BfModule::WantsDebugInfo()
  10587. {
  10588. if ((mCurMethodInstance != NULL) &&
  10589. ((mCurMethodInstance->mIsUnspecialized) || (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)))
  10590. return false;
  10591. return (mBfIRBuilder->DbgHasInfo()) && (mHasFullDebugInfo) &&
  10592. ((mCurMethodState == NULL) || (mCurMethodState->mClosureState == NULL) || (!mCurMethodState->mClosureState->mCapturing));
  10593. }
  10594. BfTypeOptions* BfModule::GetTypeOptions()
  10595. {
  10596. if ((mCurMethodState != NULL) && (mCurMethodState->mMethodTypeOptions != NULL))
  10597. return mCurMethodState->mMethodTypeOptions;
  10598. return mSystem->GetTypeOptions(mCurTypeInstance->mTypeOptionsIdx);
  10599. }
  10600. bool BfModule::HasDeferredScopeCalls(BfScopeData* scope)
  10601. {
  10602. BfScopeData* checkScope = mCurMethodState->mCurScope;
  10603. while (checkScope != NULL)
  10604. {
  10605. if ((!checkScope->mDeferredCallEntries.IsEmpty()) || (!checkScope->mDeferredLifetimeEnds.empty()))
  10606. return true;
  10607. if (checkScope == scope)
  10608. break;
  10609. checkScope = checkScope->mPrevScope;
  10610. }
  10611. return false;
  10612. }
  10613. void BfModule::EmitDeferredScopeCalls(bool useSrcPositions, BfScopeData* scopeData, BfIRBlock doneBlock)
  10614. {
  10615. // Is there anything we need to do here?
  10616. if (mBfIRBuilder->mIgnoreWrites)
  10617. {
  10618. // Just visit deferred blocks
  10619. BfScopeData* checkScope = mCurMethodState->mCurScope;
  10620. while (checkScope != NULL)
  10621. {
  10622. BfDeferredCallEntry* deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  10623. while (deferredCallEntry != NULL)
  10624. {
  10625. if (deferredCallEntry->mDeferredBlock != NULL)
  10626. {
  10627. VisitEmbeddedStatement(deferredCallEntry->mDeferredBlock, NULL, BfEmbeddedStatementFlags_IsDeferredBlock);
  10628. }
  10629. deferredCallEntry = deferredCallEntry->mNext;
  10630. }
  10631. if (checkScope == scopeData)
  10632. break;
  10633. checkScope = checkScope->mPrevScope;
  10634. }
  10635. return;
  10636. }
  10637. // Why did we want to do SetIllegalSrcPos here?
  10638. // Don't we always want to step onto these instances?
  10639. // Find a case where we don't and perhaps only do it there.
  10640. // The downside was that 'EmitEnsureInstructionAt' on the end of block statements causes
  10641. // a (seemingly) unneeded NOP when we do SetIllegalSrcPos
  10642. //SetIllegalSrcPos();
  10643. bool setSrcPos = false;
  10644. bool wantsNop = true;
  10645. BfAstNode* deferCloseNode = NULL;
  10646. if (mCurMethodState->mInPostReturn)
  10647. {
  10648. // These won't get used, they are post-return
  10649. return;
  10650. }
  10651. SizedArray<BfIRValue, 8> deferredLifetimeEnds;
  10652. BfScopeData* scopeJumpBlock = NULL;
  10653. bool hadExtraDeferredLifetimeEnds = false;
  10654. auto _FlushLifetimeEnds = [&]()
  10655. {
  10656. for (auto lifetimeEnd : deferredLifetimeEnds)
  10657. {
  10658. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  10659. mBfIRBuilder->ClearDebugLocation_Last();
  10660. }
  10661. deferredLifetimeEnds.clear();
  10662. };
  10663. BfScopeData* checkScope = mCurMethodState->mCurScope;
  10664. while (checkScope != NULL)
  10665. {
  10666. if (checkScope->mCloseNode != NULL)
  10667. deferCloseNode = checkScope->mCloseNode;
  10668. if (doneBlock)
  10669. {
  10670. // Try to find a match where we've already emitted these calls and then jumped to the correct block
  10671. for (auto& checkHandler : checkScope->mDeferredHandlers)
  10672. {
  10673. if (checkHandler.mDoneBlock == doneBlock)
  10674. {
  10675. scopeJumpBlock = checkScope;
  10676. mBfIRBuilder->CreateBr(checkHandler.mHandlerBlock);
  10677. mBfIRBuilder->ClearDebugLocation_Last();
  10678. _FlushLifetimeEnds();
  10679. break;
  10680. }
  10681. }
  10682. if (scopeJumpBlock != NULL)
  10683. break;
  10684. }
  10685. bool hasWork = (checkScope->mSavedStack) || (checkScope->mDeferredCallEntries.mHead != NULL);
  10686. if (checkScope != scopeData) // Only emit a block for deferred lifetimes if we're going back beyond this entry
  10687. hasWork |= (!deferredLifetimeEnds.IsEmpty());
  10688. if (hasWork)
  10689. {
  10690. SetAndRestoreValue<BfScopeData*> prevScope(mCurMethodState->mCurScope, checkScope);
  10691. if (deferCloseNode != NULL)
  10692. {
  10693. UpdateSrcPos(deferCloseNode);
  10694. }
  10695. if (doneBlock)
  10696. {
  10697. bool crossingMixin = mCurMethodState->mCurScope->mMixinDepth != checkScope->mMixinDepth;
  10698. String blockName = "deferredCalls";
  10699. //blockName += StrFormat("_%d", mBfIRBuilder->mBlockCount);
  10700. BfDeferredHandler deferredHandler;
  10701. if ((!crossingMixin) && (deferredLifetimeEnds.IsEmpty()))
  10702. {
  10703. mBfIRBuilder->SaveDebugLocation();
  10704. mBfIRBuilder->ClearDebugLocation();
  10705. deferredHandler.mHandlerBlock = mBfIRBuilder->MaybeChainNewBlock(blockName);
  10706. mBfIRBuilder->RestoreDebugLocation();
  10707. }
  10708. else
  10709. {
  10710. // Definitely chain
  10711. deferredHandler.mHandlerBlock = mBfIRBuilder->CreateBlock(blockName);
  10712. mBfIRBuilder->CreateBr(deferredHandler.mHandlerBlock);
  10713. mBfIRBuilder->ClearDebugLocation_Last();
  10714. _FlushLifetimeEnds();
  10715. mBfIRBuilder->AddBlock(deferredHandler.mHandlerBlock);
  10716. mBfIRBuilder->SetInsertPoint(deferredHandler.mHandlerBlock);
  10717. }
  10718. deferredHandler.mDoneBlock = doneBlock;
  10719. if (!mBfIRBuilder->mIgnoreWrites)
  10720. checkScope->mDeferredHandlers.push_back(deferredHandler);
  10721. if (checkScope == &mCurMethodState->mHeadScope)
  10722. {
  10723. if (!mCurMethodState->mDIRetVal)
  10724. {
  10725. // 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
  10726. // be scoped to the physical method
  10727. /*if (deferCloseNode != NULL)
  10728. {
  10729. UpdateSrcPos(deferCloseNode);
  10730. }*/
  10731. CreateDIRetVal();
  10732. }
  10733. }
  10734. if (checkScope != mCurMethodState->mTailScope)
  10735. {
  10736. if (deferredHandler.mHandlerBlock.IsFake())
  10737. {
  10738. BF_ASSERT(mBfIRBuilder->mIgnoreWrites);
  10739. }
  10740. if (!mBfIRBuilder->mIgnoreWrites)
  10741. checkScope->mAtEndBlocks.push_back(deferredHandler.mHandlerBlock);
  10742. }
  10743. }
  10744. std::unordered_set<BfDeferredCallEntry*> handledSet;
  10745. BfDeferredCallEntry* deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  10746. while (deferredCallEntry != NULL)
  10747. {
  10748. BfDeferredCallEmitState deferredCallEmitState;
  10749. deferredCallEmitState.mCloseNode = deferCloseNode;
  10750. SetAndRestoreValue<BfDeferredCallEmitState*> prevDeferredCallEmitState(mCurMethodState->mDeferredCallEmitState, &deferredCallEmitState);
  10751. SetAndRestoreValue<bool> prevIgnoredWrites(mBfIRBuilder->mIgnoreWrites, deferredCallEntry->mIgnored);
  10752. if (deferCloseNode != NULL)
  10753. {
  10754. UpdateSrcPos(deferCloseNode);
  10755. }
  10756. if (wantsNop)
  10757. EmitEnsureInstructionAt();
  10758. wantsNop = false;
  10759. if (deferredCallEntry->mDeferredBlock != NULL)
  10760. {
  10761. auto itr = handledSet.insert(deferredCallEntry);
  10762. if (!itr.second)
  10763. {
  10764. // Already handled, can happen if we defer again within the block
  10765. deferredCallEntry = deferredCallEntry->mNext;
  10766. continue;
  10767. }
  10768. auto prevHead = checkScope->mDeferredCallEntries.mHead;
  10769. EmitDeferredCall(*deferredCallEntry);
  10770. if (prevHead != checkScope->mDeferredCallEntries.mHead)
  10771. {
  10772. // The list changed, start over and ignore anything we've already handled
  10773. deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  10774. }
  10775. else
  10776. deferredCallEntry = deferredCallEntry->mNext;
  10777. }
  10778. else
  10779. {
  10780. EmitDeferredCall(*deferredCallEntry);
  10781. deferredCallEntry = deferredCallEntry->mNext;
  10782. }
  10783. }
  10784. if (checkScope->mSavedStack)
  10785. {
  10786. checkScope->mSavedStackUses.Add(mBfIRBuilder->CreateStackRestore(checkScope->mSavedStack));
  10787. if (mCurMethodState->mDynStackRevIdx)
  10788. {
  10789. auto curValue = mBfIRBuilder->CreateLoad(mCurMethodState->mDynStackRevIdx);
  10790. auto newValue = mBfIRBuilder->CreateAdd(curValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  10791. mBfIRBuilder->CreateStore(newValue, mCurMethodState->mDynStackRevIdx);
  10792. }
  10793. }
  10794. }
  10795. if (!checkScope->mIsScopeHead)
  10796. {
  10797. // We manually emit function-level lifetime ends after the 'ret' in ProcessMethod
  10798. if (!IsTargetingBeefBackend())
  10799. {
  10800. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  10801. {
  10802. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  10803. }
  10804. }
  10805. else
  10806. {
  10807. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  10808. {
  10809. deferredLifetimeEnds.Add(lifetimeEnd);
  10810. }
  10811. }
  10812. }
  10813. if (checkScope == scopeData)
  10814. break;
  10815. checkScope = checkScope->mPrevScope;
  10816. }
  10817. if ((doneBlock) && (scopeJumpBlock == NULL))
  10818. {
  10819. mBfIRBuilder->CreateBr(doneBlock);
  10820. mBfIRBuilder->ClearDebugLocation_Last();
  10821. }
  10822. // Keeping CreateLifetimeEnds until the end messes up when we chain to old mDeferredHandlers that
  10823. // may have been created when other scope lifetimes were available
  10824. _FlushLifetimeEnds();
  10825. // Emit lifetimeEnds after the branch for Beef
  10826. /*if (IsTargetingBeefBackend())
  10827. {
  10828. bool needsEnsureInst = (!doneBlock) && (scopeJumpBlock == NULL);
  10829. BfScopeData* checkScope = mCurMethodState->mCurScope;
  10830. while (checkScope != NULL)
  10831. {
  10832. if (checkScope == scopeJumpBlock)
  10833. break;
  10834. if (!checkScope->mIsScopeHead)
  10835. {
  10836. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  10837. {
  10838. if (needsEnsureInst)
  10839. {
  10840. needsEnsureInst = false;
  10841. }
  10842. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  10843. }
  10844. }
  10845. if (checkScope == scopeData)
  10846. break;
  10847. checkScope = checkScope->mPrevScope;
  10848. }
  10849. }*/
  10850. }
  10851. void BfModule::MarkScopeLeft(BfScopeData* scopeData)
  10852. {
  10853. if (mCurMethodState->mDeferredLocalAssignData != NULL)
  10854. {
  10855. auto deferredLocalAssignData = mCurMethodState->mDeferredLocalAssignData;
  10856. while (deferredLocalAssignData != NULL)
  10857. {
  10858. if ((deferredLocalAssignData->mScopeData == NULL) || (deferredLocalAssignData->mScopeData->mScopeDepth < scopeData->mScopeDepth))
  10859. break;
  10860. if ((deferredLocalAssignData->mScopeData != NULL) && (deferredLocalAssignData->mScopeData->mScopeDepth == scopeData->mScopeDepth))
  10861. deferredLocalAssignData->mIsUnconditional = false;
  10862. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  10863. }
  10864. }
  10865. //for (int localIdx = scopeData->mLocalVarStart; localIdx < (int)mCurMethodState->mLocals.size(); localIdx++)
  10866. // We mark all unassigned variables as assigned now, for avoiding "may be unassigned" usage cases like:
  10867. // int b;
  10868. // if (cond) return;
  10869. // else b = 1;
  10870. // Use(b);
  10871. for (int localIdx = 0; localIdx < (int)mCurMethodState->mLocals.size(); localIdx++)
  10872. {
  10873. auto localDef = mCurMethodState->mLocals[localIdx];
  10874. if ((!localDef->mIsAssigned) && (!localDef->IsParam()))
  10875. mCurMethodState->LocalDefined(localDef);
  10876. }
  10877. }
  10878. void BfModule::CreateReturn(BfIRValue val)
  10879. {
  10880. if (mCurMethodInstance->mReturnType->IsComposite())
  10881. {
  10882. // Store to sret
  10883. BF_ASSERT(val);
  10884. mBfIRBuilder->CreateStore(val, mBfIRBuilder->GetArgument(0));
  10885. mBfIRBuilder->CreateRetVoid();
  10886. }
  10887. else
  10888. {
  10889. if (mCurMethodInstance->mReturnType->IsValuelessType())
  10890. {
  10891. mBfIRBuilder->CreateRetVoid();
  10892. }
  10893. else
  10894. {
  10895. BF_ASSERT(val);
  10896. mBfIRBuilder->CreateRet(val);
  10897. }
  10898. }
  10899. }
  10900. void BfModule::EmitReturn(BfIRValue val)
  10901. {
  10902. if (mCurMethodState->mIRExitBlock)
  10903. {
  10904. if (!mCurMethodInstance->mReturnType->IsValuelessType())
  10905. {
  10906. if (val) // We allow for val to be empty if we know we've already written the value to mRetVal
  10907. {
  10908. BfIRValue retVal = mCurMethodState->mRetVal.mValue;
  10909. if (!mCurMethodState->mRetVal)
  10910. retVal = mBfIRBuilder->CreateLoad(mCurMethodState->mRetValAddr);
  10911. mBfIRBuilder->CreateStore(val, retVal);
  10912. }
  10913. }
  10914. EmitDeferredScopeCalls(true, NULL, mCurMethodState->mIRExitBlock);
  10915. }
  10916. else
  10917. {
  10918. EmitDeferredScopeCalls(false, NULL);
  10919. if (mCurMethodInstance->mReturnType->IsValuelessType())
  10920. mBfIRBuilder->CreateRetVoid();
  10921. else
  10922. mBfIRBuilder->CreateRet(val);
  10923. }
  10924. mCurMethodState->SetHadReturn(true);
  10925. mCurMethodState->mLeftBlockUncond = true;
  10926. }
  10927. void BfModule::EmitDefaultReturn()
  10928. {
  10929. if (mCurMethodState->mInDeferredBlock)
  10930. return;
  10931. if (mCurMethodState->mIRExitBlock)
  10932. {
  10933. EmitDeferredScopeCalls(true, NULL, mCurMethodState->mIRExitBlock);
  10934. }
  10935. else
  10936. {
  10937. if (mCurMethodInstance->mReturnType->IsVoid())
  10938. mBfIRBuilder->CreateRetVoid();
  10939. else
  10940. mBfIRBuilder->CreateRet(GetDefaultValue(mCurMethodInstance->mReturnType));
  10941. }
  10942. mCurMethodState->SetHadReturn(true);
  10943. mCurMethodState->mLeftBlockUncond = true;
  10944. }
  10945. void BfModule::AssertErrorState()
  10946. {
  10947. if (mIgnoreErrors)
  10948. return;
  10949. if (mHadBuildError)
  10950. return;
  10951. if (mCurTypeInstance != NULL)
  10952. {
  10953. if (mCurTypeInstance->IsUnspecializedTypeVariation())
  10954. return;
  10955. }
  10956. if (mCurMethodInstance != NULL)
  10957. {
  10958. if (mCurMethodInstance->mIsUnspecializedVariation)
  10959. return;
  10960. }
  10961. // We want the module to be marked as failed even if it's just an error in the parser
  10962. if (mCurMethodInstance != NULL)
  10963. mCurMethodInstance->mHasFailed = true;
  10964. mHadBuildError = true;
  10965. // We check for either the parsing to have failed (possibly on a previous run), or for the current instance to have failed
  10966. if (mCurTypeInstance != NULL)
  10967. {
  10968. if (mCurTypeInstance->mTypeFailed)
  10969. return;
  10970. if (mCurTypeInstance->mTypeDef->mSource->mParsingFailed)
  10971. return;
  10972. }
  10973. if (mCurMethodInstance != NULL)
  10974. {
  10975. if ((mCurMethodInstance->mMethodDef->mDeclaringType != NULL) && (mCurMethodInstance->mMethodDef->mDeclaringType->mSource->mParsingFailed))
  10976. return;
  10977. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL) && (mCurMethodState->mMixinState->mMixinMethodInstance->mMethodDef->mDeclaringType->mSource->mParsingFailed))
  10978. return;
  10979. }
  10980. BF_ASSERT(mCompiler->mPassInstance->HasFailed());
  10981. }
  10982. void BfModule::AssertParseErrorState()
  10983. {
  10984. if (mCompiler->mRevision == 1)
  10985. AssertErrorState();
  10986. }
  10987. BfType* BfModule::GetDelegateReturnType(BfType* delegateType)
  10988. {
  10989. BF_ASSERT(delegateType->IsDelegate());
  10990. auto typeInst = delegateType->ToTypeInstance();
  10991. PopulateType(typeInst, BfPopulateType_DataAndMethods);
  10992. BfMethodInstance* invokeMethodInstance = GetRawMethodInstanceAtIdx(typeInst->ToTypeInstance(), 0, "Invoke");
  10993. return invokeMethodInstance->mReturnType;
  10994. }
  10995. BfMethodInstance* BfModule::GetDelegateInvokeMethod(BfTypeInstance* typeInstance)
  10996. {
  10997. return GetRawMethodInstanceAtIdx(typeInstance, 0, "Invoke");
  10998. }
  10999. void BfModule::CreateDelegateInvokeMethod()
  11000. {
  11001. // Clear out debug loc - otherwise we'll single step onto the delegate type declaration
  11002. //mBfIRBuilder->ClearDebugLocation();
  11003. SetIllegalSrcPos();
  11004. auto typeInstance = mCurTypeInstance;
  11005. auto memberFuncType = mBfIRBuilder->MapMethod(mCurMethodInstance);
  11006. SizedArray<BfIRType, 4> staticParamTypes;
  11007. SizedArray<BfIRValue, 4> staticFuncArgs;
  11008. SizedArray<BfIRValue, 4> memberFuncArgs;
  11009. auto multicastDelegateType = typeInstance->mBaseType;
  11010. if (multicastDelegateType->mFieldInstances.size() != 2)
  11011. {
  11012. AssertErrorState();
  11013. return;
  11014. }
  11015. auto multicastDelegate = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapType(multicastDelegateType));
  11016. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 2); // Load 'delegate.mTarget'
  11017. auto fieldVal = mBfIRBuilder->CreateLoad(fieldPtr);
  11018. BfExprEvaluator exprEvaluator(this);
  11019. SizedArray<BfIRType, 8> origParamTypes;
  11020. BfIRType origReturnType;
  11021. mCurMethodInstance->GetIRFunctionInfo(this, origReturnType, origParamTypes);
  11022. if (mCurMethodInstance->mReturnType->IsValueType())
  11023. mBfIRBuilder->PopulateType(mCurMethodInstance->mReturnType, BfIRPopulateType_Full);
  11024. int thisIdx = 0;
  11025. if (mCurMethodInstance->HasStructRet())
  11026. {
  11027. thisIdx = 1;
  11028. staticFuncArgs.push_back(mBfIRBuilder->GetArgument(0));
  11029. memberFuncArgs.push_back(mBfIRBuilder->GetArgument(0));
  11030. }
  11031. memberFuncArgs.push_back(BfIRValue()); // Push 'target'
  11032. mCurMethodInstance->GetIRFunctionInfo(this, origReturnType, staticParamTypes, true);
  11033. for (int i = 1; i < (int)mCurMethodState->mLocals.size(); i++)
  11034. {
  11035. BfTypedValue localVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[i], true);
  11036. exprEvaluator.PushArg(localVal, staticFuncArgs);
  11037. exprEvaluator.PushArg(localVal, memberFuncArgs);
  11038. }
  11039. auto staticFunc = mBfIRBuilder->CreateFunctionType(origReturnType, staticParamTypes, false);
  11040. auto staticFuncPtr = mBfIRBuilder->GetPointerTo(staticFunc);
  11041. auto staticFuncPtrPtr = mBfIRBuilder->GetPointerTo(staticFuncPtr);
  11042. auto trueBB = mBfIRBuilder->CreateBlock("if.then", true);
  11043. auto falseBB = mBfIRBuilder->CreateBlock("if.else");
  11044. auto doneBB = mBfIRBuilder->CreateBlock("done");
  11045. auto checkTargetNull = mBfIRBuilder->CreateIsNotNull(fieldVal);
  11046. mBfIRBuilder->CreateCondBr(checkTargetNull, trueBB, falseBB);
  11047. BfIRValue nonStaticResult;
  11048. BfIRValue staticResult;
  11049. auto callingConv = GetCallingConvention(mCurTypeInstance, mCurMethodInstance->mMethodDef);
  11050. /// Non-static invocation
  11051. {
  11052. auto memberFuncPtr = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapMethod(mCurMethodInstance));
  11053. auto memberFuncPtrPtr = mBfIRBuilder->GetPointerTo(memberFuncPtr);
  11054. mBfIRBuilder->SetInsertPoint(trueBB);
  11055. memberFuncArgs[thisIdx] = mBfIRBuilder->CreateBitCast(fieldVal, mBfIRBuilder->MapType(mCurTypeInstance));
  11056. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 1); // Load 'delegate.mFuncPtr'
  11057. auto funcPtrPtr = mBfIRBuilder->CreateBitCast(fieldPtr, memberFuncPtrPtr);
  11058. auto funcPtr = mBfIRBuilder->CreateLoad(funcPtrPtr);
  11059. nonStaticResult = mBfIRBuilder->CreateCall(funcPtr, memberFuncArgs);
  11060. if (callingConv != BfIRCallingConv_CDecl)
  11061. mBfIRBuilder->SetCallCallingConv(nonStaticResult, callingConv);
  11062. mCurMethodState->SetHadReturn(false);
  11063. mCurMethodState->mLeftBlockUncond = false;
  11064. mCurMethodState->mLeftBlockCond = false;
  11065. mBfIRBuilder->CreateBr(doneBB);
  11066. }
  11067. // Static invocation
  11068. {
  11069. mBfIRBuilder->AddBlock(falseBB);
  11070. mBfIRBuilder->SetInsertPoint(falseBB);
  11071. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 1); // Load 'delegate.mFuncPtr'
  11072. auto funcPtrPtr = mBfIRBuilder->CreateBitCast(fieldPtr, staticFuncPtrPtr);
  11073. auto funcPtr = mBfIRBuilder->CreateLoad(funcPtrPtr);
  11074. staticResult = mBfIRBuilder->CreateCall(funcPtr, staticFuncArgs);
  11075. if (callingConv == BfIRCallingConv_ThisCall)
  11076. callingConv = BfIRCallingConv_CDecl;
  11077. if (callingConv != BfIRCallingConv_CDecl)
  11078. mBfIRBuilder->SetCallCallingConv(staticResult, callingConv);
  11079. // if (!mSystem->IsCompatibleCallingConvention(BfCallingConvention_Unspecified, mCurMethodInstance->mMethodDef->mCallingConvention))
  11080. // {
  11081. // if (mCurMethodInstance->mMethodDef->mCallingConvention == BfCallingConvention_Stdcall)
  11082. //
  11083. // }
  11084. mCurMethodState->SetHadReturn(false);
  11085. mCurMethodState->mLeftBlockUncond = false;
  11086. mCurMethodState->mLeftBlockCond = false;
  11087. mBfIRBuilder->CreateBr(doneBB);
  11088. }
  11089. mBfIRBuilder->AddBlock(doneBB);
  11090. mBfIRBuilder->SetInsertPoint(doneBB);
  11091. if ((mCurMethodInstance->mReturnType->IsValuelessType()) || (mCurMethodInstance->HasStructRet()))
  11092. {
  11093. mBfIRBuilder->CreateRetVoid();
  11094. }
  11095. else
  11096. {
  11097. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapType(mCurMethodInstance->mReturnType), 2);
  11098. mBfIRBuilder->AddPhiIncoming(phi, nonStaticResult, trueBB);
  11099. mBfIRBuilder->AddPhiIncoming(phi, staticResult, falseBB);
  11100. mBfIRBuilder->CreateRet(phi);
  11101. }
  11102. }
  11103. // "Interested" here means every method for a normal compile, and just the method the cursor is on for autocompletion
  11104. bool BfModule::IsInterestedInMethod(BfTypeInstance* typeInstance, BfMethodDef* methodDef)
  11105. {
  11106. auto typeDef = typeInstance->mTypeDef;
  11107. auto methodDeclaration = methodDef->mMethodDeclaration;
  11108. if (!mCompiler->mIsResolveOnly)
  11109. return true;
  11110. if (typeInstance->IsGenericTypeInstance())
  11111. {
  11112. // We only really want to process the unspecialized type for autocompletion
  11113. if ((!typeInstance->IsUnspecializedType()) || (typeInstance->IsUnspecializedTypeVariation()))
  11114. return false;
  11115. }
  11116. BfAstNode* checkNode = methodDeclaration;
  11117. if (methodDeclaration == NULL)
  11118. checkNode = methodDef->mBody;
  11119. if ((mCompiler->mResolvePassData->mParser != NULL) && (typeDef->mTypeDeclaration->IsFromParser(mCompiler->mResolvePassData->mParser)))
  11120. {
  11121. if (mCompiler->mResolvePassData->mAutoComplete == NULL)
  11122. return true;
  11123. }
  11124. return false;
  11125. }
  11126. void BfModule::CalcAppendAlign(BfMethodInstance* methodInst)
  11127. {
  11128. methodInst->mAppendAllocAlign = 1;
  11129. }
  11130. BfTypedValue BfModule::TryConstCalcAppend(BfMethodInstance* methodInst, SizedArrayImpl<BfIRValue>& args)
  11131. {
  11132. BP_ZONE("BfModule::TryConstCalcAppend");
  11133. if (mCompiler->mIsResolveOnly)
  11134. return BfTypedValue();
  11135. // We want to regenerate all ctor calls when the method internals change
  11136. {
  11137. auto checkTypeInst = methodInst->GetOwner();
  11138. while (checkTypeInst->mTypeDef->mHasAppendCtor)
  11139. {
  11140. AddDependency(checkTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_InlinedCall);
  11141. checkTypeInst = GetBaseType(checkTypeInst);
  11142. }
  11143. }
  11144. if (!methodInst->mMayBeConst)
  11145. return BfTypedValue();
  11146. // Do we need to iterate in order to resolve mAppendAllocAlign?
  11147. bool isFirstRun = methodInst->mAppendAllocAlign < 0;
  11148. bool wasAllConst = true;
  11149. int argIdx = 0;
  11150. int paramIdx = 0;
  11151. while (true)
  11152. {
  11153. if (argIdx >= (int)args.size())
  11154. break;
  11155. auto paramType = methodInst->GetParamType(paramIdx);
  11156. PopulateType(paramType);
  11157. int argCount = 0;
  11158. if (!paramType->IsValuelessType())
  11159. {
  11160. if (methodInst->GetParamIsSplat(paramIdx))
  11161. argCount = paramType->GetSplatCount();
  11162. else
  11163. argCount = 1;
  11164. for (int argOfs = 0; argOfs < argCount; argOfs++)
  11165. {
  11166. auto arg = args[argIdx + argOfs];
  11167. if (!arg.IsConst())
  11168. {
  11169. wasAllConst = false;
  11170. if (!isFirstRun)
  11171. {
  11172. auto& param = methodInst->mParams[argIdx];
  11173. if (param.mReferencedInConstPass)
  11174. {
  11175. // If this param is required as part of the const calculation then
  11176. // we require that it be const...
  11177. return BfTypedValue();
  11178. }
  11179. }
  11180. }
  11181. }
  11182. }
  11183. paramIdx++;
  11184. argIdx += argCount;
  11185. }
  11186. auto methodDef = methodInst->mMethodDef;
  11187. auto methodDecl = methodDef->GetMethodDeclaration();
  11188. auto methodDeclBlock = BfNodeDynCast<BfBlock>(methodDecl->mBody);
  11189. if (methodDeclBlock == NULL)
  11190. return BfTypedValue();
  11191. BfTypedValue constValue;
  11192. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  11193. auto checkState = mCurMethodState->mConstResolveState;
  11194. while (checkState != NULL)
  11195. {
  11196. if (checkState->mMethodInstance == methodInst)
  11197. {
  11198. return BfTypedValue();
  11199. }
  11200. checkState = checkState->mPrevConstResolveState;
  11201. }
  11202. //auto accumValue = GetConstValue(0);
  11203. bool failed = false;
  11204. //
  11205. {
  11206. BfConstResolveState constResolveState;
  11207. constResolveState.mMethodInstance = methodInst;
  11208. constResolveState.mPrevConstResolveState = mCurMethodState->mConstResolveState;
  11209. SetAndRestoreValue<bool> ignoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  11210. BfMethodState methodState;
  11211. SetAndRestoreValue<BfTypeInstance*> prevTypeInst(mCurTypeInstance, methodInst->GetOwner());
  11212. SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, methodInst);
  11213. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  11214. methodState.mTempKind = BfMethodState::TempKind_NonStatic;
  11215. methodState.mConstResolveState = &constResolveState;
  11216. int argIdx = 0;
  11217. for (int paramIdx = 0; paramIdx < methodInst->GetParamCount(); paramIdx++)
  11218. {
  11219. if (methodInst->GetParamKind(paramIdx) == BfParamKind_AppendIdx)
  11220. continue;
  11221. auto paramType = methodInst->GetParamType(paramIdx);
  11222. // Fix this after we allow structs to be consts
  11223. //BF_ASSERT(!paramType->IsSplattable());
  11224. BfLocalVariable* localVar = new BfLocalVariable();
  11225. localVar->mName = methodInst->GetParamName(paramIdx);
  11226. localVar->mResolvedType = paramType;
  11227. localVar->mConstValue = args[argIdx];
  11228. localVar->mParamIdx = paramIdx;
  11229. AddLocalVariableDef(localVar);
  11230. argIdx++;
  11231. }
  11232. AppendAllocVisitor appendAllocVisitor;
  11233. appendAllocVisitor.mConstAccum = GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr));
  11234. appendAllocVisitor.mIsFirstConstPass = isFirstRun;
  11235. BfTypedValue baseCtorAppendValue = CallBaseCtorCalc(true);
  11236. if (baseCtorAppendValue)
  11237. {
  11238. if (baseCtorAppendValue.mValue.IsFake())
  11239. appendAllocVisitor.mFailed = true;
  11240. else
  11241. appendAllocVisitor.mConstAccum = baseCtorAppendValue;
  11242. }
  11243. appendAllocVisitor.mModule = this;
  11244. appendAllocVisitor.VisitChild(methodDecl->mBody);
  11245. if (!appendAllocVisitor.mFailed)
  11246. constValue = appendAllocVisitor.mConstAccum;
  11247. if (isFirstRun)
  11248. mCurMethodInstance->mEndingAppendAllocAlign = appendAllocVisitor.mCurAppendAlign;
  11249. if (isFirstRun)
  11250. {
  11251. for (int paramIdx = 0; paramIdx < methodInst->GetParamCount(); paramIdx++)
  11252. {
  11253. auto localVar = mCurMethodState->mLocals[paramIdx];
  11254. if (localVar->mReadFromId != -1)
  11255. {
  11256. auto& param = methodInst->mParams[paramIdx];
  11257. param.mReferencedInConstPass = true;
  11258. }
  11259. }
  11260. }
  11261. }
  11262. mBfIRBuilder->SetInsertPoint(prevBlock);
  11263. if (!constValue)
  11264. {
  11265. // If we did a 'force' then some params may not have been const -- only clear mMayBeConst if we had
  11266. // all-const args
  11267. if (wasAllConst)
  11268. {
  11269. methodInst->mMayBeConst = false;
  11270. }
  11271. }
  11272. return constValue;
  11273. }
  11274. BfTypedValue BfModule::CallBaseCtorCalc(bool constOnly)
  11275. {
  11276. // Any errors should only be shown in the actual CTOR call
  11277. SetAndRestoreValue<bool> prevIgnoreWrites(mIgnoreErrors, true);
  11278. auto methodDef = mCurMethodInstance->mMethodDef;
  11279. BF_ASSERT((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend));
  11280. auto ctorDeclaration = (BfConstructorDeclaration*)methodDef->mMethodDeclaration;
  11281. BfTypeInstance* targetType = NULL;
  11282. if (ctorDeclaration->mInitializer != NULL)
  11283. {
  11284. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorDeclaration->mInitializer->mTarget);
  11285. targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  11286. }
  11287. else
  11288. targetType = mCurTypeInstance->mBaseType;
  11289. if ((targetType == NULL) || (targetType == mContext->mBfObjectType))
  11290. return NULL;
  11291. auto targetRefNode = methodDef->GetRefNode();
  11292. BfType* targetThisType = targetType;
  11293. BfTypedValue target(mBfIRBuilder->GetFakeVal(), targetThisType);
  11294. BfExprEvaluator exprEvaluator(this);
  11295. BfResolvedArgs argValues;
  11296. if ((ctorDeclaration != NULL) && (ctorDeclaration->mInitializer != NULL))
  11297. {
  11298. argValues.Init(&ctorDeclaration->mInitializer->mArguments);
  11299. }
  11300. //
  11301. {
  11302. }
  11303. BfFunctionBindResult bindResult;
  11304. bindResult.mSkipThis = true;
  11305. bindResult.mWantsArgs = true;
  11306. {
  11307. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  11308. exprEvaluator.ResolveArgValues(argValues, BfResolveArgFlag_DeferParamEval);
  11309. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(exprEvaluator.mFunctionBindResult, &bindResult);
  11310. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, true);
  11311. }
  11312. if (bindResult.mMethodInstance == NULL)
  11313. {
  11314. AssertErrorState();
  11315. return BfTypedValue();
  11316. }
  11317. if (!bindResult.mMethodInstance->mMethodDef->mHasAppend)
  11318. {
  11319. return BfTypedValue();
  11320. }
  11321. BF_ASSERT(bindResult.mIRArgs[0].IsFake());
  11322. bindResult.mIRArgs.RemoveAt(0);
  11323. auto calcAppendMethodModule = GetMethodInstanceAtIdx(bindResult.mMethodInstance->GetOwner(), bindResult.mMethodInstance->mMethodDef->mIdx + 1, BF_METHODNAME_CALCAPPEND);
  11324. BfTypedValue appendSizeTypedValue = TryConstCalcAppend(calcAppendMethodModule.mMethodInstance, bindResult.mIRArgs);
  11325. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mAppendAllocAlign >= 0);
  11326. mCurMethodInstance->mAppendAllocAlign = BF_MAX((int)mCurMethodInstance->mAppendAllocAlign, calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  11327. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign > -1);
  11328. mCurMethodState->mCurAppendAlign = BF_MAX(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign, 0);
  11329. if (appendSizeTypedValue)
  11330. return appendSizeTypedValue;
  11331. if (constOnly)
  11332. return BfTypedValue(mBfIRBuilder->GetFakeVal(), GetPrimitiveType(BfTypeCode_IntPtr));
  11333. bool needsRecalc = false;
  11334. for (auto irArg : bindResult.mIRArgs)
  11335. {
  11336. if (irArg.IsFake())
  11337. needsRecalc = true;
  11338. }
  11339. auto calcAppendArgs = bindResult.mIRArgs;
  11340. if (needsRecalc)
  11341. {
  11342. // Do it again, but without mIgnoreWrites set
  11343. BfResolvedArgs argValues;
  11344. argValues.Init(&ctorDeclaration->mInitializer->mArguments);
  11345. exprEvaluator.ResolveArgValues(argValues, BfResolveArgFlag_DeferParamEval);
  11346. BfFunctionBindResult bindResult;
  11347. bindResult.mSkipThis = true;
  11348. bindResult.mWantsArgs = true;
  11349. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(exprEvaluator.mFunctionBindResult, &bindResult);
  11350. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, true);
  11351. BF_ASSERT(bindResult.mIRArgs[0].IsFake());
  11352. bindResult.mIRArgs.RemoveAt(0);
  11353. calcAppendArgs = bindResult.mIRArgs;
  11354. }
  11355. BF_ASSERT(calcAppendMethodModule.mFunc);
  11356. appendSizeTypedValue = exprEvaluator.CreateCall(calcAppendMethodModule.mMethodInstance, calcAppendMethodModule.mFunc, false, calcAppendArgs);
  11357. BF_ASSERT(appendSizeTypedValue.mType == GetPrimitiveType(BfTypeCode_IntPtr));
  11358. return appendSizeTypedValue;
  11359. }
  11360. // This method never throws errors - it relies on the proper ctor actually throwing the errors
  11361. void BfModule::EmitCtorCalcAppend()
  11362. {
  11363. if (mCompiler->mIsResolveOnly)
  11364. return;
  11365. auto methodDef = mCurMethodInstance->mMethodDef;
  11366. auto methodDecl = methodDef->GetMethodDeclaration();
  11367. Array<BfAstNode*> deferredNodeList;
  11368. auto methodDeclBlock = BfNodeDynCast<BfBlock>(methodDecl->mBody);
  11369. if (methodDeclBlock == NULL)
  11370. return;
  11371. AppendAllocVisitor appendAllocVisitor;
  11372. auto baseCalcAppend = CallBaseCtorCalc(false);
  11373. if (baseCalcAppend)
  11374. {
  11375. mBfIRBuilder->CreateStore(baseCalcAppend.mValue, mCurMethodState->mRetVal.mValue);
  11376. }
  11377. appendAllocVisitor.mModule = this;
  11378. appendAllocVisitor.VisitChild(methodDecl->mBody);
  11379. }
  11380. void BfModule::CreateStaticCtor()
  11381. {
  11382. auto typeDef = mCurTypeInstance->mTypeDef;
  11383. auto methodDef = mCurMethodInstance->mMethodDef;
  11384. BfIRBlock exitBB;
  11385. if ((HasCompiledOutput()) && (!mCurMethodInstance->mIsUnspecialized) && (mCurMethodInstance->mChainType != BfMethodChainType_ChainMember))
  11386. {
  11387. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  11388. auto didStaticInitVarAddr = mBfIRBuilder->CreateGlobalVariable(
  11389. mBfIRBuilder->MapType(boolType),
  11390. false,
  11391. BfIRLinkageType_Internal,
  11392. GetDefaultValue(boolType),
  11393. "didStaticInit");
  11394. auto initBB = mBfIRBuilder->CreateBlock("init", true);
  11395. mCurMethodState->mIRExitBlock = mBfIRBuilder->CreateBlock("exit", true);
  11396. auto didStaticInitVar = mBfIRBuilder->CreateLoad(didStaticInitVarAddr);
  11397. mBfIRBuilder->CreateCondBr(didStaticInitVar, mCurMethodState->mIRExitBlock, initBB);
  11398. mBfIRBuilder->SetInsertPoint(initBB);
  11399. mBfIRBuilder->CreateStore(GetConstValue(1, boolType), didStaticInitVarAddr);
  11400. }
  11401. // Do DLL imports
  11402. if (!mDllImportEntries.empty())
  11403. {
  11404. auto internalType = ResolveTypeDef(mCompiler->mInternalTypeDef);
  11405. PopulateType(internalType);
  11406. auto getSharedProcAddressInstance = GetMethodByName(internalType->ToTypeInstance(), "GetSharedProcAddress");
  11407. if (!getSharedProcAddressInstance)
  11408. {
  11409. if (!mCompiler->mPassInstance->HasFailed())
  11410. Fail("Internal error: System.Internal doesn't contain LoadSharedLibrary method");
  11411. }
  11412. }
  11413. // Fill in initializer values
  11414. if ((!mCompiler->mIsResolveOnly) || (mCompiler->mResolvePassData->mAutoComplete == NULL))
  11415. {
  11416. for (auto fieldDef : typeDef->mFields)
  11417. {
  11418. if ((!fieldDef->mIsConst) && (fieldDef->mIsStatic) && (fieldDef->mInitializer != NULL))
  11419. {
  11420. // For extensions, only handle these fields in the appropriate extension
  11421. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  11422. continue;
  11423. UpdateSrcPos(fieldDef->mInitializer);
  11424. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  11425. if (!fieldInst->mFieldIncluded)
  11426. continue;
  11427. if (fieldInst->mResolvedType->IsVar())
  11428. {
  11429. BF_ASSERT(mHadVarUsage);
  11430. continue;
  11431. }
  11432. auto assignValue = GetFieldInitializerValue(fieldInst);
  11433. if (assignValue)
  11434. {
  11435. assignValue = LoadValue(assignValue);
  11436. if (!assignValue.mType->IsValuelessType())
  11437. {
  11438. auto staticVarRef = ReferenceStaticField(fieldInst).mValue;
  11439. mBfIRBuilder->CreateStore(assignValue.mValue, staticVarRef);
  11440. }
  11441. }
  11442. }
  11443. }
  11444. }
  11445. else
  11446. {
  11447. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  11448. {
  11449. if (tempTypeDef->mFullName == typeDef->mFullName)
  11450. {
  11451. for (auto fieldDef : tempTypeDef->mFields)
  11452. {
  11453. if ((fieldDef->mIsStatic) && (!fieldDef->mIsConst))
  11454. {
  11455. if (fieldDef->mInitializer != NULL)
  11456. {
  11457. if (mCompiler->mResolvePassData->mSourceClassifier != NULL)
  11458. {
  11459. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(fieldDef->mInitializer, BfSourceElementType_Normal);
  11460. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(fieldDef->mInitializer);
  11461. }
  11462. BfType* wantType = NULL;
  11463. if ((!BfNodeIsA<BfVarTypeReference>(fieldDef->mTypeRef)) && (!BfNodeIsA<BfLetTypeReference>(fieldDef->mTypeRef)))
  11464. {
  11465. wantType = ResolveTypeRef(fieldDef->mTypeRef);
  11466. }
  11467. CreateValueFromExpression(fieldDef->mInitializer, wantType, BfEvalExprFlags_FieldInitializer);
  11468. }
  11469. }
  11470. }
  11471. }
  11472. }
  11473. }
  11474. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  11475. CallChainedMethods(mCurMethodInstance, false);
  11476. }
  11477. void BfModule::EmitDtorBody()
  11478. {
  11479. if (mCurTypeInstance->IsClosure())
  11480. {
  11481. BfFieldInstance* fieldInstance = &mCurTypeInstance->mFieldInstances.back();
  11482. BF_ASSERT(fieldInstance->GetFieldDef()->mName == "__dtorThunk");
  11483. auto thisVal = GetThis();
  11484. auto dtorThunkPtr = mBfIRBuilder->CreateInBoundsGEP(thisVal.mValue, 0, fieldInstance->mDataIdx);
  11485. auto dtorThunk = mBfIRBuilder->CreateLoad(dtorThunkPtr);
  11486. auto funcPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapMethod(mCurMethodInstance));
  11487. auto dtorPtr = mBfIRBuilder->CreateBitCast(dtorThunk, funcPtrType);
  11488. SizedArray<BfIRValue, 1> args;
  11489. args.push_back(thisVal.mValue);
  11490. auto result = mBfIRBuilder->CreateCall(dtorPtr, args);
  11491. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_CDecl);
  11492. // Fall through to Object::~this call
  11493. auto dtorFunc = GetMethodByName(mContext->mBfObjectType, "~this");
  11494. auto basePtr = mBfIRBuilder->CreateBitCast(thisVal.mValue, mBfIRBuilder->MapTypeInstPtr(mContext->mBfObjectType));
  11495. SizedArray<BfIRValue, 1> vals = { basePtr };
  11496. result = mBfIRBuilder->CreateCall(dtorFunc.mFunc, vals);
  11497. mBfIRBuilder->SetCallCallingConv(result, GetCallingConvention(dtorFunc.mMethodInstance));
  11498. mBfIRBuilder->SetTailCall(result);
  11499. return;
  11500. }
  11501. auto typeDef = mCurTypeInstance->mTypeDef;
  11502. auto methodDef = mCurMethodInstance->mMethodDef;
  11503. auto methodDeclaration = methodDef->GetMethodDeclaration();
  11504. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  11505. CallChainedMethods(mCurMethodInstance, true);
  11506. if (auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody))
  11507. {
  11508. VisitCodeBlock(bodyBlock);
  11509. if (bodyBlock->mCloseBrace != NULL)
  11510. {
  11511. UpdateSrcPos(bodyBlock->mCloseBrace);
  11512. }
  11513. }
  11514. else
  11515. {
  11516. if (methodDeclaration != NULL)
  11517. UpdateSrcPos(methodDeclaration);
  11518. else if (typeDef->mTypeDeclaration != NULL)
  11519. UpdateSrcPos(typeDef->mTypeDeclaration);
  11520. if ((methodDeclaration != NULL) && (methodDeclaration->mFatArrowToken != NULL))
  11521. {
  11522. Fail("Destructors cannot have expression bodies", methodDeclaration->mFatArrowToken);
  11523. }
  11524. }
  11525. if ((!mCompiler->mIsResolveOnly) || (mCompiler->mResolvePassData->mAutoComplete == NULL))
  11526. {
  11527. for (int fieldIdx = (int)mCurTypeInstance->mFieldInstances.size() - 1; fieldIdx >= 0; fieldIdx--)
  11528. {
  11529. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldIdx];
  11530. auto fieldDef = fieldInst->GetFieldDef();
  11531. if ((fieldDef != NULL) && (fieldDef->mIsStatic == methodDef->mIsStatic) && (fieldDef->mFieldDeclaration != NULL) && (fieldDef->mFieldDeclaration->mFieldDtor != NULL))
  11532. {
  11533. if ((!methodDef->mIsStatic) && (mCurTypeInstance->IsValueType()))
  11534. {
  11535. Fail("Structs cannot have field destructors", fieldDef->mFieldDeclaration->mFieldDtor->mTildeToken);
  11536. }
  11537. SetAndRestoreValue<BfFilePosition> prevFilePos(mCurFilePosition);
  11538. auto fieldDtor = fieldDef->mFieldDeclaration->mFieldDtor;
  11539. if ((fieldDef->mIsStatic) != (methodDef->mIsStatic))
  11540. continue;
  11541. UpdateSrcPos(fieldDtor);
  11542. BfScopeData scopeData;
  11543. mCurMethodState->AddScope(&scopeData);
  11544. NewScopeState();
  11545. UpdateSrcPos(fieldDtor);
  11546. bool hasDbgInfo = (!fieldDef->mIsConst);
  11547. if (hasDbgInfo)
  11548. {
  11549. mBfIRBuilder->SaveDebugLocation();
  11550. mBfIRBuilder->ClearDebugLocation();
  11551. }
  11552. BfIRValue value;
  11553. if (fieldDef->mIsStatic)
  11554. {
  11555. value = ReferenceStaticField(fieldInst).mValue;
  11556. }
  11557. else
  11558. {
  11559. if (!mCurTypeInstance->IsValueType())
  11560. {
  11561. auto thisValue = GetThis();
  11562. value = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInst->mDataIdx);
  11563. }
  11564. else
  11565. {
  11566. AssertErrorState();
  11567. value = mBfIRBuilder->CreateConstNull(mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(fieldInst->mResolvedType)));
  11568. }
  11569. }
  11570. BfIRValue staticVal;
  11571. if (hasDbgInfo)
  11572. {
  11573. BfIRValue dbgShowValue = value;
  11574. BfLocalVariable* localDef = new BfLocalVariable();
  11575. localDef->mName = "_";
  11576. localDef->mResolvedType = fieldInst->mResolvedType;
  11577. localDef->mAddr = value;
  11578. if ((mBfIRBuilder->DbgHasInfo()) && (!IsTargetingBeefBackend()))
  11579. {
  11580. // Create another pointer indirection, a ref to the gep
  11581. auto refFieldType = CreateRefType(fieldInst->mResolvedType);
  11582. auto allocaInst = CreateAlloca(refFieldType);
  11583. auto storeResult = mBfIRBuilder->CreateStore(value, allocaInst);
  11584. localDef->mResolvedType = refFieldType;
  11585. localDef->mAddr = allocaInst;
  11586. }
  11587. mBfIRBuilder->RestoreDebugLocation();
  11588. auto defLocalVar = AddLocalVariableDef(localDef, true);
  11589. // Put back so we actually modify the correct value*/
  11590. defLocalVar->mResolvedType = fieldInst->mResolvedType;
  11591. defLocalVar->mAddr = value;
  11592. }
  11593. while (fieldDtor != NULL)
  11594. {
  11595. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  11596. {
  11597. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(fieldDtor, BfSourceElementType_Normal);
  11598. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(fieldDtor);
  11599. }
  11600. UpdateSrcPos(fieldDtor);
  11601. VisitEmbeddedStatement(fieldDtor->mBody);
  11602. fieldDtor = fieldDtor->mNextFieldDtor;
  11603. }
  11604. RestoreScopeState();
  11605. }
  11606. }
  11607. if (!methodDef->mIsStatic)
  11608. {
  11609. auto checkBaseType = mCurTypeInstance->mBaseType;
  11610. while (checkBaseType != NULL)
  11611. {
  11612. if (auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody))
  11613. {
  11614. if (bodyBlock->mCloseBrace != NULL)
  11615. UpdateSrcPos(bodyBlock->mCloseBrace);
  11616. }
  11617. else
  11618. {
  11619. UpdateSrcPos(typeDef->mTypeDeclaration->mNameNode);
  11620. }
  11621. if (checkBaseType->mTypeDef->mDtorDef != NULL)
  11622. {
  11623. auto dtorMethodInstance = GetMethodInstance(checkBaseType, checkBaseType->mTypeDef->mDtorDef, BfTypeVector());
  11624. if (mCompiler->IsSkippingExtraResolveChecks())
  11625. {
  11626. // Nothing
  11627. }
  11628. else if (dtorMethodInstance.mMethodInstance->GetParamCount() == 0)
  11629. {
  11630. if ((!mCompiler->IsSkippingExtraResolveChecks()) && (!checkBaseType->IsUnspecializedType()))
  11631. {
  11632. auto basePtr = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapTypeInstPtr(checkBaseType));
  11633. SizedArray<BfIRValue, 1> vals = { basePtr };
  11634. auto callInst = mBfIRBuilder->CreateCall(dtorMethodInstance.mFunc, vals);
  11635. mBfIRBuilder->SetCallCallingConv(callInst, GetCallingConvention(dtorMethodInstance.mMethodInstance));
  11636. }
  11637. }
  11638. else
  11639. {
  11640. // Invalid base dtor declaration
  11641. AssertErrorState();
  11642. }
  11643. break;
  11644. }
  11645. checkBaseType = checkBaseType->mBaseType;
  11646. }
  11647. }
  11648. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  11649. }
  11650. else
  11651. {
  11652. // The reason we can't just do the 'normal' path for this is that the BfTypeInstance here is NOT the
  11653. // autocomplete type instance, so FieldInstance initializer values contain expressions from the full
  11654. // resolve pass, NOT the autocomplete expression
  11655. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  11656. {
  11657. if (tempTypeDef->mFullName == typeDef->mFullName)
  11658. {
  11659. for (auto fieldDef : tempTypeDef->mFields)
  11660. {
  11661. if ((fieldDef->mIsStatic == methodDef->mIsStatic) && (fieldDef->mFieldDeclaration != NULL) &&
  11662. (fieldDef->mFieldDeclaration->mFieldDtor != NULL) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  11663. {
  11664. BfType* fieldType = NULL;
  11665. for (int curFieldIdx = 0; curFieldIdx < (int)mCurTypeInstance->mFieldInstances.size(); curFieldIdx++)
  11666. {
  11667. auto curFieldInstance = &mCurTypeInstance->mFieldInstances[curFieldIdx];
  11668. auto curFieldDef = curFieldInstance->GetFieldDef();
  11669. if ((curFieldDef != NULL) && (fieldDef->mName == curFieldDef->mName))
  11670. fieldType = curFieldInstance->GetResolvedType();
  11671. }
  11672. auto fieldDtor = fieldDef->mFieldDeclaration->mFieldDtor;
  11673. BfScopeData scopeData;
  11674. mCurMethodState->AddScope(&scopeData);
  11675. NewScopeState();
  11676. // This is just for autocomplete, it doesn't matter that mAddr is incorrect
  11677. if (fieldType != NULL)
  11678. {
  11679. BfLocalVariable* localDef = new BfLocalVariable();
  11680. localDef->mName = "_";
  11681. localDef->mResolvedType = fieldType;
  11682. localDef->mAddr = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(fieldType));
  11683. localDef->mIsAssigned = true;
  11684. AddLocalVariableDef(localDef);
  11685. }
  11686. while (fieldDtor != NULL)
  11687. {
  11688. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(fieldDtor, BfSourceElementType_Normal);
  11689. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(fieldDtor);
  11690. UpdateSrcPos(fieldDtor);
  11691. VisitEmbeddedStatement(fieldDtor->mBody);
  11692. fieldDtor = fieldDtor->mNextFieldDtor;
  11693. }
  11694. RestoreScopeState();
  11695. }
  11696. }
  11697. }
  11698. }
  11699. }
  11700. }
  11701. BfIRValue BfModule::CreateDllImportGlobalVar(BfMethodInstance* methodInstance, bool define)
  11702. {
  11703. auto typeInstance = methodInstance->GetOwner();
  11704. bool foundDllImportAttr = false;
  11705. BfCallingConvention callingConvention = methodInstance->mMethodDef->mCallingConvention;
  11706. for (auto customAttr : methodInstance->GetCustomAttributes()->mAttributes)
  11707. {
  11708. if (customAttr.mType->mTypeDef->mFullName.ToString() == "System.ImportAttribute")
  11709. {
  11710. foundDllImportAttr = true;
  11711. }
  11712. }
  11713. if (!foundDllImportAttr)
  11714. {
  11715. AssertErrorState();
  11716. return BfIRValue();
  11717. }
  11718. String name = "bf_hs_preserve@";
  11719. BfMangler::Mangle(name, mCompiler->GetMangleKind(), methodInstance);
  11720. name += "__imp";
  11721. BfIRType returnType;
  11722. SizedArray<BfIRType, 8> paramTypes;
  11723. methodInstance->GetIRFunctionInfo(this, returnType, paramTypes);
  11724. BfIRFunctionType externFunctionType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes, false);
  11725. auto ptrType = mBfIRBuilder->GetPointerTo(externFunctionType);
  11726. BfIRValue initVal;
  11727. if (define)
  11728. {
  11729. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  11730. initVal = mBfIRBuilder->CreateConstNull(ptrType);
  11731. }
  11732. auto globalVar = mBfIRBuilder->CreateGlobalVariable(ptrType, false, BfIRLinkageType_External, initVal, name);
  11733. if ((define) && (mBfIRBuilder->DbgHasInfo()))
  11734. {
  11735. auto voidType = GetPrimitiveType(BfTypeCode_None);
  11736. auto ptrType = CreatePointerType(voidType);
  11737. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, name, name, BfIRMDNode(), 0, mBfIRBuilder->DbgGetType(ptrType), false, globalVar);
  11738. }
  11739. return globalVar;
  11740. }
  11741. void BfModule::CreateDllImportMethod()
  11742. {
  11743. if (mBfIRBuilder->mIgnoreWrites)
  11744. return;
  11745. auto globalVar = mFuncReferences[mCurMethodInstance];
  11746. if (!globalVar)
  11747. return;
  11748. bool allowTailCall = true;
  11749. mBfIRBuilder->ClearDebugLocation();
  11750. bool isHotCompile = mCompiler->IsHotCompile();
  11751. // If we are hot swapping, we need to have this stub because we may need to call the LoadSharedLibraries on demand
  11752. if (isHotCompile)
  11753. {
  11754. auto loadSharedLibsFunc = GetBuiltInFunc(BfBuiltInFuncType_LoadSharedLibraries);
  11755. mBfIRBuilder->CreateCall(loadSharedLibsFunc, SizedArray<BfIRValue, 0>());
  11756. }
  11757. auto callingConvention = GetCallingConvention(mCurTypeInstance, mCurMethodInstance->mMethodDef);
  11758. BfIRType returnType;
  11759. SizedArray<BfIRType, 8> paramTypes;
  11760. mCurMethodInstance->GetIRFunctionInfo(this, returnType, paramTypes);
  11761. SizedArray<BfIRValue, 8> args;
  11762. for (int i = 0; i < (int)paramTypes.size(); i++)
  11763. args.push_back(mBfIRBuilder->GetArgument(i));
  11764. BfIRFunctionType externFunctionType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes, false);
  11765. if (isHotCompile)
  11766. {
  11767. BfIRValue funcVal = mBfIRBuilder->CreateLoad(globalVar);
  11768. auto result = mBfIRBuilder->CreateCall(funcVal, args);
  11769. if (callingConvention == BfIRCallingConv_StdCall)
  11770. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_StdCall);
  11771. else
  11772. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_CDecl);
  11773. if (allowTailCall)
  11774. mBfIRBuilder->SetTailCall(result);
  11775. CreateReturn(result);
  11776. mCurMethodState->mHadReturn = true;
  11777. }
  11778. if (HasCompiledOutput())
  11779. {
  11780. BfDllImportEntry dllImportEntry;
  11781. dllImportEntry.mFuncVar = globalVar;
  11782. dllImportEntry.mMethodInstance = mCurMethodInstance;
  11783. mDllImportEntries.push_back(dllImportEntry);
  11784. }
  11785. }
  11786. BfIRCallingConv BfModule::GetCallingConvention(BfTypeInstance* typeInst, BfMethodDef* methodDef)
  11787. {
  11788. if (mSystem->mPtrSize == 8)
  11789. return BfIRCallingConv_CDecl;
  11790. if (methodDef->mCallingConvention == BfCallingConvention_Stdcall)
  11791. return BfIRCallingConv_StdCall;
  11792. if ((!methodDef->mIsStatic) && (!typeInst->IsValuelessType()) &&
  11793. ((!typeInst->IsSplattable()) || (methodDef->HasNoThisSplat())))
  11794. return BfIRCallingConv_ThisCall;
  11795. return BfIRCallingConv_CDecl;
  11796. }
  11797. BfIRCallingConv BfModule::GetCallingConvention(BfMethodInstance* methodInstance)
  11798. {
  11799. return GetCallingConvention(methodInstance->GetOwner(), methodInstance->mMethodDef);
  11800. }
  11801. void BfModule::SetupIRMethod(BfMethodInstance* methodInstance, BfIRFunction func, bool isInlined)
  11802. {
  11803. BfMethodDef* methodDef = NULL;
  11804. if (methodInstance != NULL)
  11805. methodDef = methodInstance->mMethodDef;
  11806. if (!func)
  11807. return;
  11808. if (mCompiler->mOptions.mNoFramePointerElim)
  11809. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_NoFramePointerElim);
  11810. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_NoUnwind);
  11811. if (mSystem->mPtrSize == 8) // We need unwind info for debugging
  11812. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_UWTable);
  11813. if (methodInstance == NULL)
  11814. return;
  11815. if (methodDef->mImportKind == BfImportKind_Export)
  11816. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_DllExport);
  11817. if (methodDef->mNoReturn)
  11818. mBfIRBuilder->Func_AddAttribute(func, -1, BfIRAttribute_NoReturn);
  11819. auto callingConv = GetCallingConvention(methodInstance->GetOwner(), methodDef);
  11820. if (callingConv != BfIRCallingConv_CDecl)
  11821. mBfIRBuilder->SetFuncCallingConv(func, callingConv);
  11822. if (isInlined)
  11823. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_AlwaysInline);
  11824. int argIdx = 0;
  11825. int paramIdx = 0;
  11826. if (methodInstance->HasThis())
  11827. {
  11828. paramIdx = -1;
  11829. }
  11830. int argCount = methodInstance->GetIRFunctionParamCount(this);
  11831. if (methodInstance->HasStructRet())
  11832. {
  11833. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_NoAlias);
  11834. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_StructRet);
  11835. argIdx++;
  11836. }
  11837. while (argIdx < argCount)
  11838. {
  11839. while ((paramIdx != -1) && (methodInstance->IsParamSkipped(paramIdx)))
  11840. paramIdx++;
  11841. BfType* resolvedTypeRef = NULL;
  11842. String paramName;
  11843. bool isSplattable = false;
  11844. bool isThis = paramIdx == -1;
  11845. if (isThis)
  11846. {
  11847. paramName = "this";
  11848. if (methodInstance->mIsClosure)
  11849. resolvedTypeRef = mCurMethodState->mClosureState->mClosureType;
  11850. else
  11851. resolvedTypeRef = methodInstance->GetOwner();
  11852. isSplattable = (resolvedTypeRef->IsSplattable()) && (!methodDef->HasNoThisSplat());
  11853. }
  11854. else if (!methodDef->mNoSplat)
  11855. {
  11856. paramName = methodInstance->GetParamName(paramIdx);
  11857. resolvedTypeRef = methodInstance->GetParamType(paramIdx);
  11858. if (resolvedTypeRef->IsMethodRef())
  11859. isSplattable = true;
  11860. else if (resolvedTypeRef->IsSplattable())
  11861. {
  11862. if (resolvedTypeRef->GetSplatCount() + argIdx <= mCompiler->mOptions.mMaxSplatRegs)
  11863. isSplattable = true;
  11864. }
  11865. }
  11866. //
  11867. {
  11868. auto loweredTypeCode = resolvedTypeRef->GetLoweredType();
  11869. if (loweredTypeCode != BfTypeCode_None)
  11870. resolvedTypeRef = GetPrimitiveType(loweredTypeCode);
  11871. }
  11872. auto _SetupParam = [&](const StringImpl& paramName, BfType* resolvedTypeRef)
  11873. {
  11874. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, paramName);
  11875. int addDeref = -1;
  11876. if (resolvedTypeRef->IsRef())
  11877. {
  11878. auto refType = (BfRefType*)resolvedTypeRef;
  11879. auto elementType = refType->mElementType;
  11880. PopulateType(elementType, BfPopulateType_Data);
  11881. addDeref = elementType->mSize;
  11882. if ((addDeref <= 0) && (!elementType->IsValuelessType()))
  11883. AssertErrorState();
  11884. }
  11885. if ((resolvedTypeRef->IsComposite()) && (!resolvedTypeRef->IsTypedPrimitive()))
  11886. {
  11887. if (mCompiler->mOptions.mAllowStructByVal)
  11888. {
  11889. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_ByVal);
  11890. }
  11891. else
  11892. {
  11893. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_NoCapture);
  11894. PopulateType(resolvedTypeRef, BfPopulateType_Data);
  11895. addDeref = resolvedTypeRef->mSize;
  11896. }
  11897. }
  11898. else if (resolvedTypeRef->IsPrimitiveType())
  11899. {
  11900. auto primType = (BfPrimitiveType*)resolvedTypeRef;
  11901. if (primType->mTypeDef->mTypeCode == BfTypeCode_Boolean)
  11902. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_ZExt);
  11903. }
  11904. if (addDeref >= 0)
  11905. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_Dereferencable, addDeref);
  11906. argIdx++;
  11907. };
  11908. if (isSplattable)
  11909. {
  11910. std::function<void(BfType*, const StringImpl&)> checkTypeLambda = [&](BfType* checkType, const StringImpl& curName)
  11911. {
  11912. if (checkType->IsStruct())
  11913. {
  11914. auto checkTypeInstance = checkType->ToTypeInstance();
  11915. if (checkTypeInstance->mBaseType != NULL)
  11916. checkTypeLambda(checkTypeInstance->mBaseType, curName);
  11917. if (checkTypeInstance->mIsUnion)
  11918. {
  11919. BfType* unionInnerType = checkTypeInstance->GetUnionInnerType();
  11920. checkTypeLambda(unionInnerType, curName + "_data");
  11921. }
  11922. else
  11923. {
  11924. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  11925. {
  11926. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  11927. auto fieldDef = fieldInstance->GetFieldDef();
  11928. if (fieldInstance->mDataIdx >= 0)
  11929. {
  11930. checkTypeLambda(fieldInstance->GetResolvedType(), curName + "_" + fieldInstance->GetFieldDef()->mName);
  11931. }
  11932. }
  11933. }
  11934. if (checkTypeInstance->IsEnum())
  11935. {
  11936. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, curName + "_dscr");
  11937. argIdx++;
  11938. }
  11939. }
  11940. else if (checkType->IsMethodRef())
  11941. {
  11942. auto methodRefType = (BfMethodRefType*)checkType;
  11943. BfMethodInstance* methodRefMethodInst = methodRefType->mMethodRef;
  11944. for (int dataIdx = 0; dataIdx < (int)methodRefType->GetCaptureDataCount(); dataIdx++)
  11945. {
  11946. int methodRefParamIdx = methodRefType->GetParamIdxFromDataIdx(dataIdx);
  11947. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  11948. {
  11949. checkTypeLambda(methodRefType->GetCaptureType(dataIdx), curName + "_" + methodRefMethodInst->GetParamName(methodRefParamIdx));
  11950. }
  11951. else
  11952. {
  11953. _SetupParam(curName + "_" + methodRefMethodInst->GetParamName(methodRefParamIdx), methodRefType->GetCaptureType(dataIdx));
  11954. }
  11955. }
  11956. }
  11957. else if (!checkType->IsValuelessType())
  11958. {
  11959. _SetupParam(curName, checkType);
  11960. }
  11961. };
  11962. checkTypeLambda(resolvedTypeRef, paramName);
  11963. paramIdx++;
  11964. continue;
  11965. }
  11966. _SetupParam(paramName, resolvedTypeRef);
  11967. //argIdx++;
  11968. paramIdx++;
  11969. }
  11970. }
  11971. void BfModule::EmitCtorBody(bool& skipBody)
  11972. {
  11973. auto methodInstance = mCurMethodInstance;
  11974. auto methodDef = methodInstance->mMethodDef;
  11975. auto methodDeclaration = methodDef->mMethodDeclaration;
  11976. auto ctorDeclaration = (BfConstructorDeclaration*)methodDef->mMethodDeclaration;
  11977. auto typeDef = mCurTypeInstance->mTypeDef;
  11978. // Prologue
  11979. mBfIRBuilder->ClearDebugLocation();
  11980. bool hadThisInitializer = false;
  11981. if ((ctorDeclaration != NULL) && (ctorDeclaration->mInitializer != NULL))
  11982. {
  11983. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorDeclaration->mInitializer->mTarget);
  11984. auto targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  11985. if (targetToken->GetToken() == BfToken_This)
  11986. {
  11987. hadThisInitializer = true;
  11988. // Since we call a 'this', it's that other ctor's responsibility to fully assign the fields
  11989. mCurMethodState->LocalDefined(GetThisVariable());
  11990. }
  11991. }
  11992. // Zero out memory for default ctor
  11993. if ((methodDeclaration == NULL) && (mCurTypeInstance->IsStruct()))
  11994. {
  11995. if (mCurTypeInstance->IsTypedPrimitive())
  11996. {
  11997. auto thisRef = mCurMethodState->mLocals[0]->mValue;
  11998. mBfIRBuilder->CreateStore(GetDefaultValue(mCurTypeInstance), thisRef);
  11999. }
  12000. else if (mCurTypeInstance->mInstSize > 0)
  12001. {
  12002. BfIRValue fillValue = GetConstValue8(0);
  12003. BfIRValue sizeValue = GetConstValue(mCurTypeInstance->mInstSize);
  12004. auto thisRef = mCurMethodState->mLocals[0]->mValue;
  12005. BfIRValue destBits = mBfIRBuilder->CreateBitCast(thisRef, mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr));
  12006. mBfIRBuilder->CreateMemSet(destBits, fillValue, sizeValue, mCurTypeInstance->mAlign);
  12007. }
  12008. }
  12009. BfAstNode* baseCtorNode = NULL;
  12010. if ((ctorDeclaration != NULL) && (ctorDeclaration->mInitializer != NULL) && (ctorDeclaration->mInitializer->mTarget != NULL))
  12011. baseCtorNode = ctorDeclaration->mInitializer->mTarget;
  12012. else if (methodDef->mBody != NULL)
  12013. baseCtorNode = methodDef->mBody;
  12014. else if (ctorDeclaration != NULL)
  12015. baseCtorNode = ctorDeclaration;
  12016. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  12017. baseCtorNode = mCurTypeInstance->mTypeDef->mTypeDeclaration->mNameNode;
  12018. else if ((mCurTypeInstance->mBaseType != NULL) && (mCurTypeInstance->mBaseType->mTypeDef->mTypeDeclaration != NULL))
  12019. baseCtorNode = mCurTypeInstance->mBaseType->mTypeDef->mTypeDeclaration;
  12020. else
  12021. baseCtorNode = mContext->mBfObjectType->mTypeDef->mTypeDeclaration;
  12022. if ((!mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType == BfMethodType_Ctor))
  12023. {
  12024. // Call the root type's default ctor (with no body) to initialize its fields and call the chained ctors
  12025. if (methodDef->mDeclaringType->mTypeCode == BfTypeCode_Extension)
  12026. {
  12027. BfMethodDef* defaultCtor = NULL;
  12028. for (auto methodDef : mCurTypeInstance->mTypeDef->mMethods)
  12029. {
  12030. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) && (methodDef->mDeclaringType->mTypeCode != BfTypeCode_Extension))
  12031. {
  12032. defaultCtor = methodDef;
  12033. }
  12034. }
  12035. if (defaultCtor != NULL)
  12036. {
  12037. UpdateSrcPos(mCurTypeInstance->mTypeDef->GetRefNode());
  12038. SetIllegalSrcPos();
  12039. auto moduleMethodInstance = GetMethodInstance(mCurTypeInstance, defaultCtor, BfTypeVector());
  12040. BfExprEvaluator exprEvaluator(this);
  12041. SizedArray<BfIRValue, 1> irArgs;
  12042. exprEvaluator.PushThis(NULL, GetThis(), moduleMethodInstance.mMethodInstance, irArgs);
  12043. exprEvaluator.CreateCall(moduleMethodInstance.mMethodInstance, moduleMethodInstance.mFunc, false, irArgs);
  12044. }
  12045. }
  12046. }
  12047. // Initialize fields (if applicable)
  12048. if (mCurTypeInstance->IsBoxed())
  12049. {
  12050. skipBody = true;
  12051. }
  12052. else if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mDeclaringType->mTypeCode == BfTypeCode_Extension))
  12053. {
  12054. // Field initializers occur in CtorNoBody methods for extensions
  12055. }
  12056. else if (!hadThisInitializer)
  12057. {
  12058. // If we had a 'this' initializer, that other ctor will have initialized our fields
  12059. if ((!mCompiler->mIsResolveOnly) ||
  12060. (mCompiler->mResolvePassData->mAutoComplete == NULL) ||
  12061. (mCompiler->mResolvePassData->mAutoComplete->mResolveType == BfResolveType_ShowFileSymbolReferences))
  12062. {
  12063. bool hadInlineInitBlock = false;
  12064. BfScopeData scopeData;
  12065. for (auto fieldDef : typeDef->mFields)
  12066. {
  12067. // For extensions, only handle these fields in the appropriate extension
  12068. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  12069. continue;
  12070. if ((!fieldDef->mIsConst) && (!fieldDef->mIsStatic))
  12071. {
  12072. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  12073. if (!fieldInst->mFieldIncluded)
  12074. continue;
  12075. if (fieldInst->mDataIdx < 0)
  12076. continue;
  12077. if (fieldDef->mInitializer == NULL)
  12078. {
  12079. if (fieldDef->mProtection != BfProtection_Hidden)
  12080. continue;
  12081. if (mCurTypeInstance->IsObject()) // Already zeroed out
  12082. continue;
  12083. }
  12084. if (fieldInst->mResolvedType == NULL)
  12085. {
  12086. BF_ASSERT(mHadBuildError);
  12087. continue;
  12088. }
  12089. if (fieldDef->mInitializer != NULL)
  12090. {
  12091. if (!hadInlineInitBlock)
  12092. {
  12093. if ((mBfIRBuilder->DbgHasInfo()) && (!mCurTypeInstance->IsUnspecializedType()) && (mHasFullDebugInfo))
  12094. {
  12095. UpdateSrcPos(baseCtorNode);
  12096. // 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
  12097. EmitEnsureInstructionAt();
  12098. BfType* thisType = mCurTypeInstance;
  12099. if (thisType->IsValueType())
  12100. thisType = CreateRefType(thisType);
  12101. SizedArray<BfIRMDNode, 1> diParamTypes;
  12102. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParamTypes);
  12103. mCurMethodState->AddScope(&scopeData);
  12104. NewScopeState();
  12105. int flags = 0;
  12106. mCurMethodState->mCurScope->mDIInlinedAt = mBfIRBuilder->DbgGetCurrentLocation();
  12107. BF_ASSERT(mCurMethodState->mCurScope->mDIInlinedAt);
  12108. // mCurMethodState->mCurScope->mDIInlinedAt may still be null ifwe don't have an explicit ctor
  12109. mCurMethodState->mCurScope->mDIScope = mBfIRBuilder->DbgCreateFunction(mBfIRBuilder->DbgGetTypeInst(mCurTypeInstance), "this$initFields", "", mCurFilePosition.mFileInstance->mDIFile,
  12110. mCurFilePosition.mCurLine + 1, diFuncType, false, true, mCurFilePosition.mCurLine + 1, flags, false, BfIRValue());
  12111. UpdateSrcPos(fieldDef->mInitializer);
  12112. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  12113. "this", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(thisType));
  12114. //
  12115. {
  12116. auto loadedThis = GetThis();
  12117. // LLVM can't handle two variables pointing to the same value
  12118. BfIRValue copiedThisPtr;
  12119. copiedThisPtr = CreateAlloca(thisType);
  12120. auto storeInst = mBfIRBuilder->CreateStore(loadedThis.mValue, copiedThisPtr);
  12121. mBfIRBuilder->ClearDebugLocation(storeInst);
  12122. mBfIRBuilder->DbgInsertDeclare(copiedThisPtr, diVariable);
  12123. }
  12124. hadInlineInitBlock = true;
  12125. }
  12126. }
  12127. UpdateSrcPos(fieldDef->mInitializer);
  12128. }
  12129. BfIRValue fieldAddr;
  12130. if (!mCurTypeInstance->IsTypedPrimitive())
  12131. {
  12132. fieldAddr = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, fieldInst->mDataIdx /*, fieldDef->mName*/);
  12133. }
  12134. else
  12135. {
  12136. AssertErrorState();
  12137. }
  12138. auto assignValue = GetFieldInitializerValue(fieldInst);
  12139. if ((fieldAddr) && (assignValue))
  12140. mBfIRBuilder->CreateStore(assignValue.mValue, fieldAddr);
  12141. }
  12142. }
  12143. if (hadInlineInitBlock)
  12144. {
  12145. RestoreScopeState();
  12146. // This gets set to false because of AddScope but we actually are still in the head block
  12147. mCurMethodState->mInHeadScope = true;
  12148. }
  12149. }
  12150. else // Autocomplete case
  12151. {
  12152. // The reason we can't just do the 'normal' path for this is that the BfTypeInstance here is NOT the
  12153. // autocomplete type instance, so FieldInstance initializer values contain expressions from the full
  12154. // resolve pass, NOT the autocomplete expression
  12155. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  12156. {
  12157. if (tempTypeDef->mFullName == typeDef->mFullName)
  12158. {
  12159. for (auto fieldDef : tempTypeDef->mFields)
  12160. {
  12161. if ((!fieldDef->mIsStatic) && (fieldDef->mInitializer != NULL) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  12162. {
  12163. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(fieldDef->mInitializer, BfSourceElementType_Normal);
  12164. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(fieldDef->mInitializer);
  12165. auto wantType = ResolveTypeRef(fieldDef->mTypeRef);
  12166. if ((wantType != NULL) &&
  12167. ((wantType->IsVar()) || (wantType->IsLet()) || (wantType->IsRef())))
  12168. wantType = NULL;
  12169. CreateValueFromExpression(fieldDef->mInitializer, wantType, BfEvalExprFlags_FieldInitializer);
  12170. }
  12171. }
  12172. }
  12173. }
  12174. // Mark fields from full type with initializers as initialized, to give proper initialization errors within ctor
  12175. for (auto fieldDef : typeDef->mFields)
  12176. {
  12177. if ((!fieldDef->mIsConst) && (!fieldDef->mIsStatic) && (fieldDef->mInitializer != NULL))
  12178. {
  12179. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  12180. if (fieldDef->mInitializer != NULL)
  12181. MarkFieldInitialized(fieldInst);
  12182. }
  12183. }
  12184. }
  12185. }
  12186. // Call base ctor (if applicable)
  12187. BfTypeInstance* targetType = NULL;
  12188. BfAstNode* targetRefNode = NULL;
  12189. if (ctorDeclaration != NULL)
  12190. targetRefNode = ctorDeclaration->mInitializer;
  12191. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(targetRefNode))
  12192. targetRefNode = invocationExpr->mTarget;
  12193. if (baseCtorNode != NULL)
  12194. {
  12195. UpdateSrcPos(baseCtorNode);
  12196. }
  12197. if ((ctorDeclaration != NULL) && (ctorDeclaration->mInitializer != NULL))
  12198. {
  12199. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorDeclaration->mInitializer->mTarget);
  12200. targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  12201. }
  12202. else if ((mCurTypeInstance->mBaseType != NULL) && (!mCurTypeInstance->IsUnspecializedType()))
  12203. {
  12204. auto baseType = mCurTypeInstance->mBaseType;
  12205. if ((!mCurTypeInstance->IsTypedPrimitive()) &&
  12206. (baseType->mTypeDef != mCompiler->mValueTypeTypeDef) &&
  12207. (baseType->mTypeDef != mCompiler->mBfObjectTypeDef))
  12208. {
  12209. // Try to find a ctor without any params first
  12210. bool foundBaseCtor = false;
  12211. bool hadCtorWithAllDefaults = false;
  12212. for (int pass = 0; pass < 2; pass++)
  12213. {
  12214. for (auto checkMethodDef : baseType->mTypeDef->mMethods)
  12215. {
  12216. bool allowPriv = checkMethodDef->mProtection != BfProtection_Private;
  12217. // Allow calling of the default base ctor if it is implicitly defined
  12218. if ((checkMethodDef->mMethodDeclaration == NULL) && (pass == 1) && (!hadCtorWithAllDefaults))
  12219. allowPriv = true;
  12220. if ((checkMethodDef->mMethodType == BfMethodType_Ctor) && (!checkMethodDef->mIsStatic) && (allowPriv))
  12221. {
  12222. if (checkMethodDef->mParams.size() == 0)
  12223. {
  12224. foundBaseCtor = true;
  12225. if (HasCompiledOutput())
  12226. {
  12227. SizedArray<BfIRValue, 1> args;
  12228. auto ctorBodyMethodInstance = GetMethodInstance(mCurTypeInstance->mBaseType, checkMethodDef, BfTypeVector());
  12229. if (!mCurTypeInstance->mBaseType->IsValuelessType())
  12230. {
  12231. auto basePtr = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapTypeInstPtr(mCurTypeInstance->mBaseType));
  12232. args.push_back(basePtr);
  12233. }
  12234. AddCallDependency(ctorBodyMethodInstance.mMethodInstance, true);
  12235. auto callInst = mBfIRBuilder->CreateCall(ctorBodyMethodInstance.mFunc, args);
  12236. auto callingConv = GetCallingConvention(ctorBodyMethodInstance.mMethodInstance->GetOwner(), ctorBodyMethodInstance.mMethodInstance->mMethodDef);
  12237. if (callingConv != BfIRCallingConv_CDecl)
  12238. mBfIRBuilder->SetCallCallingConv(callInst, callingConv);
  12239. // if (!mCurTypeInstance->mBaseType->IsValuelessType())
  12240. // mBfIRBuilder->SetCallCallingConv(callInst, BfIRCallingConv_ThisCall);
  12241. break;
  12242. }
  12243. }
  12244. else if ((checkMethodDef->mParams[0]->mParamDeclaration != NULL) && (checkMethodDef->mParams[0]->mParamDeclaration->mInitializer != NULL))
  12245. hadCtorWithAllDefaults = true;
  12246. }
  12247. }
  12248. if (foundBaseCtor)
  12249. break;
  12250. }
  12251. if (!foundBaseCtor)
  12252. {
  12253. targetType = mCurTypeInstance->mBaseType;
  12254. if (ctorDeclaration != NULL)
  12255. targetRefNode = ctorDeclaration->mThisToken;
  12256. else if (typeDef->mTypeDeclaration != NULL)
  12257. targetRefNode = typeDef->mTypeDeclaration->mNameNode;
  12258. }
  12259. }
  12260. }
  12261. if (methodDef->mHasAppend)
  12262. {
  12263. mCurMethodState->mCurAppendAlign = methodInstance->mAppendAllocAlign;
  12264. }
  12265. if (targetType != NULL)
  12266. {
  12267. auto autoComplete = mCompiler->GetAutoComplete();
  12268. auto wasCapturingMethodInfo = (autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo);
  12269. if ((autoComplete != NULL) && (ctorDeclaration != NULL) && (ctorDeclaration->mInitializer != NULL))
  12270. {
  12271. auto invocationExpr = ctorDeclaration->mInitializer;
  12272. autoComplete->CheckInvocation(invocationExpr, invocationExpr->mOpenParen, invocationExpr->mCloseParen, invocationExpr->mCommas);
  12273. }
  12274. BfType* targetThisType = targetType;
  12275. auto target = Cast(targetRefNode, GetThis(), targetThisType);
  12276. BfExprEvaluator exprEvaluator(this);
  12277. BfResolvedArgs argValues;
  12278. if ((ctorDeclaration != NULL) && (ctorDeclaration->mInitializer != NULL))
  12279. {
  12280. argValues.Init(&ctorDeclaration->mInitializer->mArguments);
  12281. if (gDebugStuff)
  12282. {
  12283. OutputDebugStrF("Expr: %@ %d\n", argValues.mArguments->mVals, argValues.mArguments->mSize);
  12284. }
  12285. }
  12286. exprEvaluator.ResolveArgValues(argValues, BfResolveArgFlag_DeferParamEval);
  12287. BfTypedValue appendIdxVal;
  12288. if (methodDef->mHasAppend)
  12289. {
  12290. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  12291. BF_ASSERT(localVar->mName == "appendIdx");
  12292. auto intRefType = CreateRefType(localVar->mResolvedType);
  12293. appendIdxVal = BfTypedValue(localVar->mValue, intRefType);
  12294. mCurMethodState->mCurAppendAlign = 1; // Don't make any assumptions about how the base leaves the alignment
  12295. }
  12296. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, methodDef->mHasAppend, &appendIdxVal);
  12297. if (autoComplete != NULL)
  12298. {
  12299. if ((wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo))
  12300. {
  12301. if (autoComplete->mMethodMatchInfo != NULL)
  12302. autoComplete->mIsCapturingMethodMatchInfo = true;
  12303. else
  12304. autoComplete->mIsCapturingMethodMatchInfo = false;
  12305. }
  12306. else
  12307. autoComplete->mIsCapturingMethodMatchInfo = false;
  12308. }
  12309. }
  12310. }
  12311. void BfModule::EmitEnumToStringBody()
  12312. {
  12313. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  12314. auto strVal = CreateAlloca(stringType);
  12315. auto int64StructType = GetPrimitiveStructType(BfTypeCode_Int64);
  12316. BfExprEvaluator exprEvaluator(this);
  12317. auto stringDestAddr = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  12318. BfIRBlock appendBlock = mBfIRBuilder->CreateBlock("append");
  12319. BfIRBlock noMatchBlock = mBfIRBuilder->CreateBlock("noMatch");
  12320. BfIRBlock endBlock = mBfIRBuilder->CreateBlock("end");
  12321. BfType* discriminatorType = NULL;
  12322. BfTypedValue rawPayload;
  12323. BfIRValue enumVal;
  12324. if (mCurTypeInstance->IsPayloadEnum())
  12325. {
  12326. discriminatorType = mCurTypeInstance->GetDiscriminatorType();
  12327. auto enumTypedValue = ExtractValue(GetThis(), NULL, 2);
  12328. enumTypedValue = LoadValue(enumTypedValue);
  12329. enumVal = enumTypedValue.mValue;
  12330. rawPayload = ExtractValue(GetThis(), NULL, 1);
  12331. }
  12332. else
  12333. enumVal = mBfIRBuilder->GetArgument(0);
  12334. Array<BfType*> paramTypes;
  12335. paramTypes.Add(stringType);
  12336. auto appendModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  12337. auto switchVal = mBfIRBuilder->CreateSwitch(enumVal, noMatchBlock, (int)mCurTypeInstance->mFieldInstances.size());
  12338. HashSet<int64> handledCases;
  12339. for (auto& fieldInstance : mCurTypeInstance->mFieldInstances)
  12340. {
  12341. if (fieldInstance.mIsEnumPayloadCase)
  12342. {
  12343. int tagId = -fieldInstance.mDataIdx - 1;
  12344. BfIRBlock caseBlock = mBfIRBuilder->CreateBlock("case");
  12345. mBfIRBuilder->AddBlock(caseBlock);
  12346. mBfIRBuilder->SetInsertPoint(caseBlock);
  12347. BF_ASSERT(discriminatorType->IsPrimitiveType());
  12348. auto constVal = mBfIRBuilder->CreateConst(((BfPrimitiveType*)discriminatorType)->mTypeDef->mTypeCode, tagId);
  12349. mBfIRBuilder->AddSwitchCase(switchVal, constVal, caseBlock);
  12350. auto caseStr = GetStringObjectValue(fieldInstance.GetFieldDef()->mName);
  12351. auto stringDestVal = LoadValue(stringDestAddr);
  12352. SizedArray<BfIRValue, 2> args;
  12353. args.Add(stringDestVal.mValue);
  12354. args.Add(caseStr);
  12355. exprEvaluator.CreateCall(appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  12356. auto payloadType = fieldInstance.mResolvedType->ToTypeInstance();
  12357. BF_ASSERT(payloadType->IsTuple());
  12358. if (payloadType->mFieldInstances.size() != 0)
  12359. {
  12360. auto payload = rawPayload;
  12361. if (payload.mType != payloadType)
  12362. {
  12363. payload = Cast(NULL, payload, payloadType, BfCastFlags_Force);
  12364. }
  12365. auto toStringMethod = GetMethodByName(payloadType->ToTypeInstance(), "ToString");
  12366. SizedArray<BfIRValue, 2> irArgs;
  12367. exprEvaluator.PushThis(NULL, payload, toStringMethod.mMethodInstance, irArgs);
  12368. stringDestVal = LoadValue(stringDestAddr);
  12369. irArgs.Add(stringDestVal.mValue);
  12370. exprEvaluator.CreateCall(toStringMethod.mMethodInstance, toStringMethod.mFunc, true, irArgs);
  12371. }
  12372. mBfIRBuilder->CreateBr(endBlock);
  12373. continue;
  12374. }
  12375. if (fieldInstance.mConstIdx == -1)
  12376. continue;
  12377. auto constant = mCurTypeInstance->mConstHolder->GetConstantById(fieldInstance.mConstIdx);
  12378. if (!handledCases.TryAdd(constant->mInt64, NULL))
  12379. {
  12380. // Duplicate
  12381. continue;
  12382. }
  12383. BfIRBlock caseBlock = mBfIRBuilder->CreateBlock("case");
  12384. mBfIRBuilder->AddBlock(caseBlock);
  12385. mBfIRBuilder->SetInsertPoint(caseBlock);
  12386. BfIRValue constVal = ConstantToCurrent(constant, mCurTypeInstance->mConstHolder, mCurTypeInstance);
  12387. mBfIRBuilder->AddSwitchCase(switchVal, constVal, caseBlock);
  12388. auto caseStr = GetStringObjectValue(fieldInstance.GetFieldDef()->mName);
  12389. mBfIRBuilder->CreateStore(caseStr, strVal);
  12390. mBfIRBuilder->CreateBr(appendBlock);
  12391. }
  12392. mBfIRBuilder->AddBlock(appendBlock);
  12393. mBfIRBuilder->SetInsertPoint(appendBlock);
  12394. SizedArray<BfIRValue, 2> args;
  12395. auto stringDestVal = LoadValue(stringDestAddr);
  12396. args.Add(stringDestVal.mValue);
  12397. args.Add(mBfIRBuilder->CreateLoad(strVal));
  12398. exprEvaluator.CreateCall(appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  12399. mBfIRBuilder->CreateBr(endBlock);
  12400. mBfIRBuilder->AddBlock(noMatchBlock);
  12401. mBfIRBuilder->SetInsertPoint(noMatchBlock);
  12402. auto int64Val = mBfIRBuilder->CreateNumericCast(enumVal, false, BfTypeCode_Int64);
  12403. auto toStringModuleMethodInstance = GetMethodByName(int64StructType, "ToString", 1);
  12404. args.clear();
  12405. args.Add(int64Val);
  12406. stringDestVal = LoadValue(stringDestAddr);
  12407. args.Add(stringDestVal.mValue);
  12408. exprEvaluator.CreateCall(toStringModuleMethodInstance.mMethodInstance, toStringModuleMethodInstance.mFunc, false, args);
  12409. mBfIRBuilder->CreateBr(endBlock);
  12410. mBfIRBuilder->AddBlock(endBlock);
  12411. mBfIRBuilder->SetInsertPoint(endBlock);
  12412. }
  12413. void BfModule::EmitTupleToStringBody()
  12414. {
  12415. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  12416. BfExprEvaluator exprEvaluator(this);
  12417. auto stringDestRef = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  12418. Array<BfType*> paramTypes;
  12419. paramTypes.Add(GetPrimitiveType(BfTypeCode_Char8));
  12420. auto appendCharModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  12421. paramTypes.Clear();
  12422. paramTypes.Add(stringType);
  12423. auto appendModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  12424. auto _AppendChar = [&](char c)
  12425. {
  12426. SizedArray<BfIRValue, 2> args;
  12427. auto stringDestVal = LoadValue(stringDestRef);
  12428. args.Add(stringDestVal.mValue);
  12429. args.Add(mBfIRBuilder->CreateConst(BfTypeCode_Char8, (int)c));
  12430. exprEvaluator.CreateCall(appendCharModuleMethodInstance.mMethodInstance, appendCharModuleMethodInstance.mFunc, false, args);
  12431. };
  12432. int fieldIdx = 0;
  12433. auto thisValue = GetThis();
  12434. auto toStringModuleMethodInstance = GetMethodByName(mContext->mBfObjectType, "ToString", 1);
  12435. auto toStringSafeModuleMethodInstance = GetMethodByName(mContext->mBfObjectType, "ToString", 2);
  12436. BfIRValue commaStr;
  12437. auto iPrintableType = ResolveTypeDef(mCompiler->mIPrintableTypeDef)->ToTypeInstance();
  12438. auto printModuleMethodInstance = GetMethodByName(iPrintableType, "Print");
  12439. _AppendChar('(');
  12440. for (auto& fieldInstance : mCurTypeInstance->mFieldInstances)
  12441. {
  12442. if (fieldInstance.mDataIdx == -1)
  12443. continue;
  12444. if (fieldIdx > 0)
  12445. {
  12446. if (!commaStr)
  12447. commaStr = GetStringObjectValue(", ");
  12448. SizedArray<BfIRValue, 2> args;
  12449. auto stringDestVal = LoadValue(stringDestRef);
  12450. args.Add(stringDestVal.mValue);
  12451. args.Add(commaStr);
  12452. exprEvaluator.CreateCall(appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  12453. }
  12454. fieldIdx++;
  12455. if (fieldInstance.mResolvedType->IsValuelessType())
  12456. continue;
  12457. BfTypedValue fieldValue = ExtractValue(thisValue, &fieldInstance, fieldInstance.mDataIdx);
  12458. if (fieldValue.mType->IsPrimitiveType())
  12459. {
  12460. fieldValue.mType = GetPrimitiveStructType(((BfPrimitiveType*)fieldValue.mType)->mTypeDef->mTypeCode);
  12461. }
  12462. auto typeInstance = fieldValue.mType->ToTypeInstance();
  12463. if ((typeInstance != NULL) && (TypeIsSubTypeOf(typeInstance, iPrintableType, false)))
  12464. {
  12465. BfExprEvaluator exprEvaluator(this);
  12466. SizedArray<BfResolvedArg, 0> resolvedArgs;
  12467. BfMethodMatcher methodMatcher(NULL, this, printModuleMethodInstance.mMethodInstance, resolvedArgs);
  12468. methodMatcher.mBestMethodDef = printModuleMethodInstance.mMethodInstance->mMethodDef;
  12469. methodMatcher.mBestMethodTypeInstance = iPrintableType;
  12470. methodMatcher.TryDevirtualizeCall(fieldValue);
  12471. BfTypedValue callVal = Cast(NULL, fieldValue, methodMatcher.mBestMethodTypeInstance);
  12472. BfResolvedArg resolvedArg;
  12473. auto stringDestVal = LoadValue(stringDestRef);
  12474. resolvedArg.mTypedValue = stringDestVal;
  12475. resolvedArg.mResolvedType = stringDestVal.mType;
  12476. resolvedArgs.Add(resolvedArg);
  12477. exprEvaluator.CreateCall(&methodMatcher, callVal);
  12478. continue;
  12479. }
  12480. if (fieldValue.mType->IsObjectOrInterface())
  12481. {
  12482. BF_ASSERT(!fieldValue.IsAddr());
  12483. SizedArray<BfIRValue, 2> args;
  12484. args.Add(mBfIRBuilder->CreateBitCast(fieldValue.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType)));
  12485. auto stringDestVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  12486. stringDestVal = LoadValue(stringDestVal);
  12487. args.Add(stringDestVal.mValue);
  12488. exprEvaluator.CreateCall(toStringSafeModuleMethodInstance.mMethodInstance, toStringSafeModuleMethodInstance.mFunc, false, args);
  12489. continue;
  12490. }
  12491. BfExprEvaluator exprEvaluator(this);
  12492. SizedArray<BfResolvedArg, 0> resolvedArgs;
  12493. BfMethodMatcher methodMatcher(NULL, this, toStringModuleMethodInstance.mMethodInstance, resolvedArgs);
  12494. methodMatcher.mBestMethodDef = toStringModuleMethodInstance.mMethodInstance->mMethodDef;
  12495. methodMatcher.mBestMethodTypeInstance = mContext->mBfObjectType;
  12496. methodMatcher.TryDevirtualizeCall(fieldValue);
  12497. if (methodMatcher.mBestMethodTypeInstance == mContext->mBfObjectType)
  12498. {
  12499. AddCallDependency(appendModuleMethodInstance.mMethodInstance);
  12500. AddDependency(fieldValue.mType, mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  12501. // Just append the type name
  12502. String typeName = TypeToString(fieldInstance.mResolvedType);
  12503. auto strVal = GetStringObjectValue(typeName);
  12504. SizedArray<BfIRValue, 2> args;
  12505. auto stringDestVal = LoadValue(stringDestRef);
  12506. args.Add(stringDestVal.mValue);
  12507. args.Add(strVal);
  12508. exprEvaluator.CreateCall(appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  12509. continue;
  12510. }
  12511. BfTypedValue callVal = Cast(NULL, fieldValue, methodMatcher.mBestMethodTypeInstance);
  12512. BfResolvedArg resolvedArg;
  12513. auto stringDestVal = LoadValue(stringDestRef);
  12514. resolvedArg.mTypedValue = stringDestVal;
  12515. resolvedArg.mResolvedType = stringDestVal.mType;
  12516. resolvedArgs.Add(resolvedArg);
  12517. exprEvaluator.CreateCall(&methodMatcher, callVal);
  12518. }
  12519. _AppendChar(')');
  12520. }
  12521. void BfModule::EmitIteratorBlock(bool& skipBody)
  12522. {
  12523. auto methodInstance = mCurMethodInstance;
  12524. auto methodDef = methodInstance->mMethodDef;
  12525. auto methodDeclaration = methodDef->GetMethodDeclaration();
  12526. auto typeDef = mCurTypeInstance->mTypeDef;
  12527. BfType* innerRetType = NULL;
  12528. BfTypeInstance* usingInterface = NULL;
  12529. auto retTypeInst = mCurMethodInstance->mReturnType->ToGenericTypeInstance();
  12530. if (retTypeInst != NULL)
  12531. {
  12532. if ((retTypeInst->mTypeDef == mCompiler->mGenericIEnumerableTypeDef) ||
  12533. (retTypeInst->mTypeDef == mCompiler->mGenericIEnumeratorTypeDef))
  12534. {
  12535. innerRetType = retTypeInst->mTypeGenericArguments[0];
  12536. }
  12537. }
  12538. if (innerRetType == NULL)
  12539. {
  12540. Fail("Methods with yields must return either System.IEnumerable<T> or System.IEnumerator<T>", methodDeclaration->mReturnType);
  12541. return;
  12542. }
  12543. auto blockBody = BfNodeDynCast<BfBlock>(methodDeclaration->mBody);
  12544. if (blockBody == NULL)
  12545. return;
  12546. }
  12547. void BfModule::EmitGCMarkValue(BfTypedValue markVal, BfModuleMethodInstance markFromGCThreadMethodInstance)
  12548. {
  12549. auto fieldTypeInst = markVal.mType->ToTypeInstance();
  12550. if (fieldTypeInst == NULL)
  12551. return;
  12552. if (!markVal.mType->IsComposite())
  12553. markVal = LoadValue(markVal);
  12554. BfExprEvaluator exprEvaluator(this);
  12555. PopulateType(markVal.mType, BfPopulateType_Data);
  12556. if (markVal.mType->IsObjectOrInterface())
  12557. {
  12558. BfIRValue val = markVal.mValue;
  12559. val = mBfIRBuilder->CreateBitCast(val, mBfIRBuilder->MapType(mContext->mBfObjectType));
  12560. SizedArray<BfIRValue, 1> args;
  12561. args.push_back(val);
  12562. exprEvaluator.CreateCall(markFromGCThreadMethodInstance.mMethodInstance, markFromGCThreadMethodInstance.mFunc, false, args);
  12563. }
  12564. else if ((fieldTypeInst->IsComposite()) && (!fieldTypeInst->IsTypedPrimitive()))
  12565. {
  12566. auto markMemberMethodInstance = GetMethodByName(fieldTypeInst, BF_METHODNAME_MARKMEMBERS, 0, true);
  12567. if (markMemberMethodInstance)
  12568. {
  12569. SizedArray<BfIRValue, 1> args;
  12570. //(1, markVal.mValue);
  12571. //exprEvaluator.PushArg(markVal, args);
  12572. exprEvaluator.PushThis(NULL, markVal, markMemberMethodInstance.mMethodInstance, args);
  12573. exprEvaluator.CreateCall(markMemberMethodInstance.mMethodInstance, markMemberMethodInstance.mFunc, false, args);
  12574. }
  12575. }
  12576. }
  12577. void BfModule::CallChainedMethods(BfMethodInstance* methodInstance, bool reverse)
  12578. {
  12579. Array<BfMethodInstance*> methodInstances;
  12580. for (int methodIdx = 0; methodIdx < (int)mCurTypeInstance->mMethodInstanceGroups.size(); methodIdx++)
  12581. {
  12582. auto& methodInstGroup = mCurTypeInstance->mMethodInstanceGroups[methodIdx];
  12583. auto chainedMethodInst = methodInstGroup.mDefault;
  12584. if ((chainedMethodInst != NULL) && (chainedMethodInst->mChainType == BfMethodChainType_ChainMember))
  12585. {
  12586. if ((chainedMethodInst->mMethodDef->mIsStatic == methodInstance->mMethodDef->mIsStatic) &&
  12587. (CompareMethodSignatures(methodInstance, chainedMethodInst)))
  12588. {
  12589. methodInstances.push_back(chainedMethodInst);
  12590. }
  12591. }
  12592. }
  12593. std::stable_sort(methodInstances.begin(), methodInstances.end(),
  12594. [&](BfMethodInstance* lhs, BfMethodInstance* rhs)
  12595. {
  12596. bool isBetter;
  12597. bool isWorse;
  12598. CompareDeclTypes(lhs->mMethodDef->mDeclaringType, rhs->mMethodDef->mDeclaringType, isBetter, isWorse);
  12599. if (isBetter == isWorse)
  12600. {
  12601. return false;
  12602. }
  12603. return isWorse;
  12604. });
  12605. if (reverse)
  12606. std::reverse(methodInstances.begin(), methodInstances.end());
  12607. for (auto chainedMethodInst : methodInstances)
  12608. {
  12609. auto declModule = this;
  12610. BfGetMethodInstanceFlags flags = BfGetMethodInstanceFlag_None;
  12611. auto moduleMethodInst = declModule->GetMethodInstance(mCurTypeInstance, chainedMethodInst->mMethodDef, BfTypeVector(), flags);
  12612. BfExprEvaluator exprEvaluator(this);
  12613. SizedArray<BfIRValue, 1> args;
  12614. exprEvaluator.PushThis(chainedMethodInst->mMethodDef->GetRefNode(), GetThis(), chainedMethodInst, args);
  12615. exprEvaluator.CreateCall(moduleMethodInst.mMethodInstance, moduleMethodInst.mFunc, true, args);
  12616. }
  12617. }
  12618. void BfModule::AddHotDataReferences(BfHotDataReferenceBuilder* builder)
  12619. {
  12620. BF_ASSERT(mCurMethodInstance->mIsReified);
  12621. if (mCurTypeInstance->mHotTypeData == NULL)
  12622. mCurTypeInstance->mHotTypeData = new BfHotTypeData();
  12623. auto hotMethod = mCurMethodInstance->mHotMethod;
  12624. for (auto depData : hotMethod->mReferences)
  12625. {
  12626. // Only virtual decls are allowed to already be there
  12627. BF_ASSERT((depData->mDataKind == BfHotDepDataKind_VirtualDecl) || (depData->mDataKind == BfHotDepDataKind_DupMethod));
  12628. }
  12629. BF_ASSERT(hotMethod->mSrcTypeVersion != NULL);
  12630. int prevSize = (int)hotMethod->mReferences.size();
  12631. int refCount = (int)(prevSize + builder->mUsedData.size() + builder->mCalledMethods.size() + builder->mDevirtualizedCalledMethods.size());
  12632. if (!mCurMethodInstance->mMethodDef->mIsStatic)
  12633. refCount++;
  12634. hotMethod->mReferences.Reserve(refCount);
  12635. if (!mCurMethodInstance->mMethodDef->mIsStatic)
  12636. {
  12637. auto hotThis = mCompiler->mHotData->GetThisType(mCurMethodInstance->GetOwner()->mHotTypeData->GetLatestVersion());
  12638. hotThis->mRefCount++;
  12639. hotMethod->mReferences.Insert(0, hotThis);
  12640. prevSize++;
  12641. }
  12642. for (auto val : builder->mAllocatedData)
  12643. {
  12644. auto hotAllocation = mCompiler->mHotData->GetAllocation(val);
  12645. hotMethod->mReferences.Add(hotAllocation);
  12646. }
  12647. for (auto val : builder->mUsedData)
  12648. hotMethod->mReferences.Add(val);
  12649. for (auto val : builder->mCalledMethods)
  12650. hotMethod->mReferences.Add(val);
  12651. for (auto val : builder->mDevirtualizedCalledMethods)
  12652. {
  12653. auto devirtualizedMethod = mCompiler->mHotData->GetDevirtualizedMethod(val);
  12654. hotMethod->mReferences.Add(devirtualizedMethod);
  12655. }
  12656. for (auto val : builder->mFunctionPtrs)
  12657. {
  12658. auto funcRef = mCompiler->mHotData->GetFunctionReference(val);
  12659. hotMethod->mReferences.Add(funcRef);
  12660. }
  12661. for (auto val : builder->mInnerMethods)
  12662. {
  12663. auto innerMethod = mCompiler->mHotData->GetInnerMethod(val);
  12664. hotMethod->mReferences.Add(innerMethod);
  12665. }
  12666. for (int refIdx = prevSize; refIdx < (int)hotMethod->mReferences.size(); refIdx++)
  12667. {
  12668. auto depData = hotMethod->mReferences[refIdx];
  12669. BF_ASSERT(depData != NULL);
  12670. depData->mRefCount++;
  12671. }
  12672. //hotMethod->mReferences.Sort([](BfHotDepData* lhs, BfHotDepData* rhs) { return lhs < rhs; });
  12673. }
  12674. void BfModule::ProcessMethod_SetupParams(BfMethodInstance* methodInstance, BfType* thisType, bool wantsDIData, SizedArrayImpl<BfIRMDNode>* diParams)
  12675. {
  12676. auto methodDef = methodInstance->mMethodDef;
  12677. auto methodDeclaration = methodDef->mMethodDeclaration;
  12678. bool isThisStruct = false;
  12679. if (thisType != NULL)
  12680. isThisStruct = thisType->IsStruct() && !thisType->IsTypedPrimitive();
  12681. int argIdx = 0;
  12682. if (methodInstance->HasStructRet())
  12683. argIdx++;
  12684. if (!methodDef->mIsStatic)
  12685. {
  12686. BfLocalVariable* paramVar = new BfLocalVariable();
  12687. paramVar->mResolvedType = thisType;
  12688. paramVar->mName = "this";
  12689. if (!thisType->IsValuelessType())
  12690. paramVar->mValue = mBfIRBuilder->GetArgument(argIdx);
  12691. else
  12692. paramVar->mValue = mBfIRBuilder->GetFakeVal();
  12693. if ((thisType->IsComposite()) && (!methodDef->HasNoThisSplat()))
  12694. {
  12695. if (thisType->IsSplattable())
  12696. paramVar->mIsSplat = true;
  12697. else
  12698. paramVar->mIsLowered = thisType->GetLoweredType() != BfTypeCode_None;
  12699. }
  12700. auto thisTypeInst = thisType->ToTypeInstance();
  12701. paramVar->mIsStruct = isThisStruct;
  12702. paramVar->mAddr = BfIRValue();
  12703. paramVar->mIsThis = true;
  12704. paramVar->mParamIdx = -1;
  12705. if ((methodDef->mMethodType == BfMethodType_Ctor) && (mCurTypeInstance->IsStruct()))
  12706. {
  12707. paramVar->mIsAssigned = false;
  12708. }
  12709. else
  12710. {
  12711. paramVar->mIsAssigned = true;
  12712. }
  12713. paramVar->mReadFromId = -1;
  12714. paramVar->Init();
  12715. if (methodDeclaration == NULL)
  12716. UseDefaultSrcPos();
  12717. AddLocalVariableDef(paramVar);
  12718. if (!thisType->IsValuelessType())
  12719. {
  12720. if (wantsDIData)
  12721. {
  12722. BfType* thisPtrType = thisType;
  12723. auto diType = mBfIRBuilder->DbgGetType(thisPtrType);
  12724. if (!thisType->IsValueType())
  12725. diType = mBfIRBuilder->DbgCreateArtificialType(diType);
  12726. diParams->push_back(diType);
  12727. }
  12728. if (paramVar->mIsSplat)
  12729. {
  12730. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  12731. }
  12732. else
  12733. {
  12734. argIdx++;
  12735. }
  12736. }
  12737. }
  12738. bool hadParams = false;
  12739. bool hasDefault = false;
  12740. int compositeVariableIdx = -1;
  12741. int paramIdx = 0;
  12742. for (paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  12743. {
  12744. // We already issues a type error for this param if we had one in declaration processing
  12745. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  12746. BfLocalVariable* paramVar = new BfLocalVariable();
  12747. bool isParamSkipped = methodInstance->IsParamSkipped(paramIdx);
  12748. BfType* unresolvedType = methodInstance->GetParamType(paramIdx, false);
  12749. if (unresolvedType == NULL)
  12750. {
  12751. AssertErrorState();
  12752. unresolvedType = mContext->mBfObjectType;
  12753. paramVar->mParamFailed = true;
  12754. }
  12755. auto resolvedType = methodInstance->GetParamType(paramIdx, true);
  12756. prevIgnoreErrors.Restore();
  12757. PopulateType(resolvedType, BfPopulateType_Declaration);
  12758. paramVar->mResolvedType = resolvedType;
  12759. paramVar->mName = methodInstance->GetParamName(paramIdx);
  12760. paramVar->mNameNode = methodInstance->GetParamNameNode(paramIdx);
  12761. if (!isParamSkipped)
  12762. {
  12763. paramVar->mValue = mBfIRBuilder->GetArgument(argIdx);
  12764. if (resolvedType->IsMethodRef())
  12765. {
  12766. paramVar->mIsSplat = true;
  12767. }
  12768. else if (resolvedType->IsComposite() && resolvedType->IsSplattable())
  12769. {
  12770. int splatCount = resolvedType->GetSplatCount();
  12771. if (argIdx + splatCount <= mCompiler->mOptions.mMaxSplatRegs)
  12772. paramVar->mIsSplat = true;
  12773. }
  12774. }
  12775. else
  12776. {
  12777. paramVar->mIsSplat = true; // Treat skipped (valueless) as a splat
  12778. paramVar->mValue = mBfIRBuilder->GetFakeVal();
  12779. }
  12780. paramVar->mIsLowered = resolvedType->GetLoweredType() != BfTypeCode_None;
  12781. paramVar->mIsStruct = resolvedType->IsComposite() && !resolvedType->IsTypedPrimitive();
  12782. paramVar->mParamIdx = paramIdx;
  12783. paramVar->mIsImplicitParam = methodInstance->IsImplicitCapture(paramIdx);
  12784. paramVar->mReadFromId = 0;
  12785. if (resolvedType->IsRef())
  12786. {
  12787. auto refType = (BfRefType*)resolvedType;
  12788. paramVar->mIsAssigned = refType->mRefKind != BfRefType::RefKind_Out;
  12789. }
  12790. else
  12791. {
  12792. paramVar->mIsAssigned = true;
  12793. if (methodDef->mMethodType != BfMethodType_Mixin)
  12794. paramVar->mIsReadOnly = true;
  12795. }
  12796. if (paramVar->mResolvedType->IsGenericParam())
  12797. {
  12798. auto genericParamInst = GetGenericParamInstance((BfGenericParamType*)paramVar->mResolvedType);
  12799. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  12800. {
  12801. auto typedVal = GetDefaultTypedValue(genericParamInst->mTypeConstraint, false, BfDefaultValueKind_Undef);
  12802. paramVar->mResolvedType = typedVal.mType;
  12803. paramVar->mConstValue = typedVal.mValue;
  12804. }
  12805. }
  12806. if (paramVar->mResolvedType->IsConstExprValue())
  12807. {
  12808. BfConstExprValueType* constExprValueType = (BfConstExprValueType*)paramVar->mResolvedType;
  12809. auto unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance);
  12810. auto unspecParamType = unspecializedMethodInstance->GetParamType(paramIdx);
  12811. BF_ASSERT(unspecParamType->IsGenericParam());
  12812. if (unspecParamType->IsGenericParam())
  12813. {
  12814. BfGenericParamType* genericParamType = (BfGenericParamType*)unspecParamType;
  12815. if (genericParamType->mGenericParamKind == BfGenericParamKind_Method)
  12816. {
  12817. auto genericParamInst = unspecializedMethodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  12818. if (genericParamInst->mTypeConstraint != NULL)
  12819. {
  12820. BfExprEvaluator exprEvaluator(this);
  12821. exprEvaluator.mExpectingType = genericParamInst->mTypeConstraint;
  12822. exprEvaluator.GetLiteral(NULL, constExprValueType->mValue);
  12823. auto checkType = genericParamInst->mTypeConstraint;
  12824. if (checkType->IsTypedPrimitive())
  12825. checkType = checkType->GetUnderlyingType();
  12826. if (exprEvaluator.mResult.mType == checkType)
  12827. {
  12828. paramVar->mResolvedType = genericParamInst->mTypeConstraint;
  12829. paramVar->mConstValue = exprEvaluator.mResult.mValue;
  12830. BF_ASSERT(paramVar->mConstValue.IsConst());
  12831. }
  12832. else
  12833. {
  12834. AssertErrorState();
  12835. paramVar->mResolvedType = genericParamInst->mTypeConstraint;
  12836. paramVar->mConstValue = GetDefaultValue(genericParamInst->mTypeConstraint);
  12837. }
  12838. }
  12839. }
  12840. }
  12841. //BF_ASSERT(!paramVar->mResolvedType->IsConstExprValue());
  12842. if (paramVar->mResolvedType->IsConstExprValue())
  12843. {
  12844. Fail("Invalid use of constant expression", methodInstance->GetParamTypeRef(paramIdx));
  12845. //AssertErrorState();
  12846. paramVar->mResolvedType = GetPrimitiveType(BfTypeCode_IntPtr);
  12847. paramVar->mConstValue = GetDefaultValue(paramVar->mResolvedType);
  12848. }
  12849. }
  12850. if (methodInstance->GetParamKind(paramIdx) == BfParamKind_DelegateParam)
  12851. {
  12852. if (compositeVariableIdx == -1)
  12853. {
  12854. compositeVariableIdx = (int)mCurMethodState->mLocals.size();
  12855. BfLocalVariable* localVar = new BfLocalVariable();
  12856. auto paramInst = &methodInstance->mParams[paramIdx];
  12857. auto paramDef = methodDef->mParams[paramInst->mParamDefIdx];
  12858. localVar->mName = paramDef->mName;
  12859. localVar->mResolvedType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_NoResolveGenericParam);
  12860. localVar->mCompositeCount = 0;
  12861. DoAddLocalVariable(localVar);
  12862. }
  12863. mCurMethodState->mLocals[compositeVariableIdx]->mCompositeCount++;
  12864. }
  12865. CheckVariableDef(paramVar);
  12866. paramVar->Init();
  12867. AddLocalVariableDef(paramVar);
  12868. if (!isParamSkipped)
  12869. {
  12870. if (wantsDIData)
  12871. diParams->push_back(mBfIRBuilder->DbgGetType(resolvedType));
  12872. if (paramVar->mIsSplat)
  12873. {
  12874. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  12875. }
  12876. else
  12877. {
  12878. argIdx++;
  12879. }
  12880. }
  12881. }
  12882. // Try to find an ending delegate params composite
  12883. if ((compositeVariableIdx == -1) && (methodDef->mParams.size() > 0))
  12884. {
  12885. auto paramDef = methodDef->mParams.back();
  12886. if (paramDef->mParamKind == BfParamKind_Params)
  12887. {
  12888. auto paramsType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_NoResolveGenericParam);
  12889. if (paramsType == NULL)
  12890. {
  12891. AssertErrorState();
  12892. }
  12893. else if (paramsType->IsGenericParam())
  12894. {
  12895. auto genericParamInstance = GetGenericParamInstance((BfGenericParamType*)paramsType);
  12896. if (genericParamInstance->mTypeConstraint != NULL)
  12897. {
  12898. auto typeInstConstraint = genericParamInstance->mTypeConstraint->ToTypeInstance();
  12899. if ((genericParamInstance->mTypeConstraint->IsDelegate()) || (genericParamInstance->mTypeConstraint->IsFunction()) ||
  12900. ((typeInstConstraint != NULL) &&
  12901. ((typeInstConstraint->mTypeDef == mCompiler->mDelegateTypeDef) || (typeInstConstraint->mTypeDef == mCompiler->mFunctionTypeDef))))
  12902. {
  12903. BfLocalVariable* localVar = new BfLocalVariable();
  12904. localVar->mName = paramDef->mName;
  12905. localVar->mResolvedType = paramsType;
  12906. localVar->mCompositeCount = 0;
  12907. DoAddLocalVariable(localVar);
  12908. }
  12909. }
  12910. }
  12911. else if (paramsType->IsDelegate())
  12912. {
  12913. BfMethodInstance* invokeMethodInstance = GetRawMethodInstanceAtIdx(paramsType->ToTypeInstance(), 0, "Invoke");
  12914. if (invokeMethodInstance != NULL)
  12915. {
  12916. // This is only for the case where the delegate didn't actually have any params so the composite is zero-sized
  12917. // and wasn't cleared by the preceding loop
  12918. BF_ASSERT(invokeMethodInstance->GetParamCount() == 0);
  12919. BfLocalVariable* localVar = new BfLocalVariable();
  12920. localVar->mName = paramDef->mName;
  12921. localVar->mResolvedType = paramsType;
  12922. localVar->mCompositeCount = 0;
  12923. DoAddLocalVariable(localVar);
  12924. }
  12925. }
  12926. }
  12927. }
  12928. }
  12929. void BfModule::ProcessMethod_ProcessDeferredLocals(int startIdx)
  12930. {
  12931. // if (mCurMethodState->mPrevMethodState != NULL) // Re-entry
  12932. // return;
  12933. auto _ClearState = [&]()
  12934. {
  12935. mCurMethodState->mLocalMethods.Clear();
  12936. for (auto& local : mCurMethodState->mLocals)
  12937. delete local;
  12938. mCurMethodState->mLocals.Clear();
  12939. mCurMethodState->mLocalVarSet.Clear();
  12940. };
  12941. // 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
  12942. // we show errors in the capture phase. If we somehow pass the capture phase without error then this method WILL show any errors here,
  12943. // however (compiler bug), so this is the safest way
  12944. if (!mCurMethodState->mDeferredLocalMethods.IsEmpty())
  12945. {
  12946. for (int deferredLocalMethodIdx = 0; deferredLocalMethodIdx < (int)mCurMethodState->mDeferredLocalMethods.size(); deferredLocalMethodIdx++)
  12947. {
  12948. auto deferredLocalMethod = mCurMethodState->mDeferredLocalMethods[deferredLocalMethodIdx];
  12949. BfLogSysM("Processing deferred local method %p\n", deferredLocalMethod);
  12950. if (!mHadBuildError)
  12951. {
  12952. // Process as a closure - that allows us to look back and see the const locals and stuff
  12953. BfClosureState closureState;
  12954. mCurMethodState->mClosureState = &closureState;
  12955. closureState.mConstLocals = deferredLocalMethod->mConstLocals;
  12956. closureState.mReturnType = deferredLocalMethod->mMethodInstance->mReturnType;
  12957. closureState.mActiveDeferredLocalMethod = deferredLocalMethod;
  12958. closureState.mLocalMethod = deferredLocalMethod->mLocalMethod;
  12959. if (deferredLocalMethod->mMethodInstance->mMethodInfoEx != NULL)
  12960. closureState.mClosureInstanceInfo = deferredLocalMethod->mMethodInstance->mMethodInfoEx->mClosureInstanceInfo;
  12961. mCurMethodState->mMixinState = deferredLocalMethod->mLocalMethod->mDeclMixinState;
  12962. _ClearState();
  12963. for (auto& constLocal : deferredLocalMethod->mConstLocals)
  12964. {
  12965. auto localVar = new BfLocalVariable();
  12966. *localVar = constLocal;
  12967. DoAddLocalVariable(localVar);
  12968. }
  12969. mCurMethodState->mLocalMethods = deferredLocalMethod->mLocalMethods;
  12970. bool doProcess = !mCompiler->mCanceling;
  12971. if (doProcess)
  12972. {
  12973. BP_ZONE_F("ProcessMethod local %s", deferredLocalMethod->mMethodInstance->mMethodDef->mName.c_str());
  12974. ProcessMethod(deferredLocalMethod->mMethodInstance);
  12975. }
  12976. }
  12977. delete deferredLocalMethod;
  12978. mSystem->CheckLockYield();
  12979. }
  12980. }
  12981. for (auto& kv : mCurMethodState->mLocalMethodCache)
  12982. {
  12983. BF_ASSERT((kv.mValue->mMethodDef == NULL) || (kv.mKey == kv.mValue->mMethodDef->mName));
  12984. }
  12985. if ((!mCurMethodState->mDeferredLambdaInstances.IsEmpty()) && (!mHadBuildError))
  12986. {
  12987. for (int deferredLambdaIdx = 0; deferredLambdaIdx < (int)mCurMethodState->mDeferredLambdaInstances.size(); deferredLambdaIdx++)
  12988. {
  12989. auto lambdaInstance = mCurMethodState->mDeferredLambdaInstances[deferredLambdaIdx];
  12990. BfLogSysM("Processing deferred lambdaInstance %p\n", lambdaInstance);
  12991. BfClosureState closureState;
  12992. mCurMethodState->mClosureState = &closureState;
  12993. //closureState.mConstLocals = deferredLocalMethod->mConstLocals;
  12994. closureState.mReturnType = lambdaInstance->mMethodInstance->mReturnType;
  12995. if (lambdaInstance->mClosureTypeInstance != NULL)
  12996. closureState.mClosureType = lambdaInstance->mClosureTypeInstance;
  12997. else
  12998. closureState.mClosureType = lambdaInstance->mDelegateTypeInstance;
  12999. closureState.mClosureInstanceInfo = lambdaInstance->mMethodInstance->mMethodInfoEx->mClosureInstanceInfo;
  13000. mCurMethodState->mMixinState = lambdaInstance->mDeclMixinState;
  13001. _ClearState();
  13002. for (auto& constLocal : lambdaInstance->mConstLocals)
  13003. {
  13004. //if (constLocal.mIsThis)
  13005. {
  13006. // Valueless 'this'
  13007. closureState.mConstLocals.Add(constLocal);
  13008. }
  13009. /*else
  13010. {
  13011. auto localVar = new BfLocalVariable();
  13012. *localVar = constLocal;
  13013. DoAddLocalVariable(localVar);
  13014. }*/
  13015. }
  13016. BfMethodInstanceGroup methodInstanceGroup;
  13017. methodInstanceGroup.mOwner = mCurTypeInstance;
  13018. methodInstanceGroup.mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  13019. bool doProcess = !mCompiler->mCanceling;
  13020. if (doProcess)
  13021. {
  13022. BP_ZONE_F("ProcessMethod lambdaInstance %s", lambdaInstance->mMethodInstance->mMethodDef->mName.c_str());
  13023. lambdaInstance->mMethodInstance->mMethodInstanceGroup = &methodInstanceGroup;
  13024. ProcessMethod(lambdaInstance->mMethodInstance);
  13025. if (lambdaInstance->mDtorMethodInstance != NULL)
  13026. {
  13027. lambdaInstance->mDtorMethodInstance->mMethodInstanceGroup = &methodInstanceGroup;
  13028. ProcessMethod(lambdaInstance->mDtorMethodInstance);
  13029. }
  13030. }
  13031. }
  13032. mSystem->CheckLockYield();
  13033. }
  13034. }
  13035. void BfModule::EmitGCMarkValue(BfTypedValue& thisValue, BfType* checkType, int memberDepth, int curOffset, HashSet<int>& objectOffsets, BfModuleMethodInstance markFromGCThreadMethodInstance)
  13036. {
  13037. if (checkType->IsComposite())
  13038. PopulateType(checkType, BfPopulateType_Data);
  13039. if (!checkType->WantsGCMarking())
  13040. return;
  13041. auto typeInstance = checkType->ToTypeInstance();
  13042. bool callMarkMethod = false;
  13043. // Call the actual marking method
  13044. if (memberDepth == 0)
  13045. {
  13046. // Don't call marking method on self
  13047. }
  13048. else if (checkType->IsObjectOrInterface())
  13049. {
  13050. if (!objectOffsets.Add(curOffset))
  13051. {
  13052. return;
  13053. }
  13054. callMarkMethod = true;
  13055. }
  13056. else if (checkType->IsSizedArray())
  13057. {
  13058. callMarkMethod = true;
  13059. }
  13060. else if (typeInstance != NULL)
  13061. {
  13062. typeInstance->mTypeDef->PopulateMemberSets();
  13063. BfMemberSetEntry* entry = NULL;
  13064. BfMethodDef* methodDef = NULL;
  13065. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(String(BF_METHODNAME_MARKMEMBERS), &entry))
  13066. {
  13067. methodDef = (BfMethodDef*)entry->mMemberDef;
  13068. if (methodDef->HasBody())
  13069. {
  13070. callMarkMethod = true;
  13071. }
  13072. }
  13073. }
  13074. if (callMarkMethod)
  13075. {
  13076. BfTypedValue markValue;
  13077. auto memberType = checkType;
  13078. if (memberType->IsObjectOrInterface())
  13079. memberType = mContext->mBfObjectType; // Just to avoid that extra cast for the call itself
  13080. auto memberPtrType = CreatePointerType(memberType);
  13081. if (curOffset == 0)
  13082. {
  13083. markValue = BfTypedValue(mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(memberPtrType)), memberType, true);
  13084. }
  13085. else
  13086. {
  13087. if (!thisValue.mType->IsPointer())
  13088. {
  13089. auto int8Type = GetPrimitiveType(BfTypeCode_UInt8);
  13090. auto int8PtrType = CreatePointerType(int8Type);
  13091. thisValue = BfTypedValue(mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(int8PtrType)), int8PtrType);
  13092. }
  13093. auto offsetValue = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, curOffset);
  13094. markValue = BfTypedValue(mBfIRBuilder->CreateBitCast(offsetValue, mBfIRBuilder->MapType(memberPtrType)), memberType, true);
  13095. }
  13096. EmitGCMarkValue(markValue, markFromGCThreadMethodInstance);
  13097. return;
  13098. }
  13099. auto methodDef = mCurMethodInstance->mMethodDef;
  13100. if (checkType->IsPayloadEnum())
  13101. {
  13102. for (auto& fieldInst : typeInstance->mFieldInstances)
  13103. {
  13104. if (!fieldInst.mIsEnumPayloadCase)
  13105. continue;
  13106. auto fieldDef = fieldInst.GetFieldDef();
  13107. EmitGCMarkValue(thisValue, fieldInst.mResolvedType, memberDepth + 1, curOffset, objectOffsets, markFromGCThreadMethodInstance);
  13108. }
  13109. return;
  13110. }
  13111. if (typeInstance == NULL)
  13112. return;
  13113. for (auto& fieldInst : typeInstance->mFieldInstances)
  13114. {
  13115. auto fieldDef = fieldInst.GetFieldDef();
  13116. if (fieldDef == NULL)
  13117. continue;
  13118. if (fieldDef->mIsStatic)
  13119. continue;
  13120. if (typeInstance == mCurTypeInstance)
  13121. {
  13122. // Note: we don't do method chaining when we are marking members of members. Theoretically this means
  13123. // we may be marking member values that can never contain a value anyway, but this is benign
  13124. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  13125. continue;
  13126. }
  13127. EmitGCMarkValue(thisValue, fieldInst.mResolvedType, memberDepth + 1, curOffset + fieldInst.mDataOffset, objectOffsets, markFromGCThreadMethodInstance);
  13128. }
  13129. if ((typeInstance->mBaseType != NULL) && (typeInstance->mBaseType != mContext->mBfObjectType))
  13130. {
  13131. EmitGCMarkValue(thisValue, typeInstance->mBaseType, memberDepth, curOffset, objectOffsets, markFromGCThreadMethodInstance);
  13132. }
  13133. }
  13134. void BfModule::EmitGCMarkMembers()
  13135. {
  13136. auto methodDef = mCurMethodInstance->mMethodDef;
  13137. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef, BfPopulateType_DataAndMethods);
  13138. BfModuleMethodInstance markFromGCThreadMethodInstance;
  13139. if (gcType != NULL)
  13140. markFromGCThreadMethodInstance = GetMethodByName(gcType->ToTypeInstance(), "Mark", 1);
  13141. if ((markFromGCThreadMethodInstance.mMethodInstance != NULL) && (!mCurMethodInstance->mIsUnspecialized))
  13142. {
  13143. if (mCurTypeInstance->IsBoxed())
  13144. {
  13145. // This already gets filled in by the normal boxed forwarding
  13146. }
  13147. else
  13148. {
  13149. auto thisValue = GetThis();
  13150. if (thisValue.IsSplat())
  13151. {
  13152. BfIRFunction func = mCurMethodInstance->mIRFunction;
  13153. int argIdx = 0;
  13154. std::function<void(BfType*)> checkTypeLambda = [&](BfType* checkType)
  13155. {
  13156. if (checkType->IsStruct())
  13157. {
  13158. auto checkTypeInstance = checkType->ToTypeInstance();
  13159. if (checkTypeInstance->mBaseType != NULL)
  13160. checkTypeLambda(checkTypeInstance->mBaseType);
  13161. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  13162. {
  13163. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  13164. if (fieldInstance->mDataIdx >= 0)
  13165. checkTypeLambda(fieldInstance->GetResolvedType());
  13166. }
  13167. }
  13168. else if (checkType->IsMethodRef())
  13169. {
  13170. BF_FATAL("Not handled");
  13171. }
  13172. else if (checkType->WantsGCMarking())
  13173. {
  13174. BfTypedValue markValue(mBfIRBuilder->GetArgument(argIdx), checkType);
  13175. EmitGCMarkValue(markValue, markFromGCThreadMethodInstance);
  13176. argIdx++;
  13177. }
  13178. };
  13179. checkTypeLambda(thisValue.mType);
  13180. }
  13181. else if (!methodDef->mIsStatic)
  13182. {
  13183. if ((mCurTypeInstance->mBaseType != NULL) && (!mCurTypeInstance->IsTypedPrimitive()) && (mCurTypeInstance->mBaseType->WantsGCMarking()))
  13184. {
  13185. BfModuleMethodInstance moduleMethodInst = GetMethodByName(mCurTypeInstance->mBaseType, BF_METHODNAME_MARKMEMBERS, 0, true);
  13186. if (moduleMethodInst)
  13187. {
  13188. auto methodBaseType = moduleMethodInst.mMethodInstance->GetOwner();
  13189. if (methodBaseType != mContext->mBfObjectType)
  13190. {
  13191. auto thisValue = GetThis();
  13192. auto baseValue = Cast(NULL, thisValue, methodBaseType, BfCastFlags_Explicit);
  13193. SizedArray<BfIRValue, 1> args;
  13194. if (moduleMethodInst.mMethodInstance->GetParamIsSplat(-1))
  13195. {
  13196. BfExprEvaluator exprEvaluator(this);
  13197. exprEvaluator.SplatArgs(baseValue, args);
  13198. }
  13199. else
  13200. {
  13201. args.push_back(baseValue.mValue);
  13202. }
  13203. mBfIRBuilder->CreateCall(moduleMethodInst.mFunc, args);
  13204. }
  13205. }
  13206. }
  13207. }
  13208. if (!methodDef->mIsStatic)
  13209. {
  13210. HashSet<int> objectOffsets;
  13211. EmitGCMarkValue(thisValue, mCurTypeInstance, 0, 0, objectOffsets, markFromGCThreadMethodInstance);
  13212. }
  13213. else
  13214. {
  13215. for (auto& fieldInst : mCurTypeInstance->mFieldInstances)
  13216. {
  13217. if (thisValue.IsSplat())
  13218. break;
  13219. auto fieldDef = fieldInst.GetFieldDef();
  13220. if (fieldDef == NULL)
  13221. continue;
  13222. if (fieldInst.mIsThreadLocal)
  13223. continue;
  13224. if (fieldDef->mIsStatic == methodDef->mIsStatic)
  13225. {
  13226. // For extensions, only handle these fields in the appropriate extension
  13227. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  13228. continue;
  13229. if (!fieldInst.mFieldIncluded)
  13230. continue;
  13231. auto fieldTypeInst = fieldInst.mResolvedType->ToTypeInstance();
  13232. if (fieldTypeInst != NULL)
  13233. {
  13234. auto fieldDef = fieldInst.GetFieldDef();
  13235. BfTypedValue markVal;
  13236. if (fieldDef->mIsConst)
  13237. continue;
  13238. if ((!fieldTypeInst->IsObjectOrInterface()) && (!fieldTypeInst->IsComposite()))
  13239. continue;
  13240. mBfIRBuilder->PopulateType(fieldTypeInst);
  13241. if (fieldTypeInst->IsValuelessType())
  13242. continue;
  13243. if ((fieldDef->mIsStatic) && (!fieldDef->mIsConst))
  13244. {
  13245. markVal = ReferenceStaticField(&fieldInst);
  13246. }
  13247. else if (!fieldDef->mIsStatic)
  13248. {
  13249. markVal = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInst.mDataIdx/*, fieldDef->mName*/), fieldInst.mResolvedType, true);
  13250. }
  13251. if (markVal)
  13252. EmitGCMarkValue(markVal, markFromGCThreadMethodInstance);
  13253. }
  13254. }
  13255. }
  13256. }
  13257. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  13258. CallChainedMethods(mCurMethodInstance, false);
  13259. }
  13260. }
  13261. }
  13262. void BfModule::EmitGCFindTLSMembers()
  13263. {
  13264. auto methodDef = mCurMethodInstance->mMethodDef;
  13265. auto gcTypeInst = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  13266. auto reportTLSMark = GetMethodByName(gcTypeInst, "ReportTLSMember", 2);
  13267. BF_ASSERT(reportTLSMark);
  13268. for (auto& fieldInst : mCurTypeInstance->mFieldInstances)
  13269. {
  13270. auto fieldDef = fieldInst.GetFieldDef();
  13271. if (fieldDef == NULL)
  13272. continue;
  13273. if (!fieldInst.mIsThreadLocal)
  13274. continue;
  13275. // For extensions, only handle these fields in the appropriate extension
  13276. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  13277. continue;
  13278. if (!fieldInst.mFieldIncluded)
  13279. continue;
  13280. if (fieldDef->mIsConst)
  13281. continue;
  13282. auto fieldType = fieldInst.mResolvedType;
  13283. if ((!fieldType->IsObjectOrInterface()) && (!fieldType->IsComposite()))
  13284. continue;
  13285. if (fieldType->IsValuelessType())
  13286. continue;
  13287. BfTypedValue markVal = ReferenceStaticField(&fieldInst);
  13288. if (markVal)
  13289. {
  13290. BfIRValue fieldRefPtr = mBfIRBuilder->CreateBitCast(markVal.mValue, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  13291. BfIRValue markFuncPtr = GetMarkFuncPtr(fieldType);
  13292. SizedArray<BfIRValue, 2> llvmArgs;
  13293. llvmArgs.push_back(fieldRefPtr);
  13294. llvmArgs.push_back(markFuncPtr);
  13295. mBfIRBuilder->CreateCall(reportTLSMark.mFunc, llvmArgs);
  13296. }
  13297. }
  13298. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  13299. CallChainedMethods(mCurMethodInstance, false);
  13300. }
  13301. void BfModule::ProcessMethod(BfMethodInstance* methodInstance, bool isInlineDup)
  13302. {
  13303. BP_ZONE_F("BfModule::ProcessMethod %s", BP_DYN_STR(methodInstance->mMethodDef->mName.c_str()));
  13304. if (mAwaitingInitFinish)
  13305. FinishInit();
  13306. if (!methodInstance->mIsReified)
  13307. BF_ASSERT(!mIsReified);
  13308. if (methodInstance->mMethodInfoEx != NULL)
  13309. {
  13310. for (auto methodGenericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  13311. {
  13312. if (methodGenericArg->IsMethodRef())
  13313. {
  13314. auto methodRefType = (BfMethodRefType*)methodGenericArg;
  13315. BF_ASSERT(methodRefType->mOwnerRevision == methodRefType->mOwner->mRevision);
  13316. }
  13317. }
  13318. }
  13319. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mWantsIRIgnoreWrites || methodInstance->mIsUnspecialized);
  13320. bool ignoreWrites = mBfIRBuilder->mIgnoreWrites;
  13321. if ((HasCompiledOutput()) && (!mBfIRBuilder->mIgnoreWrites))
  13322. {
  13323. BF_ASSERT(!methodInstance->mIRFunction.IsFake() || (methodInstance->GetImportCallKind() != BfImportCallKind_None));
  13324. }
  13325. SetAndRestoreValue<BfSourceClassifier*> prevSourceClassifier;
  13326. if (((methodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend) || (methodInstance->mIsForeignMethodDef) || (methodInstance->IsSpecializedGenericMethod())) &&
  13327. (mCompiler->mResolvePassData != NULL))
  13328. {
  13329. // Don't classify on the CtorCalcAppend, just on the actual Ctor
  13330. prevSourceClassifier.Init(mCompiler->mResolvePassData->mSourceClassifier, NULL);
  13331. }
  13332. if (methodInstance->mHasBeenProcessed)
  13333. {
  13334. BfLogSysM("ProcessMethod %p HasBeenProcessed\n", methodInstance);
  13335. return;
  13336. }
  13337. if (methodInstance->mFailedConstraints)
  13338. {
  13339. // The only way this should be able to happen is if we fail our generic param check
  13340. BF_ASSERT(methodInstance->IsSpecializedGenericMethod());
  13341. BfLogSysM("Method instance marked as 'failed' at start of ProcessMethod %p\n", methodInstance);
  13342. methodInstance->mHasBeenProcessed = true;
  13343. return;
  13344. }
  13345. BfMethodInstance* defaultMethodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  13346. BF_ASSERT(methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_NotSet);
  13347. if ((methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_AlwaysInclude) &&
  13348. (methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_Referenced))
  13349. {
  13350. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Referenced;
  13351. auto owningModule = methodInstance->GetOwner()->mModule;
  13352. if (owningModule->mIsScratchModule)
  13353. {
  13354. BF_ASSERT(owningModule->mOnDemandMethodCount == 0);
  13355. }
  13356. else
  13357. {
  13358. BF_ASSERT((owningModule->mOnDemandMethodCount > 0) || (!HasCompiledOutput()) || (owningModule->mExtensionCount > 0));
  13359. if (owningModule->mOnDemandMethodCount > 0)
  13360. owningModule->mOnDemandMethodCount--;
  13361. }
  13362. }
  13363. // We set mHasBeenProcessed to true immediately -- this helps avoid stack overflow during recursion for things like
  13364. // self-referencing append allocations in ctor@calcAppend
  13365. methodInstance->mHasBeenProcessed = true;
  13366. mIncompleteMethodCount--;
  13367. BF_ASSERT((mIsSpecialModule) || (mIncompleteMethodCount >= 0));
  13368. auto typeDef = methodInstance->mMethodInstanceGroup->mOwner->mTypeDef;
  13369. auto methodDef = methodInstance->mMethodDef;
  13370. auto methodDeclaration = methodDef->GetMethodDeclaration();
  13371. if ((methodInstance->mIsReified) && (methodInstance->mVirtualTableIdx != -1))
  13372. {
  13373. // If we reify a virtual method in a HotCompile then we need to make sure the type data gets written out
  13374. // so we get the new vdata for it
  13375. methodInstance->GetOwner()->mDirty = true;
  13376. }
  13377. int dependentGenericStartIdx = 0;
  13378. if (methodDef->mIsLocalMethod) // See DoMethodDeclaration for an explaination of dependentGenericStartIdx
  13379. dependentGenericStartIdx = (int)mCurMethodState->GetRootMethodState()->mMethodInstance->GetNumGenericArguments();
  13380. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  13381. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, methodInstance->mMethodInstanceGroup->mOwner);
  13382. SetAndRestoreValue<BfFilePosition> prevFilePos(mCurFilePosition);
  13383. SetAndRestoreValue<bool> prevHadBuildError(mHadBuildError, false);
  13384. SetAndRestoreValue<bool> prevHadWarning(mHadBuildWarning, false);
  13385. SetAndRestoreValue<bool> prevIgnoreWarnings(mIgnoreWarnings, false);
  13386. if ((methodInstance->mIsReified) &&
  13387. ((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorNoBody)))
  13388. {
  13389. mCurTypeInstance->mHasBeenInstantiated = true;
  13390. }
  13391. // Warnings are shown in the capture phase
  13392. if ((methodDef->mIsLocalMethod) || (mCurTypeInstance->IsClosure()))
  13393. mIgnoreWarnings = true;
  13394. if ((methodDeclaration == NULL) && (mCurMethodState == NULL))
  13395. UseDefaultSrcPos();
  13396. // We may not actually be populated in relatively rare autocompelte cases
  13397. PopulateType(mCurTypeInstance, BfPopulateType_DataAndMethods);
  13398. mBfIRBuilder->PopulateType(mCurTypeInstance, BfIRPopulateType_Full);
  13399. BfAstNode* nameNode = NULL;
  13400. if (methodDeclaration != NULL)
  13401. {
  13402. nameNode = methodDeclaration->mNameNode;
  13403. if (nameNode == NULL)
  13404. {
  13405. if (auto ctorDeclaration = BfNodeDynCast<BfConstructorDeclaration>(methodDeclaration))
  13406. nameNode = ctorDeclaration->mThisToken;
  13407. }
  13408. }
  13409. if ((mCompiler->mResolvePassData != NULL) && (methodDeclaration != NULL) && (nameNode != NULL) &&
  13410. (mCompiler->mResolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Method) && (methodDef->mIdx >= 0))
  13411. {
  13412. if (methodInstance->GetExplicitInterface() == NULL)
  13413. mCompiler->mResolvePassData->HandleMethodReference(nameNode, typeDef, methodDef);
  13414. else
  13415. {
  13416. for (auto& ifaceEntry : mCurTypeInstance->mInterfaces)
  13417. {
  13418. auto ifaceInst = ifaceEntry.mInterfaceType;
  13419. int startIdx = ifaceEntry.mStartInterfaceTableIdx;
  13420. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  13421. if (methodInstance->GetExplicitInterface() != ifaceInst)
  13422. continue;
  13423. ifaceInst->mTypeDef->PopulateMemberSets();
  13424. BfMethodDef* nextMethod = NULL;
  13425. BfMemberSetEntry* entry = NULL;
  13426. if (ifaceInst->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  13427. nextMethod = (BfMethodDef*)entry->mMemberDef;
  13428. while (nextMethod != NULL)
  13429. {
  13430. auto checkMethod = nextMethod;
  13431. nextMethod = nextMethod->mNextWithSameName;
  13432. BfMethodInstance* implMethodInst = mCurTypeInstance->mInterfaceMethodTable[startIdx + checkMethod->mIdx].mMethodRef;
  13433. if (implMethodInst == methodInstance)
  13434. {
  13435. auto ifaceMethodDef = ifaceInst->mTypeDef->mMethods[checkMethod->mIdx];
  13436. mCompiler->mResolvePassData->HandleMethodReference(nameNode, ifaceInst->mTypeDef, ifaceMethodDef);
  13437. }
  13438. }
  13439. }
  13440. }
  13441. if (methodDef->mIsOverride)
  13442. {
  13443. for (int virtIdx = 0; virtIdx < (int)mCurTypeInstance->mVirtualMethodTable.size(); virtIdx++)
  13444. {
  13445. auto& ventry = mCurTypeInstance->mVirtualMethodTable[virtIdx];
  13446. if (ventry.mDeclaringMethod.mMethodNum == -1)
  13447. continue;
  13448. BfMethodInstance* virtMethod = ventry.mImplementingMethod;
  13449. if (virtMethod != NULL)
  13450. {
  13451. if (virtMethod == methodInstance)
  13452. {
  13453. // Is matching method
  13454. if (virtIdx < (int)mCurTypeInstance->mBaseType->mVirtualMethodTable.size())
  13455. {
  13456. auto baseType = mCurTypeInstance->mBaseType;
  13457. if (baseType != NULL)
  13458. {
  13459. while ((baseType->mBaseType != NULL) && (virtIdx < baseType->mBaseType->mVirtualMethodTableSize))
  13460. baseType = baseType->mBaseType;
  13461. BfMethodInstance* baseVirtMethod = baseType->mVirtualMethodTable[virtIdx].mImplementingMethod;
  13462. mCompiler->mResolvePassData->HandleMethodReference(nameNode, baseType->mTypeDef, baseVirtMethod->mMethodDef);
  13463. }
  13464. }
  13465. break;
  13466. }
  13467. }
  13468. }
  13469. }
  13470. }
  13471. BfLogSysM("ProcessMethod %p Unspecialized: %d Module: %p IRFunction: %d Reified: %d\n", methodInstance, mCurTypeInstance->IsUnspecializedType(), this, methodInstance->mIRFunction.mId, methodInstance->mIsReified);
  13472. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  13473. {
  13474. if (mBfIRBuilder->mIgnoreWrites)
  13475. return;
  13476. BfLogSysM("DllImportGlobalVar processing %p\n", methodInstance);
  13477. if (!methodInstance->mIRFunction)
  13478. {
  13479. BfIRValue dllImportGlobalVar = CreateDllImportGlobalVar(methodInstance, true);
  13480. methodInstance->mIRFunction = mBfIRBuilder->GetFakeVal();
  13481. mFuncReferences[mCurMethodInstance] = dllImportGlobalVar;
  13482. }
  13483. if (HasCompiledOutput())
  13484. {
  13485. BfDllImportEntry dllImportEntry;
  13486. dllImportEntry.mFuncVar = methodInstance->mIRFunction;
  13487. dllImportEntry.mMethodInstance = mCurMethodInstance;
  13488. mDllImportEntries.push_back(dllImportEntry);
  13489. }
  13490. return;
  13491. }
  13492. StringT<128> mangledName;
  13493. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  13494. if (!methodInstance->mIRFunction)
  13495. {
  13496. bool isIntrinsic = false;
  13497. SetupIRFunction(methodInstance, mangledName, false, &isIntrinsic);
  13498. }
  13499. if (methodInstance->mIsIntrinsic)
  13500. return;
  13501. auto prevActiveFunction = mBfIRBuilder->GetActiveFunction();
  13502. mBfIRBuilder->SetActiveFunction(mCurMethodInstance->mIRFunction);
  13503. if (methodDef->mBody != NULL)
  13504. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  13505. else if (methodDeclaration != NULL)
  13506. UpdateSrcPos(methodDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  13507. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  13508. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  13509. if (mCurMethodState == NULL) // Only do initial classify for the 'outer' method state, not any local methods or lambdas
  13510. {
  13511. if ((mCompiler->mIsResolveOnly) && (methodDef->mBody != NULL) && (!mCurTypeInstance->IsBoxed()) &&
  13512. (methodDef->mBody->IsFromParser(mCompiler->mResolvePassData->mParser)) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  13513. {
  13514. mCompiler->mResolvePassData->mSourceClassifier->VisitChildNoRef(methodDef->mBody);
  13515. }
  13516. }
  13517. BfHotDataReferenceBuilder hotDataReferenceBuilder;
  13518. BfMethodState methodState;
  13519. if (mCurMethodState != NULL)
  13520. methodState.mClosureState = mCurMethodState->mClosureState;
  13521. if ((mCompiler->mOptions.mAllowHotSwapping) && (methodInstance->mIsReified) && (!methodInstance->mIsUnspecialized) && (!isInlineDup))
  13522. {
  13523. //BF_ASSERT(methodInstance->mHotMethod != NULL);
  13524. if (methodInstance->mHotMethod == NULL)
  13525. CheckHotMethod(methodInstance, mangledName);
  13526. methodState.mHotDataReferenceBuilder = &hotDataReferenceBuilder;
  13527. }
  13528. methodState.mPrevMethodState = mCurMethodState;
  13529. methodState.mMethodInstance = methodInstance;
  13530. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  13531. if (methodInstance->GetCustomAttributes() != NULL)
  13532. {
  13533. int typeOptionsIdx = GenerateTypeOptions(methodInstance->GetCustomAttributes(), mCurTypeInstance, false);
  13534. if (typeOptionsIdx != -1)
  13535. methodState.mMethodTypeOptions = mSystem->GetTypeOptions(typeOptionsIdx);
  13536. }
  13537. BfTypeState typeState(mCurTypeInstance);
  13538. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  13539. bool isGenericVariation = (methodInstance->mIsUnspecializedVariation) || (mCurTypeInstance->IsUnspecializedTypeVariation());
  13540. BfMethodInstance* unspecializedMethodInstance = NULL;
  13541. if ((prevMethodState.mPrevVal != NULL) &&
  13542. ((methodState.mClosureState == NULL) || (methodState.mClosureState->mActiveDeferredLocalMethod == NULL)))
  13543. {
  13544. // This is 'inner' (probably a closure) - use binding from outer function
  13545. methodState.mGenericTypeBindings = prevMethodState.mPrevVal->mGenericTypeBindings;
  13546. }
  13547. else if ((methodInstance->mIsUnspecialized) || (mCurTypeInstance->IsUnspecializedType()) && (!isGenericVariation))
  13548. {
  13549. methodState.mGenericTypeBindings = &methodInstance->GetMethodInfoEx()->mGenericTypeBindings;
  13550. }
  13551. else if ((((methodInstance->mMethodInfoEx != NULL) && ((int)methodInstance->mMethodInfoEx->mMethodGenericArguments.size() > dependentGenericStartIdx)) || ((mCurTypeInstance->IsGenericTypeInstance())) && (!isGenericVariation)))
  13552. {
  13553. unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance);
  13554. BF_ASSERT(unspecializedMethodInstance != methodInstance);
  13555. if (!unspecializedMethodInstance->mHasBeenProcessed)
  13556. {
  13557. // Make sure the unspecialized method is processed so we can take its bindings
  13558. // Clear mCurMethodState so we don't think we're in a local method
  13559. SetAndRestoreValue<BfMethodState*> prevMethodState_Unspec(mCurMethodState, prevMethodState.mPrevVal);
  13560. mContext->ProcessMethod(unspecializedMethodInstance);
  13561. }
  13562. methodState.mGenericTypeBindings = &unspecializedMethodInstance->GetMethodInfoEx()->mGenericTypeBindings;
  13563. }
  13564. if (methodDef->mMethodType == BfMethodType_Operator)
  13565. {
  13566. auto operatorDef = (BfOperatorDef*) methodDef;
  13567. BfAstNode* refNode = operatorDef->mOperatorDeclaration->mOperatorToken;
  13568. auto paramErrorRefNode = refNode;
  13569. if (operatorDef->mOperatorDeclaration->mOpenParen != NULL)
  13570. paramErrorRefNode = operatorDef->mOperatorDeclaration->mOpenParen;
  13571. if ((mCurMethodInstance->GetParamCount() > 0) && (mCurMethodInstance->GetParamTypeRef(0) != NULL))
  13572. paramErrorRefNode = mCurMethodInstance->GetParamTypeRef(0);
  13573. if (operatorDef->mOperatorDeclaration->mBinOp != BfBinaryOp_None)
  13574. {
  13575. if (methodDef->mParams.size() != 2)
  13576. {
  13577. Fail("Binary operators must declare two parameters", paramErrorRefNode);
  13578. }
  13579. else
  13580. {
  13581. if ((mCurMethodInstance->GetParamType(0) != mCurTypeInstance) && (!mCurMethodInstance->GetParamType(0)->IsSelf()) &&
  13582. (mCurMethodInstance->GetParamType(1) != mCurTypeInstance) && (!mCurMethodInstance->GetParamType(1)->IsSelf()))
  13583. {
  13584. Fail("At least one of the parameters of a binary operator must be the containing type", paramErrorRefNode);
  13585. }
  13586. }
  13587. BfType* wantType = NULL;
  13588. if (operatorDef->mOperatorDeclaration->mBinOp == BfBinaryOp_Compare)
  13589. {
  13590. wantType = GetPrimitiveType(BfTypeCode_IntPtr);
  13591. }
  13592. if ((wantType != NULL) && (methodInstance->mReturnType != wantType))
  13593. Fail(StrFormat("The return type for the '%s' operator must be '%s'", BfGetOpName(operatorDef->mOperatorDeclaration->mBinOp),
  13594. TypeToString(wantType).c_str()), operatorDef->mOperatorDeclaration->mReturnType);
  13595. }
  13596. else if (operatorDef->mOperatorDeclaration->mUnaryOp != BfUnaryOp_None)
  13597. {
  13598. if (methodDef->mParams.size() != 1)
  13599. {
  13600. Fail("Unary operators must declare one parameter", paramErrorRefNode);
  13601. }
  13602. else if ((mCurMethodInstance->GetParamType(0) != mCurTypeInstance) && (!mCurMethodInstance->GetParamType(0)->IsSelf()))
  13603. {
  13604. Fail("The parameter of a unary operator must be the containing type", paramErrorRefNode);
  13605. }
  13606. if (((operatorDef->mOperatorDeclaration->mUnaryOp == BfUnaryOp_Increment) ||
  13607. (operatorDef->mOperatorDeclaration->mUnaryOp == BfUnaryOp_Decrement)) &&
  13608. (!TypeIsSubTypeOf(mCurMethodInstance->mReturnType->ToTypeInstance(), mCurTypeInstance)))
  13609. {
  13610. Fail("The return type for the '++' or '--' operator must match the parameter type or be derived from the parameter type", operatorDef->mOperatorDeclaration->mReturnType);
  13611. }
  13612. }
  13613. else if (operatorDef->mOperatorDeclaration->mAssignOp != BfAssignmentOp_None)
  13614. {
  13615. if (methodDef->mParams.size() != 1)
  13616. {
  13617. Fail("Assignment operators must declare one parameter", paramErrorRefNode);
  13618. }
  13619. if (mCurMethodInstance->mReturnType->IsVoid())
  13620. {
  13621. Fail("The return type for assignment operator must be 'void'", operatorDef->mOperatorDeclaration->mReturnType);
  13622. }
  13623. }
  13624. else // Conversion
  13625. {
  13626. if (!operatorDef->mOperatorDeclaration->mIsConvOperator)
  13627. {
  13628. if (operatorDef->mOperatorDeclaration->mReturnType != NULL)
  13629. Fail("Conversion operators must declare their target type after the 'operator' token, not before", operatorDef->mOperatorDeclaration->mReturnType);
  13630. }
  13631. if (methodDef->mParams.size() != 1)
  13632. {
  13633. auto refNode = paramErrorRefNode;
  13634. if (!operatorDef->mOperatorDeclaration->mCommas.empty())
  13635. refNode = operatorDef->mOperatorDeclaration->mCommas[0];
  13636. Fail("Conversion operators must declare one parameter", refNode);
  13637. }
  13638. else
  13639. {
  13640. if ((mCurMethodInstance->GetParamType(0) != mCurTypeInstance) && (!mCurMethodInstance->GetParamType(0)->IsSelf()) &&
  13641. (mCurMethodInstance->mReturnType != mCurTypeInstance) && (!mCurMethodInstance->mReturnType->IsSelf()))
  13642. Fail("User-defined conversion must convert to or from the enclosing type", paramErrorRefNode);
  13643. if (mCurMethodInstance->GetParamType(0) == mCurMethodInstance->mReturnType)
  13644. Fail("User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type", operatorDef->mOperatorDeclaration->mReturnType);
  13645. // On type lookup error we default to 'object', so don't do the 'base class' error if that may have
  13646. // happened here
  13647. if ((!mHadBuildError) || ((mCurMethodInstance->mReturnType != mContext->mBfObjectType) && (mCurMethodInstance->GetParamType(0) != mContext->mBfObjectType)))
  13648. {
  13649. auto isToBase = TypeIsSubTypeOf(mCurTypeInstance->mBaseType, mCurMethodInstance->mReturnType->ToTypeInstance());
  13650. bool isFromBase = TypeIsSubTypeOf(mCurTypeInstance->mBaseType, mCurMethodInstance->GetParamType(0)->ToTypeInstance());
  13651. if ((mCurTypeInstance->IsObject()) && (isToBase || isFromBase))
  13652. Fail("User-defined conversions to or from a base class are not allowed", paramErrorRefNode);
  13653. else if ((mCurTypeInstance->IsStruct()) && (isToBase))
  13654. Fail("User-defined conversions to a base struct are not allowed", paramErrorRefNode);
  13655. }
  13656. }
  13657. }
  13658. }
  13659. bool wantsDIData = (mBfIRBuilder->DbgHasInfo()) && (!methodDef->IsEmptyPartial()) && (!mCurMethodInstance->mIsUnspecialized) && (mHasFullDebugInfo);
  13660. if (methodDef->mMethodType == BfMethodType_Mixin)
  13661. wantsDIData = false;
  13662. if ((mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType != BfMethodType_Ctor))
  13663. wantsDIData = false;
  13664. bool wantsDIVariables = wantsDIData;
  13665. if (methodDef->mIsExtern)
  13666. wantsDIVariables = false;
  13667. SizedArray<BfIRMDNode, 8> diParams;
  13668. diParams.push_back(mBfIRBuilder->DbgGetType(methodInstance->mReturnType));
  13669. bool isThisStruct = mCurTypeInstance->IsStruct() && !mCurTypeInstance->IsTypedPrimitive();
  13670. BfType* thisType = NULL;
  13671. if (!methodDef->mIsStatic)
  13672. {
  13673. if ((methodState.mClosureState != NULL) && (methodState.mClosureState->mClosureType != NULL))
  13674. thisType = methodState.mClosureState->mClosureType;
  13675. else
  13676. thisType = mCurTypeInstance;
  13677. }
  13678. PopulateType(methodInstance->mReturnType, BfPopulateType_Data);
  13679. ProcessMethod_SetupParams(methodInstance, thisType, wantsDIData, &diParams);
  13680. //////////////////////////////////////////////////////////////////////////
  13681. //
  13682. {
  13683. if (methodDeclaration != NULL)
  13684. UpdateSrcPos(methodDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  13685. else if (methodDef->mBody != NULL)
  13686. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  13687. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  13688. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  13689. }
  13690. BfIRMDNode diFunction;
  13691. if (wantsDIData)
  13692. {
  13693. BP_ZONE("BfModule::BfMethodDeclaration.DISetup");
  13694. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParams);
  13695. int defLine = mCurFilePosition.mCurLine;
  13696. if (mDICompileUnit)
  13697. {
  13698. int flags = 0;
  13699. BfIRMDNode funcScope = mBfIRBuilder->DbgGetTypeInst(mCurTypeInstance);
  13700. if (methodDef->mProtection == BfProtection_Public)
  13701. flags = llvm::DINode::FlagPublic;
  13702. else if (methodDef->mProtection == BfProtection_Protected)
  13703. flags = llvm::DINode::FlagProtected;
  13704. else
  13705. flags = llvm::DINode::FlagPrivate;
  13706. if (methodDef->mIsOverride)
  13707. {
  13708. //flags |= llvm::DINode::FlagVirtual;
  13709. }
  13710. else if (methodDef->mIsVirtual)
  13711. flags |= llvm::DINode::FlagIntroducedVirtual;
  13712. if ((methodDef->mIsStatic) || (methodDef->mMethodType == BfMethodType_Mixin))
  13713. flags |= llvm::DINode::FlagStaticMember;
  13714. else
  13715. {
  13716. if ((mCurTypeInstance->IsValuelessType()) || (mCurTypeInstance->IsSplattable()))
  13717. flags |= llvm::DINode::FlagStaticMember;
  13718. }
  13719. flags |= llvm::DINode::FlagPrototyped;
  13720. if (methodDef->mMethodType == BfMethodType_Ctor)
  13721. {
  13722. flags |= llvm::DINode::FlagArtificial;
  13723. }
  13724. auto llvmFunction = methodInstance->mIRFunction;
  13725. SizedArray<BfIRMDNode, 1> genericArgs;
  13726. SizedArray<BfIRValue, 1> genericConstValueArgs;
  13727. String methodName;
  13728. if (methodInstance->GetForeignType() != NULL)
  13729. {
  13730. methodName += TypeToString(methodInstance->GetForeignType());
  13731. methodName += ".";
  13732. }
  13733. if (methodInstance->GetExplicitInterface() != NULL)
  13734. {
  13735. methodName += TypeToString(methodInstance->GetExplicitInterface());
  13736. methodName += ".";
  13737. }
  13738. methodName += methodDef->mName;
  13739. if (methodInstance->GetNumGenericArguments() != 0)
  13740. {
  13741. for (auto genericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  13742. {
  13743. if (genericArg->IsConstExprValue())
  13744. {
  13745. BfConstExprValueType* constExprValueType = (BfConstExprValueType*)genericArg;
  13746. while (genericConstValueArgs.size() < genericArgs.size())
  13747. genericConstValueArgs.push_back(BfIRValue());
  13748. genericConstValueArgs.push_back(mBfIRBuilder->CreateConst(BfTypeCode_UInt64, constExprValueType->mValue.mUInt64));
  13749. genericArgs.push_back(mBfIRBuilder->DbgGetType(GetPrimitiveType(BfTypeCode_Int64)));
  13750. }
  13751. else
  13752. genericArgs.push_back(mBfIRBuilder->DbgGetType(genericArg));
  13753. }
  13754. methodName += "<";
  13755. for (int i = 0; i < (int)methodInstance->mMethodInfoEx->mMethodGenericArguments.size(); i++)
  13756. {
  13757. if (i > 0)
  13758. methodName += ", ";
  13759. BfType* type = methodInstance->mMethodInfoEx->mMethodGenericArguments[i];
  13760. methodName += TypeToString(type);
  13761. }
  13762. methodName += ">";
  13763. }
  13764. if ((methodName.empty()) && (methodDeclaration != NULL))
  13765. {
  13766. if (auto operatorDecl = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  13767. {
  13768. methodName += "operator";
  13769. if (operatorDecl->mIsConvOperator)
  13770. {
  13771. methodName += " ";
  13772. methodName += TypeToString(methodInstance->mReturnType);
  13773. }
  13774. else if (operatorDecl->mOpTypeToken != NULL)
  13775. methodName += operatorDecl->mOpTypeToken->ToString();
  13776. }
  13777. }
  13778. methodState.mDIFile = mCurFilePosition.mFileInstance->mDIFile;
  13779. // diFunction = mBfIRBuilder->DbgCreateMethod(funcScope, methodName, mangledName, methodState.mDIFile,
  13780. // defLine + 1, diFuncType, false, true,
  13781. // (methodInstance->mVirtualTableIdx != -1) ? llvm::dwarf::DW_VIRTUALITY_virtual : llvm::dwarf::DW_VIRTUALITY_none,
  13782. // (methodInstance->mVirtualTableIdx != -1) ? methodInstance->DbgGetVirtualMethodNum() : 0,
  13783. // nullptr, flags, IsOptimized(), llvmFunction, genericArgs, genericConstValueArgs);
  13784. diFunction = mBfIRBuilder->DbgCreateMethod(funcScope, methodName, mangledName, methodState.mDIFile,
  13785. defLine + 1, diFuncType, false, true,
  13786. llvm::dwarf::DW_VIRTUALITY_none,
  13787. 0,
  13788. nullptr, flags, IsOptimized(), llvmFunction, genericArgs, genericConstValueArgs);
  13789. }
  13790. }
  13791. //////////////////////////////////////////////////////////////////////////
  13792. // Head and Init get rolled into Entry afterwards.
  13793. methodState.mIRFunction = methodInstance->mIRFunction;
  13794. methodState.mIRHeadBlock = mBfIRBuilder->CreateBlock("head", true);
  13795. methodState.mIRInitBlock = mBfIRBuilder->CreateBlock("init", true);
  13796. methodState.mIREntryBlock = mBfIRBuilder->CreateBlock("entry", true);
  13797. methodState.mCurScope->mDIScope = diFunction;
  13798. auto llvmEntryBlock = methodState.mIREntryBlock;
  13799. mBfIRBuilder->SetInsertPoint(llvmEntryBlock);
  13800. if (methodDef->mBody != NULL)
  13801. {
  13802. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  13803. }
  13804. else if ((mHasFullDebugInfo) && (diFunction) && (typeDef->mTypeDeclaration != NULL))
  13805. {
  13806. // We want to be able to step into delegate invokes -- we actually step over them
  13807. if (methodDef->mName != "Invoke")
  13808. {
  13809. UpdateSrcPos(typeDef->mTypeDeclaration);
  13810. mBfIRBuilder->DbgCreateAnnotation(diFunction, "StepOver", GetConstValue32(1));
  13811. }
  13812. }
  13813. // Clear out DebugLoc - to mark the ".addr" code as part of prologue
  13814. mBfIRBuilder->ClearDebugLocation();
  13815. bool isTypedPrimitiveFunc = mCurTypeInstance->IsTypedPrimitive() && (methodDef->mMethodType != BfMethodType_Ctor);
  13816. int irParamCount = methodInstance->GetIRFunctionParamCount(this);
  13817. if (methodDef->mImportKind != BfImportKind_Dynamic)
  13818. {
  13819. int localIdx = 0;
  13820. int argIdx = 0;
  13821. if (methodInstance->HasStructRet())
  13822. argIdx++;
  13823. //
  13824. bool doDbgAgg = false;
  13825. Array<BfIRValue> splatAddrValues;
  13826. for ( ; argIdx < irParamCount; localIdx++)
  13827. {
  13828. bool isThis = ((localIdx == 0) && (!mCurMethodInstance->mMethodDef->mIsStatic));
  13829. if ((isThis) && (thisType->IsValuelessType()))
  13830. isThis = false;
  13831. BfLocalVariable* paramVar = NULL;
  13832. while (true)
  13833. {
  13834. BF_ASSERT(localIdx < methodState.mLocals.size());
  13835. paramVar = methodState.mLocals[localIdx];
  13836. if ((paramVar->mCompositeCount == -1) &&
  13837. ((!paramVar->mResolvedType->IsValuelessType()) || (paramVar->mResolvedType->IsMethodRef())))
  13838. break;
  13839. localIdx++;
  13840. }
  13841. if ((isThis) && (mCurTypeInstance->IsValueType()) && (methodDef->mMethodType != BfMethodType_Ctor) && (!methodDef->HasNoThisSplat()))
  13842. {
  13843. paramVar->mIsReadOnly = true;
  13844. }
  13845. bool wantsAddr = (wantsDIVariables) || (!paramVar->mIsReadOnly) || (paramVar->mResolvedType->GetLoweredType() != BfTypeCode_None);
  13846. if (paramVar->mResolvedType->IsMethodRef())
  13847. wantsAddr = false;
  13848. // if ((methodDef->mHasAppend) && (argIdx == 1))
  13849. // {
  13850. // BF_ASSERT(paramVar->mName == "appendIdx");
  13851. // wantsAddr = true;
  13852. // }
  13853. if ((!doDbgAgg) && (paramVar->mIsSplat))
  13854. {
  13855. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  13856. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  13857. BfTypeUtils::SplatIterate([&](BfType* checkType)
  13858. {
  13859. BfIRType splatIRType;
  13860. if (checkType->IsComposite())
  13861. splatIRType = mBfIRBuilder->MapType(CreatePointerType(checkType));
  13862. else
  13863. splatIRType = mBfIRBuilder->MapType(checkType);
  13864. auto allocaInst = mBfIRBuilder->CreateAlloca(splatIRType);
  13865. mBfIRBuilder->SetAllocaAlignment(allocaInst, checkType->mAlign);
  13866. if (!paramVar->mAddr)
  13867. paramVar->mAddr = allocaInst;
  13868. if (WantsLifetimes())
  13869. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  13870. splatAddrValues.push_back(allocaInst);
  13871. }, paramVar->mResolvedType);
  13872. mBfIRBuilder->SetInsertPoint(prevInsert);
  13873. }
  13874. else if (isThis)
  13875. {
  13876. if (wantsAddr)
  13877. {
  13878. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  13879. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  13880. BfIRType thisAddrType = mBfIRBuilder->MapType(thisType);
  13881. if (paramVar->mIsSplat)
  13882. {
  13883. if (doDbgAgg)
  13884. {
  13885. auto allocaInst = mBfIRBuilder->CreateAlloca(thisAddrType);
  13886. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  13887. mBfIRBuilder->SetAllocaAlignment(allocaInst, thisType->mAlign);
  13888. paramVar->mAddr = allocaInst;
  13889. if (WantsLifetimes())
  13890. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  13891. }
  13892. }
  13893. else
  13894. {
  13895. bool wantPtr = (thisType->IsComposite()) && (!paramVar->mIsLowered);
  13896. if ((thisType->IsTypedPrimitive()) && (methodDef->HasNoThisSplat()))
  13897. wantPtr = true;
  13898. if (wantPtr)
  13899. {
  13900. thisAddrType = mBfIRBuilder->MapTypeInstPtr(thisType->ToTypeInstance());
  13901. }
  13902. auto allocaInst = mBfIRBuilder->CreateAlloca(thisAddrType);
  13903. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  13904. mBfIRBuilder->SetAllocaAlignment(allocaInst, mSystem->mPtrSize);
  13905. paramVar->mAddr = allocaInst;
  13906. if (WantsLifetimes())
  13907. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  13908. }
  13909. mBfIRBuilder->SetInsertPoint(prevInsert);
  13910. }
  13911. }
  13912. else if ((!isThis) && ((paramVar->mIsStruct) || (paramVar->mResolvedType->IsRef())))
  13913. {
  13914. // Address doesn't change so we don't have to alloca it
  13915. BfIRType allocType;
  13916. int alignSize = mSystem->mPtrSize;
  13917. if (paramVar->mResolvedType->IsRef())
  13918. {
  13919. allocType = mBfIRBuilder->MapType(paramVar->mResolvedType);
  13920. }
  13921. else if ((paramVar->mIsSplat) || (paramVar->mIsLowered))
  13922. {
  13923. allocType = mBfIRBuilder->MapType(paramVar->mResolvedType);
  13924. alignSize = paramVar->mResolvedType->mAlign;
  13925. }
  13926. else
  13927. {
  13928. paramVar->mHasLocalStructBacking = true;
  13929. auto typeInst = paramVar->mResolvedType->ToTypeInstance();
  13930. if (typeInst != NULL)
  13931. allocType = mBfIRBuilder->MapTypeInstPtr(paramVar->mResolvedType->ToTypeInstance());
  13932. else
  13933. allocType = mBfIRBuilder->MapType(CreatePointerType(paramVar->mResolvedType));
  13934. }
  13935. if (wantsAddr)
  13936. {
  13937. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  13938. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  13939. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  13940. auto allocaInst = mBfIRBuilder->CreateAlloca(allocType);
  13941. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  13942. mBfIRBuilder->SetAllocaAlignment(allocaInst, alignSize);
  13943. paramVar->mAddr = allocaInst;
  13944. mBfIRBuilder->SetInsertPoint(prevInsert);
  13945. if (WantsLifetimes())
  13946. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  13947. }
  13948. }
  13949. else if (wantsAddr)
  13950. {
  13951. auto allocaInst = CreateAlloca(paramVar->mResolvedType);
  13952. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  13953. paramVar->mAddr = allocaInst;
  13954. }
  13955. if (paramVar->mIsSplat)
  13956. {
  13957. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  13958. }
  13959. else
  13960. {
  13961. argIdx++;
  13962. }
  13963. }
  13964. if (methodDef->mBody != NULL)
  13965. UpdateSrcPos(methodDef->mBody);
  13966. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  13967. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration);
  13968. int declArgIdx = 0;
  13969. localIdx = 0;
  13970. argIdx = 0;
  13971. if (methodInstance->HasStructRet())
  13972. argIdx++;
  13973. int splatAddrIdx = 0;
  13974. while (localIdx < (int)methodState.mLocals.size())
  13975. {
  13976. int curLocalIdx = localIdx++;
  13977. BfLocalVariable* paramVar = methodState.mLocals[curLocalIdx];
  13978. if (!paramVar->IsParam())
  13979. continue;
  13980. if (paramVar->mCompositeCount != -1)
  13981. continue;
  13982. bool isThis = ((curLocalIdx == 0) && (!mCurMethodInstance->mMethodDef->mIsStatic));
  13983. if ((isThis) && (thisType->IsValuelessType()))
  13984. isThis = false;
  13985. BfIRMDNode diVariable;
  13986. if (wantsDIData)
  13987. {
  13988. String paramName = paramVar->mName;
  13989. BfIRMDNode diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  13990. if (isThis)
  13991. {
  13992. if ((mCurMethodState->mClosureState != NULL) && (mCurMethodState->mClosureState->mClosureType != NULL))
  13993. paramName = "__closure";
  13994. if ((paramVar->mResolvedType->IsValueType()) && (!paramVar->mIsSplat) && (!paramVar->mIsLowered))
  13995. {
  13996. diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  13997. bool wantRef = paramVar->mResolvedType->IsComposite();
  13998. if ((paramVar->mResolvedType->IsTypedPrimitive()) && (methodDef->HasNoThisSplat()))
  13999. wantRef = true;
  14000. if (wantRef)
  14001. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  14002. }
  14003. else if (!paramVar->mResolvedType->IsValueType())
  14004. {
  14005. diType = mBfIRBuilder->DbgCreateArtificialType(diType);
  14006. }
  14007. }
  14008. else
  14009. {
  14010. if ((paramVar->mResolvedType->IsComposite()) && (!paramVar->mIsSplat) && (!paramVar->mIsLowered))
  14011. {
  14012. diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  14013. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  14014. diType = mBfIRBuilder->DbgCreateConstType(diType);
  14015. }
  14016. }
  14017. if ((!paramVar->mIsSplat) || (doDbgAgg))
  14018. {
  14019. if (paramVar->mResolvedType->IsValuelessType())
  14020. {
  14021. diVariable = mBfIRBuilder->DbgCreateAutoVariable(diFunction,
  14022. paramName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  14023. }
  14024. else if (paramVar->mIsImplicitParam)
  14025. {
  14026. // Annotate this specially?
  14027. diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  14028. paramName, argIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, true, 0);
  14029. }
  14030. else
  14031. {
  14032. diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  14033. paramName, argIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, true, 0);
  14034. }
  14035. paramVar->mDbgVarInst = diVariable;
  14036. }
  14037. else if ((paramVar->mIsSplat) && (paramVar->mResolvedType->GetSplatCount() == 0))
  14038. {
  14039. // if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables))
  14040. // {
  14041. // // Only add this placeholder if we don't have any values
  14042. // auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  14043. // paramName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  14044. // mBfIRBuilder->DbgInsertValueIntrinsic(GetConstValue(0), diVariable);
  14045. // }
  14046. }
  14047. }
  14048. bool isTypedPrimCtor = mCurTypeInstance->IsTypedPrimitive() && (methodDef->mMethodType == BfMethodType_Ctor);
  14049. if ((!paramVar->mParamFailed) && (paramVar->mAddr))
  14050. {
  14051. // Write our argument value into the .addr
  14052. mBfIRBuilder->ClearDebugLocation();
  14053. if (paramVar->mIsSplat)
  14054. {
  14055. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  14056. if (doDbgAgg)
  14057. {
  14058. auto curArgIdx = argIdx;
  14059. std::function<void(BfType*, BfIRValue)> checkTypeLambda = [&](BfType* checkType, BfIRValue curDestAddr)
  14060. {
  14061. if (checkType->IsStruct())
  14062. {
  14063. auto checkTypeInstance = checkType->ToTypeInstance();
  14064. if (checkTypeInstance->mBaseType != NULL)
  14065. {
  14066. auto baseDestAddr = mBfIRBuilder->CreateBitCast(curDestAddr, mBfIRBuilder->MapTypeInstPtr(checkTypeInstance->mBaseType));
  14067. checkTypeLambda(checkTypeInstance->mBaseType, baseDestAddr);
  14068. }
  14069. if (checkTypeInstance->mIsUnion)
  14070. {
  14071. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  14072. if (!unionInnerType->IsValuelessType())
  14073. {
  14074. auto newDestAddr = mBfIRBuilder->CreateInBoundsGEP(curDestAddr, 0, 1);
  14075. checkTypeLambda(unionInnerType, newDestAddr);
  14076. }
  14077. if (checkTypeInstance->IsEnum())
  14078. {
  14079. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  14080. auto newDestAddr = mBfIRBuilder->CreateInBoundsGEP(curDestAddr, 0, 2);
  14081. checkTypeLambda(dscrType, newDestAddr);
  14082. }
  14083. }
  14084. else
  14085. {
  14086. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  14087. {
  14088. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  14089. if (fieldInstance->mDataIdx >= 0)
  14090. {
  14091. auto newDestAddr = mBfIRBuilder->CreateInBoundsGEP(curDestAddr, 0, fieldInstance->mDataIdx);
  14092. checkTypeLambda(fieldInstance->GetResolvedType(), newDestAddr);
  14093. }
  14094. }
  14095. }
  14096. }
  14097. else if (checkType->IsMethodRef())
  14098. {
  14099. BF_FATAL("Unimplemented");
  14100. // BfMethodRefType* methodRefType = (BfMethodRefType*)checkType;
  14101. // for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  14102. // {
  14103. // checkTypeLambda->
  14104. // }
  14105. }
  14106. else if (!checkType->IsValuelessType())
  14107. {
  14108. mBfIRBuilder->CreateAlignedStore(mBfIRBuilder->GetArgument(curArgIdx), curDestAddr, paramVar->mResolvedType->mAlign);
  14109. curArgIdx++;
  14110. }
  14111. };
  14112. checkTypeLambda(paramVar->mResolvedType, paramVar->mAddr);
  14113. }
  14114. }
  14115. else
  14116. {
  14117. bool handled = false;
  14118. //if ((!isThis) || (!methodDef->mIsMutating && !methodDef->mNoSplat))
  14119. if (paramVar->mIsLowered)
  14120. {
  14121. auto loweredTypeCode = paramVar->mResolvedType->GetLoweredType();
  14122. BF_ASSERT(loweredTypeCode != BfTypeCode_None);
  14123. if (loweredTypeCode != BfTypeCode_None)
  14124. {
  14125. // We have a lowered type coming in, so we have to cast the .addr before storing
  14126. auto primType = GetPrimitiveType(loweredTypeCode);
  14127. auto primPtrType = CreatePointerType(primType);
  14128. auto primPtrVal = mBfIRBuilder->CreateBitCast(paramVar->mAddr, mBfIRBuilder->MapType(primPtrType));
  14129. mBfIRBuilder->CreateAlignedStore(paramVar->mValue, primPtrVal, paramVar->mResolvedType->mSize);
  14130. // We don't want to allow directly using value
  14131. paramVar->mValue = BfIRValue();
  14132. handled = true;
  14133. }
  14134. }
  14135. if (!handled)
  14136. mBfIRBuilder->CreateAlignedStore(paramVar->mValue, paramVar->mAddr, paramVar->mResolvedType->mAlign);
  14137. }
  14138. }
  14139. if (!isThis)
  14140. declArgIdx++;
  14141. if (methodDef->mBody != NULL)
  14142. UpdateSrcPos(methodDef->mBody);
  14143. else if (methodDef->mDeclaringType->mTypeDeclaration != NULL)
  14144. UpdateSrcPos(methodDef->mDeclaringType->mTypeDeclaration);
  14145. else if (methodDeclaration == NULL)
  14146. UseDefaultSrcPos();
  14147. // Write our argument value into the .addr
  14148. if ((!doDbgAgg) && (paramVar->mIsSplat))
  14149. {
  14150. int splatComponentIdx = 0;
  14151. auto curArgIdx = argIdx;
  14152. auto _FinishSplats = [&] (BfType* checkType, const StringImpl& name)
  14153. {
  14154. BfIRValue splatAddrValue = splatAddrValues[splatAddrIdx++];
  14155. methodState.mSplatDecompAddrs.push_back(splatAddrValue);
  14156. auto storeInst = mBfIRBuilder->CreateAlignedStore(mBfIRBuilder->GetArgument(curArgIdx), splatAddrValue, checkType->mAlign);
  14157. mBfIRBuilder->ClearDebugLocation(storeInst);
  14158. if (wantsDIData)
  14159. {
  14160. BfIRMDNode diType;
  14161. if (checkType->IsComposite())
  14162. diType = mBfIRBuilder->DbgGetType(CreateRefType(checkType));
  14163. else
  14164. diType = mBfIRBuilder->DbgGetType(checkType);
  14165. auto diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  14166. name, curArgIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  14167. if (wantsDIVariables)
  14168. {
  14169. mBfIRBuilder->DbgInsertDeclare(splatAddrValue, diVariable);
  14170. }
  14171. }
  14172. curArgIdx++;
  14173. splatComponentIdx++;
  14174. };
  14175. std::function<void(BfType*, const StringImpl&)> _FinishSplatsIterate = [&](BfType* checkType, const StringImpl& name)
  14176. {
  14177. if (checkType->IsStruct())
  14178. {
  14179. auto checkTypeInstance = checkType->ToTypeInstance();
  14180. if (checkTypeInstance->mBaseType != NULL)
  14181. {
  14182. _FinishSplatsIterate(checkTypeInstance->mBaseType, name + "$b");
  14183. }
  14184. if (checkTypeInstance->mIsUnion)
  14185. {
  14186. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  14187. if (!unionInnerType->IsValuelessType())
  14188. {
  14189. _FinishSplatsIterate(unionInnerType, name + "$u");
  14190. }
  14191. if (checkTypeInstance->IsEnum())
  14192. {
  14193. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  14194. _FinishSplatsIterate(dscrType, name + "$d");
  14195. }
  14196. }
  14197. else
  14198. {
  14199. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  14200. {
  14201. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  14202. auto fieldDef = fieldInstance->GetFieldDef();
  14203. if (fieldInstance->mDataIdx >= 0)
  14204. {
  14205. _FinishSplatsIterate(fieldInstance->GetResolvedType(), name + "$m$" + fieldDef->mName);
  14206. }
  14207. }
  14208. }
  14209. }
  14210. else if (checkType->IsMethodRef())
  14211. {
  14212. auto methodRefType = (BfMethodRefType*)checkType;
  14213. BfMethodInstance* methodInstance = methodRefType->mMethodRef;
  14214. // int implicitParamCount = methodInstance->GetImplicitParamCount();
  14215. // for (int implicitParamIdx = methodInstance->HasThis() ? -1 : 0; implicitParamIdx < implicitParamCount; implicitParamIdx++)
  14216. // {
  14217. // auto paramType = methodInstance->GetParamType(implicitParamIdx);
  14218. // if (!paramType->IsValuelessType())
  14219. // _FinishSplats(paramType, name + "$m$" + methodInstance->GetParamName(implicitParamIdx));
  14220. // }
  14221. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  14222. {
  14223. int paramIdx = methodRefType->GetParamIdxFromDataIdx(dataIdx);
  14224. String paramName = methodInstance->GetParamName(paramIdx);
  14225. if (paramName == "this")
  14226. paramName = "__this";
  14227. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  14228. {
  14229. _FinishSplatsIterate(methodRefType->GetCaptureType(dataIdx), name + "$m$" + paramName);
  14230. }
  14231. else
  14232. {
  14233. _FinishSplats(methodRefType->GetCaptureType(dataIdx), name + "$m$" + paramName);
  14234. }
  14235. }
  14236. }
  14237. else if (!checkType->IsValuelessType())
  14238. {
  14239. _FinishSplats(checkType, name);
  14240. }
  14241. };
  14242. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  14243. if (!paramVar->mConstValue)
  14244. _FinishSplatsIterate(paramVar->mResolvedType, "$" + paramVar->mName);
  14245. }
  14246. BfIRValue declareCall;
  14247. if (diVariable)
  14248. {
  14249. if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables))
  14250. {
  14251. if (!paramVar->mAddr)
  14252. {
  14253. if ((!paramVar->mValue) || (paramVar->mValue.IsFake()))
  14254. {
  14255. if ((!paramVar->mIsThis) && (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU)) // DWARF chokes on this:
  14256. {
  14257. // We don't need to set the location for this
  14258. mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  14259. }
  14260. }
  14261. else
  14262. declareCall = mBfIRBuilder->DbgInsertDeclare(paramVar->mValue, diVariable);
  14263. }
  14264. else
  14265. {
  14266. declareCall = mBfIRBuilder->DbgInsertDeclare(paramVar->mAddr, diVariable);
  14267. }
  14268. }
  14269. }
  14270. if ((isThis) && (!paramVar->mIsSplat) && (paramVar->mAddr))
  14271. {
  14272. // We don't allow actually assignment to "this", so we just do a single load
  14273. // Keep in mind we don't use the ACTUAL mValue value because that's a register, but
  14274. // we need to store it in the stack frame for debugging purposes
  14275. auto loadedThis = mBfIRBuilder->CreateLoad(paramVar->mAddr/*, "this"*/);
  14276. mBfIRBuilder->ClearDebugLocation(loadedThis);
  14277. paramVar->mValue = loadedThis;
  14278. }
  14279. if ((wantsDIData) && (declareCall))
  14280. mBfIRBuilder->UpdateDebugLocation(declareCall);
  14281. if (paramVar->mIsSplat)
  14282. {
  14283. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  14284. }
  14285. else if (!paramVar->mResolvedType->IsValuelessType())
  14286. {
  14287. argIdx++;
  14288. }
  14289. }
  14290. if (wantsDIData)
  14291. {
  14292. BF_ASSERT(splatAddrIdx == (int)splatAddrValues.size());
  14293. }
  14294. }
  14295. for (int varIdx = 0; varIdx < (int)mCurMethodState->mLocals.size(); varIdx++)
  14296. {
  14297. auto paramVar = mCurMethodState->mLocals[varIdx];
  14298. // 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
  14299. // splat member. If the "splat" is valueless then we do create a placeholder, but further up in this method
  14300. // if (paramVar->mIsSplat)
  14301. // {
  14302. // if (wantsDIVariables)
  14303. // {
  14304. // auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(diFunction, paramVar->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(paramVar->mResolvedType));
  14305. // mBfIRBuilder->DbgInsertValueIntrinsic(mBfIRBuilder->CreateConst(BfTypeCode_Int64, 0), diVariable);
  14306. // }
  14307. // }
  14308. if (paramVar->mResolvedType->IsValuelessType())
  14309. {
  14310. if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables) && (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU)) // DWARF chokes on this:
  14311. {
  14312. // Only add this placeholder if we don't have any values
  14313. auto diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  14314. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  14315. paramVar->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  14316. mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  14317. }
  14318. }
  14319. }
  14320. if (IsTargetingBeefBackend())
  14321. mCurMethodState->mCurScope->mValueScopeStart = mBfIRBuilder->CreateValueScopeStart();
  14322. if (methodState.mClosureState != NULL)
  14323. {
  14324. for (auto& constLocal : methodState.mClosureState->mConstLocals)
  14325. {
  14326. BfLocalVariable* localVar = new BfLocalVariable();
  14327. *localVar = constLocal;
  14328. AddLocalVariableDef(localVar, true);
  14329. }
  14330. }
  14331. bool wantsRemoveBody = false;
  14332. bool skipBody = false;
  14333. bool skipUpdateSrcPos = false;
  14334. bool skipEndChecks = false;
  14335. bool hasExternSpecifier = (methodDeclaration != NULL) && (methodDeclaration->mExternSpecifier != NULL) && (methodDef->mImportKind != BfImportKind_Dynamic);
  14336. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  14337. if ((methodDef != NULL) && (propertyDeclaration != NULL) && (propertyDeclaration->mExternSpecifier != NULL))
  14338. hasExternSpecifier = true;
  14339. // Allocate, clear, set classVData
  14340. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mIsStatic))
  14341. {
  14342. CreateStaticCtor();
  14343. }
  14344. else if ((mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType != BfMethodType_Ctor) && (methodDef->mName != BF_METHODNAME_DYNAMICCAST) && (methodDef->mName != BF_METHODNAME_DYNAMICCAST_INTERFACE))
  14345. {
  14346. skipBody = true;
  14347. skipEndChecks = true;
  14348. if (HasCompiledOutput())
  14349. {
  14350. // Clear out DebugLoc - to mark the ".addr" code as part of prologue
  14351. mBfIRBuilder->ClearDebugLocation();
  14352. BfBoxedType* boxedType = (BfBoxedType*) mCurTypeInstance;
  14353. BfTypeInstance* innerType = boxedType->mElementType;
  14354. PopulateType(innerType, BfPopulateType_DataAndMethods);
  14355. mBfIRBuilder->PopulateType(mCurTypeInstance);
  14356. BfGetMethodInstanceFlags flags = BfGetMethodInstanceFlag_None;
  14357. if (methodInstance->mIsForeignMethodDef)
  14358. {
  14359. flags = BfGetMethodInstanceFlag_ForeignMethodDef;
  14360. }
  14361. BfTypeVector methodGenericArguments;
  14362. if (methodInstance->mMethodInfoEx != NULL)
  14363. methodGenericArguments = methodInstance->mMethodInfoEx->mMethodGenericArguments;
  14364. auto innerMethodInstance = GetMethodInstance(innerType, methodDef, methodGenericArguments, flags, methodInstance->GetForeignType());
  14365. if (innerMethodInstance.mMethodInstance->IsSkipCall())
  14366. {
  14367. if (!methodInstance->mReturnType->IsValuelessType())
  14368. {
  14369. auto retVal = GetDefaultValue(methodInstance->mReturnType);
  14370. CreateReturn(retVal);
  14371. }
  14372. }
  14373. else
  14374. {
  14375. BF_ASSERT(innerMethodInstance.mMethodInstance->mMethodDef == methodDef);
  14376. SizedArray<BfIRValue, 8> innerParams;
  14377. BfExprEvaluator exprEvaluator(this);
  14378. if (!innerType->IsValuelessType())
  14379. {
  14380. BfIRValue thisValue = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, 1);
  14381. BfTypedValue innerVal(thisValue, innerType, true);
  14382. if (boxedType->IsBoxedStructPtr())
  14383. {
  14384. innerVal = LoadValue(innerVal);
  14385. innerVal = BfTypedValue(innerVal.mValue, innerType, true);
  14386. }
  14387. exprEvaluator.PushThis(NULL, innerVal, innerMethodInstance.mMethodInstance, innerParams);
  14388. }
  14389. for (int i = 1; i < (int)mCurMethodState->mLocals.size(); i++)
  14390. {
  14391. BfLocalVariable* localVar = mCurMethodState->mLocals[i];
  14392. BfTypedValue localVal = exprEvaluator.LoadLocal(localVar, true);
  14393. exprEvaluator.PushArg(localVal, innerParams);
  14394. }
  14395. if (!innerMethodInstance.mFunc)
  14396. {
  14397. BF_ASSERT(innerType->IsUnspecializedType());
  14398. }
  14399. else if (methodInstance->HasStructRet())
  14400. {
  14401. mBfIRBuilder->PopulateType(methodInstance->mReturnType);
  14402. auto returnType = BfTypedValue(mBfIRBuilder->GetArgument(0), methodInstance->mReturnType, true);
  14403. exprEvaluator.mReceivingValue = &returnType;
  14404. auto retVal = exprEvaluator.CreateCall(innerMethodInstance.mMethodInstance, innerMethodInstance.mFunc, true, innerParams, NULL, true);
  14405. BF_ASSERT(exprEvaluator.mReceivingValue == NULL); // Ensure it was actually used
  14406. mBfIRBuilder->CreateRetVoid();
  14407. }
  14408. else
  14409. {
  14410. mBfIRBuilder->PopulateType(methodInstance->mReturnType);
  14411. auto retVal = exprEvaluator.CreateCall(innerMethodInstance.mMethodInstance, innerMethodInstance.mFunc, true, innerParams, NULL, true);
  14412. if (mCurMethodInstance->mReturnType->IsValueType())
  14413. retVal = LoadValue(retVal);
  14414. CreateReturn(retVal.mValue);
  14415. }
  14416. }
  14417. }
  14418. mCurMethodState->SetHadReturn(true);
  14419. mCurMethodState->mLeftBlockUncond = true;
  14420. }
  14421. else if (methodDef->mMethodType == BfMethodType_CtorClear)
  14422. {
  14423. SetIllegalSrcPos();
  14424. mBfIRBuilder->ClearDebugLocation();
  14425. PopulateType(mCurTypeInstance, BfPopulateType_Data);
  14426. auto thisVal = GetThis();
  14427. int prevSize = mContext->mBfObjectType->mInstSize;
  14428. int curSize = mCurTypeInstance->mInstSize;
  14429. if (curSize > prevSize)
  14430. {
  14431. auto int8PtrType = CreatePointerType(GetPrimitiveType(BfTypeCode_Int8));
  14432. auto int8PtrVal = mBfIRBuilder->CreateBitCast(thisVal.mValue, mBfIRBuilder->MapType(int8PtrType));
  14433. int8PtrVal = mBfIRBuilder->CreateInBoundsGEP(int8PtrVal, GetConstValue(prevSize));
  14434. mBfIRBuilder->CreateMemSet(int8PtrVal, GetConstValue8(0), GetConstValue(curSize - prevSize), GetConstValue(mCurTypeInstance->mInstAlign));
  14435. }
  14436. skipUpdateSrcPos = true;
  14437. }
  14438. else if (((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorNoBody)) && (!hasExternSpecifier))
  14439. {
  14440. EmitCtorBody(skipBody);
  14441. }
  14442. else if ((methodDef->mMethodType == BfMethodType_Dtor) && (!hasExternSpecifier))
  14443. {
  14444. EmitDtorBody();
  14445. skipBody = true;
  14446. }
  14447. if ((!mCurTypeInstance->IsBoxed()) && (methodDeclaration != NULL) && (methodDeclaration->mHadYield) && (methodDef->mBody != NULL))
  14448. {
  14449. EmitIteratorBlock(skipBody);
  14450. }
  14451. if (methodDef->mName == BF_METHODNAME_MARKMEMBERS)
  14452. {
  14453. // We need to be able to mark deleted objects
  14454. mCurMethodState->mIgnoreObjectAccessCheck = true;
  14455. }
  14456. auto customAttributes = methodInstance->GetCustomAttributes();
  14457. if ((customAttributes != NULL) && (customAttributes->Contains(mCompiler->mDisableObjectAccessChecksAttributeTypeDef)))
  14458. mCurMethodState->mIgnoreObjectAccessCheck = true;
  14459. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) && (!methodDef->mIsStatic) &&
  14460. ((methodInstance->mChainType == BfMethodChainType_ChainHead) || (methodInstance->mChainType == BfMethodChainType_None)))
  14461. {
  14462. // We chain even non-default ctors to the default ctors
  14463. auto defaultCtor = methodInstance;
  14464. if (defaultCtor->mChainType == BfMethodChainType_ChainHead)
  14465. CallChainedMethods(defaultCtor, false);
  14466. }
  14467. auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody);
  14468. if (methodDef->mBody == NULL)
  14469. {
  14470. if (methodDeclaration != NULL)
  14471. {
  14472. if (auto operatorDeclaration = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  14473. {
  14474. if (operatorDeclaration->mIsConvOperator)
  14475. wantsRemoveBody = true;
  14476. }
  14477. }
  14478. bool isDllImport = false;
  14479. if (methodDef->mImportKind == BfImportKind_Static)
  14480. {
  14481. for (auto customAttr : methodInstance->GetCustomAttributes()->mAttributes)
  14482. {
  14483. if (customAttr.mType->mTypeDef->mFullName.ToString() == "System.ImportAttribute")
  14484. {
  14485. if (customAttr.mCtorArgs.size() == 1)
  14486. {
  14487. auto fileNameArg = customAttr.mCtorArgs[0];
  14488. int strNum = 0;
  14489. auto constant = mCurTypeInstance->mConstHolder->GetConstant(fileNameArg);
  14490. if (constant != NULL)
  14491. {
  14492. if (constant->IsNull())
  14493. continue; // Invalid
  14494. strNum = constant->mInt32;
  14495. }
  14496. else
  14497. {
  14498. strNum = GetStringPoolIdx(fileNameArg, mCurTypeInstance->mConstHolder);
  14499. }
  14500. if (!mImportFileNames.Contains(strNum))
  14501. mImportFileNames.Add(strNum);
  14502. }
  14503. }
  14504. }
  14505. //mImportFileNames
  14506. }
  14507. else if (methodDef->mImportKind == BfImportKind_Dynamic)
  14508. {
  14509. CreateDllImportMethod();
  14510. }
  14511. else if (((mCurTypeInstance->mTypeDef->mIsDelegate) || (mCurTypeInstance->mTypeDef->mIsFunction)) &&
  14512. (methodDef->mName == "Invoke") && (methodDef->mMethodType == BfMethodType_Normal))
  14513. {
  14514. if (mCurTypeInstance->mTypeDef->mIsFunction)
  14515. {
  14516. // Emit nothing
  14517. }
  14518. else
  14519. {
  14520. CreateDelegateInvokeMethod();
  14521. mCurMethodState->SetHadReturn(true);
  14522. mCurMethodState->mLeftBlockUncond = true;
  14523. }
  14524. }
  14525. else if ((methodDef->mName == BF_METHODNAME_DYNAMICCAST) || (methodDef->mName == BF_METHODNAME_DYNAMICCAST_INTERFACE))
  14526. {
  14527. if (mCurTypeInstance->IsObject())
  14528. {
  14529. CreateDynamicCastMethod();
  14530. }
  14531. else
  14532. {
  14533. mBfIRBuilder->CreateRet(GetDefaultValue(methodInstance->mReturnType));
  14534. mCurMethodState->mHadReturn = true;
  14535. }
  14536. }
  14537. else if ((methodDef->mName == BF_METHODNAME_ENUM_HASFLAG) && (mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()))
  14538. {
  14539. BfIRValue ret;
  14540. if (mCurMethodState->mLocals[1]->mResolvedType != mCurTypeInstance)
  14541. {
  14542. // This can happen if we provide an invalid name
  14543. AssertErrorState();
  14544. ret = mBfIRBuilder->CreateRet(GetDefaultValue(GetPrimitiveType(BfTypeCode_Boolean)));
  14545. }
  14546. else
  14547. {
  14548. // Unfortunate DebugLoc shenanigans-
  14549. // 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,
  14550. // so we only set the loc on the CreateRet which gets inlined out
  14551. mBfIRBuilder->SaveDebugLocation();
  14552. mBfIRBuilder->ClearDebugLocation();
  14553. BfIRValue fromBool;
  14554. if (!mCurTypeInstance->IsTypedPrimitive())
  14555. {
  14556. fromBool = GetDefaultValue(methodInstance->mReturnType);
  14557. }
  14558. else
  14559. {
  14560. auto andResult = mBfIRBuilder->CreateAnd(mCurMethodState->mLocals[0]->mValue, mCurMethodState->mLocals[1]->mValue);
  14561. auto toBool = mBfIRBuilder->CreateCmpNE(andResult, GetDefaultValue(mCurMethodState->mLocals[0]->mResolvedType));
  14562. fromBool = mBfIRBuilder->CreateNumericCast(toBool, false, BfTypeCode_Boolean);
  14563. }
  14564. mBfIRBuilder->RestoreDebugLocation();
  14565. ret = mBfIRBuilder->CreateRet(fromBool);
  14566. //ExtendLocalLifetimes(0);
  14567. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  14568. }
  14569. mCurMethodState->SetHadReturn(true);
  14570. mCurMethodState->mLeftBlockUncond = true;
  14571. }
  14572. else if (((methodDef->mName == BF_METHODNAME_ENUM_GETUNDERLYINGREF) || (methodDef->mName == BF_METHODNAME_ENUM_GETUNDERLYING)) &&
  14573. (mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()))
  14574. {
  14575. BfIRValue ret;
  14576. // Unfortunate DebugLoc shenanigans-
  14577. // 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,
  14578. // so we only set the loc on the CreateRet which gets inlined out
  14579. mBfIRBuilder->SaveDebugLocation();
  14580. mBfIRBuilder->ClearDebugLocation();
  14581. BfIRValue fromBool;
  14582. mBfIRBuilder->RestoreDebugLocation();
  14583. ret = mBfIRBuilder->CreateRet(GetThis().mValue);
  14584. //ExtendLocalLifetimes(0);
  14585. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  14586. mCurMethodState->SetHadReturn(true);
  14587. mCurMethodState->mLeftBlockUncond = true;
  14588. }
  14589. else if ((mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()) && (methodDef->mName == BF_METHODNAME_TO_STRING))
  14590. {
  14591. auto enumType = ResolveTypeDef(mCompiler->mEnumTypeDef);
  14592. if (HasCompiledOutput())
  14593. {
  14594. EmitEnumToStringBody();
  14595. }
  14596. mBfIRBuilder->CreateRetVoid();
  14597. mCurMethodState->SetHadReturn(true);
  14598. mCurMethodState->mLeftBlockUncond = true;
  14599. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  14600. }
  14601. else if ((mCurTypeInstance->IsTuple()) && (!mCurTypeInstance->IsBoxed()) && (methodDef->mName == BF_METHODNAME_TO_STRING))
  14602. {
  14603. auto enumType = ResolveTypeDef(mCompiler->mEnumTypeDef);
  14604. if (HasCompiledOutput())
  14605. {
  14606. EmitTupleToStringBody();
  14607. }
  14608. mBfIRBuilder->CreateRetVoid();
  14609. mCurMethodState->SetHadReturn(true);
  14610. mCurMethodState->mLeftBlockUncond = true;
  14611. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  14612. }
  14613. else if (methodDef->mName == BF_METHODNAME_DEFAULT_EQUALS)
  14614. {
  14615. CreateValueTypeEqualsMethod();
  14616. skipBody = true;
  14617. skipEndChecks = true;
  14618. }
  14619. else if ((methodDef->mName == BF_METHODNAME_EQUALS) && (typeDef == mCompiler->mValueTypeTypeDef))
  14620. {
  14621. CreateValueTypeEqualsMethod();
  14622. skipBody = true;
  14623. skipEndChecks = true;
  14624. }
  14625. else if (HasCompiledOutput())
  14626. {
  14627. if ((methodDef->mName == BF_METHODNAME_MARKMEMBERS) || (methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC))
  14628. {
  14629. if (mCompiler->mOptions.mEnableRealtimeLeakCheck)
  14630. {
  14631. EmitGCMarkMembers();
  14632. }
  14633. else if (!mCurTypeInstance->IsObject())
  14634. {
  14635. }
  14636. }
  14637. else if (methodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS)
  14638. {
  14639. if (mCompiler->mOptions.mEnableRealtimeLeakCheck)
  14640. {
  14641. EmitGCFindTLSMembers();
  14642. }
  14643. }
  14644. }
  14645. }
  14646. else if (!skipBody)
  14647. {
  14648. bool isEmptyBodied = BfNodeDynCast<BfTokenNode>(methodDef->mBody) != NULL;
  14649. if (isEmptyBodied) // Generate autoProperty things
  14650. {
  14651. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  14652. if ((propertyDeclaration != NULL) && (!typeDef->HasAutoProperty(propertyDeclaration)))
  14653. {
  14654. if ((!mCurTypeInstance->IsInterface()) && (!hasExternSpecifier))
  14655. Fail("Body expected", methodDef->mBody);
  14656. }
  14657. else if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  14658. {
  14659. if (methodInstance->mReturnType->IsValuelessType())
  14660. {
  14661. mBfIRBuilder->CreateRetVoid();
  14662. }
  14663. else if (HasCompiledOutput())
  14664. {
  14665. String autoPropName = typeDef->GetAutoPropertyName(propertyDeclaration);
  14666. BfFieldInstance* fieldInstance = GetFieldByName(mCurTypeInstance, autoPropName);
  14667. BfFieldDef* fieldDef = NULL;
  14668. if (fieldInstance != NULL)
  14669. fieldDef = fieldInstance->GetFieldDef();
  14670. BfType* retType = methodInstance->mReturnType;
  14671. if (retType->IsRef())
  14672. retType = retType->GetUnderlyingType();
  14673. if ((fieldInstance != NULL) && (fieldInstance->GetResolvedType() == retType) &&
  14674. ((fieldInstance->mDataIdx >= 0) || (fieldDef->IsNonConstStatic())))
  14675. {
  14676. BfTypedValue lookupValue;
  14677. if (fieldDef->IsNonConstStatic())
  14678. lookupValue = ReferenceStaticField(fieldInstance);
  14679. else if (mCurTypeInstance->IsObject())
  14680. lookupValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(GetThis().mValue, 0, fieldInstance->mDataIdx), fieldInstance->mResolvedType, true);
  14681. else
  14682. lookupValue = ExtractValue(GetThis(), fieldInstance, fieldInstance->mFieldIdx);
  14683. if (!methodInstance->mReturnType->IsRef())
  14684. lookupValue = LoadValue(lookupValue);
  14685. mBfIRBuilder->CreateRet(lookupValue.mValue);
  14686. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  14687. }
  14688. else
  14689. {
  14690. // This can happen if we have two properties with the same name but different types
  14691. AssertErrorState();
  14692. mBfIRBuilder->CreateRet(GetDefaultValue(methodInstance->mReturnType));
  14693. }
  14694. }
  14695. else
  14696. {
  14697. // During autocomplete, the actual type may not have the proper field instance
  14698. mBfIRBuilder->CreateRet(GetDefaultValue(methodInstance->mReturnType));
  14699. }
  14700. mCurMethodState->SetHadReturn(true);
  14701. }
  14702. else if (methodDef->mMethodType == BfMethodType_PropertySetter)
  14703. {
  14704. if (!mCompiler->IsAutocomplete())
  14705. {
  14706. String autoPropName = typeDef->GetAutoPropertyName(propertyDeclaration);
  14707. BfFieldInstance* fieldInstance = GetFieldByName(mCurTypeInstance, autoPropName);
  14708. auto fieldDef = fieldInstance->GetFieldDef();
  14709. auto& lastParam = mCurMethodState->mLocals.back();
  14710. if ((fieldInstance != NULL) && (fieldInstance->GetResolvedType() == lastParam->mResolvedType) &&
  14711. ((fieldInstance->mDataIdx >= 0) || (fieldDef->IsNonConstStatic())))
  14712. {
  14713. BfIRValue lookupAddr;
  14714. if (fieldDef->IsNonConstStatic())
  14715. lookupAddr = ReferenceStaticField(fieldInstance).mValue;
  14716. else
  14717. {
  14718. auto thisValue = GetThis();
  14719. if (thisValue.IsSplat())
  14720. {
  14721. BF_FATAL("Should not happen");
  14722. }
  14723. if (mCurTypeInstance->IsObject())
  14724. thisValue = LoadValue(thisValue);
  14725. lookupAddr = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInstance->mDataIdx);
  14726. }
  14727. mBfIRBuilder->CreateStore(lastParam->mValue, lookupAddr);
  14728. }
  14729. else if (!fieldInstance->mResolvedType->IsValuelessType())
  14730. {
  14731. // This can happen if we have two properties with the same name but different types
  14732. AssertErrorState();
  14733. }
  14734. }
  14735. }
  14736. }
  14737. if ((!mCurMethodInstance->mReturnType->IsValuelessType()) && (!isEmptyBodied))
  14738. {
  14739. mBfIRBuilder->PopulateType(mCurMethodInstance->mReturnType);
  14740. if (mCurMethodInstance->HasStructRet())
  14741. {
  14742. auto ptrType = CreatePointerType(mCurMethodInstance->mReturnType);
  14743. auto allocaInst = AllocLocalVariable(ptrType, "__return.addr", false);
  14744. auto storeInst = mBfIRBuilder->CreateStore(mBfIRBuilder->GetArgument(0), allocaInst);
  14745. mBfIRBuilder->ClearDebugLocation(storeInst);
  14746. mCurMethodState->mRetValAddr = allocaInst;
  14747. }
  14748. else
  14749. {
  14750. auto allocaInst = AllocLocalVariable(mCurMethodInstance->mReturnType, "__return", false);
  14751. mCurMethodState->mRetVal = BfTypedValue(allocaInst, mCurMethodInstance->mReturnType, true);
  14752. }
  14753. }
  14754. if (methodDef->mMethodType == BfMethodType_CtorCalcAppend)
  14755. {
  14756. mBfIRBuilder->CreateStore(GetConstValue(0), mCurMethodState->mRetVal.mValue);
  14757. BfGetSymbolReferenceKind prevSymbolKind;
  14758. BfAutoComplete* prevAutoComplete;
  14759. if (mCompiler->mResolvePassData != NULL)
  14760. {
  14761. prevSymbolKind = mCompiler->mResolvePassData->mGetSymbolReferenceKind;
  14762. prevAutoComplete = mCompiler->mResolvePassData->mAutoComplete;
  14763. mCompiler->mResolvePassData->mGetSymbolReferenceKind = BfGetSymbolReferenceKind_None;
  14764. }
  14765. EmitCtorCalcAppend();
  14766. if (mCompiler->mResolvePassData != NULL)
  14767. {
  14768. mCompiler->mResolvePassData->mGetSymbolReferenceKind = prevSymbolKind;
  14769. mCompiler->mResolvePassData->mAutoComplete = prevAutoComplete;
  14770. }
  14771. }
  14772. else if (!isEmptyBodied)
  14773. {
  14774. if (!mCurMethodState->mIRExitBlock)
  14775. mCurMethodState->mIRExitBlock = mBfIRBuilder->CreateBlock("exit", true);
  14776. bool isExpressionBody = false;
  14777. if (methodDeclaration != NULL)
  14778. {
  14779. if (methodDeclaration->mFatArrowToken != NULL)
  14780. isExpressionBody = true;
  14781. }
  14782. else if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  14783. {
  14784. if (auto propBodyExpr = BfNodeDynCast<BfPropertyBodyExpression>(propertyDeclaration->mDefinitionBlock))
  14785. {
  14786. isExpressionBody = true;
  14787. }
  14788. }
  14789. else
  14790. {
  14791. if (auto block = BfNodeDynCast<BfBlock>(methodDef->mBody))
  14792. {
  14793. if (!block->mChildArr.IsEmpty())
  14794. {
  14795. if (auto exprStmt = BfNodeDynCast<BfExpressionStatement>(block->mChildArr.GetLast()))
  14796. {
  14797. if (exprStmt->mTrailingSemicolon == NULL)
  14798. isExpressionBody = true;
  14799. }
  14800. }
  14801. }
  14802. else
  14803. isExpressionBody = true;
  14804. }
  14805. if (auto fieldDtorBody = BfNodeDynCast<BfFieldDtorDeclaration>(methodDef->mBody))
  14806. {
  14807. while (fieldDtorBody != NULL)
  14808. {
  14809. VisitEmbeddedStatement(fieldDtorBody->mBody);
  14810. fieldDtorBody = fieldDtorBody->mNextFieldDtor;
  14811. }
  14812. }
  14813. else if (!isExpressionBody)
  14814. {
  14815. auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody);
  14816. mCurMethodState->mHeadScope.mAstBlock = bodyBlock;
  14817. mCurMethodState->mHeadScope.mCloseNode = bodyBlock->mCloseBrace;
  14818. VisitCodeBlock(bodyBlock);
  14819. }
  14820. else if (auto expressionBody = BfNodeDynCast<BfExpression>(methodDef->mBody))
  14821. {
  14822. if ((methodDef->mMethodType != BfMethodType_Normal) && (propertyDeclaration == NULL))
  14823. {
  14824. BF_ASSERT(methodDeclaration->mFatArrowToken != NULL);
  14825. Fail("Only normal methods can have expression bodies", methodDeclaration->mFatArrowToken);
  14826. }
  14827. auto expectingType = mCurMethodInstance->mReturnType;
  14828. // if ((expectingType->IsVoid()) && (IsInSpecializedSection()))
  14829. // {
  14830. // Warn(0, "Using a 'void' return with an expression-bodied method isn't needed. Consider removing '=>' token", methodDeclaration->mFatArrowToken);
  14831. // }
  14832. //TODO: Why did we have all this stuff for handling void?
  14833. // if (expectingType->IsVoid())
  14834. // {
  14835. // bool wasReturnGenericParam = false;
  14836. // if ((mCurMethodState->mClosureState != NULL) && (mCurMethodState->mClosureState->mReturnType != NULL))
  14837. // {
  14838. // wasReturnGenericParam = mCurMethodState->mClosureState->mReturnType->IsGenericParam();
  14839. // }
  14840. // else
  14841. // {
  14842. // auto unspecializedMethodInstance = GetUnspecializedMethodInstance(mCurMethodInstance);
  14843. // if ((unspecializedMethodInstance != NULL) && (unspecializedMethodInstance->mReturnType->IsGenericParam()))
  14844. // wasReturnGenericParam = true;
  14845. // }
  14846. //
  14847. // // If we the void return was from a generic specialization, allow us to return a void result,
  14848. // // otherwise treat expression as though it must be a statement
  14849. // bool isStatement = expressionBody->VerifyIsStatement(mCompiler->mPassInstance, wasReturnGenericParam);
  14850. // if (isStatement)
  14851. // expectingType = NULL;
  14852. // }
  14853. UpdateSrcPos(expressionBody);
  14854. auto retVal = CreateValueFromExpression(expressionBody, expectingType);
  14855. if ((retVal) && (expectingType != NULL))
  14856. {
  14857. mCurMethodState->mHadReturn = true;
  14858. retVal = LoadValue(retVal);
  14859. EmitReturn(retVal.mValue);
  14860. }
  14861. }
  14862. }
  14863. }
  14864. BF_ASSERT(mCurMethodState->mCurScope == &mCurMethodState->mHeadScope);
  14865. if (skipUpdateSrcPos)
  14866. {
  14867. // Skip
  14868. }
  14869. else if ((bodyBlock != NULL) && (bodyBlock->mCloseBrace != NULL))
  14870. UpdateSrcPos(bodyBlock->mCloseBrace);
  14871. else if (methodDef->mBody != NULL)
  14872. UpdateSrcPos(methodDef->mBody);
  14873. else if (methodDeclaration != NULL)
  14874. UpdateSrcPos(methodDeclaration);
  14875. else if (methodDef->mDeclaringType->mTypeDeclaration != NULL)
  14876. UpdateSrcPos(methodDef->mDeclaringType->mTypeDeclaration);
  14877. else
  14878. UseDefaultSrcPos();
  14879. if (methodDef->mMethodType == BfMethodType_CtorCalcAppend)
  14880. {
  14881. if (mCurMethodState->mRetVal)
  14882. {
  14883. mCurMethodState->SetHadReturn(true);
  14884. auto retVal = mBfIRBuilder->CreateLoad(mCurMethodState->mRetVal.mValue);
  14885. mBfIRBuilder->CreateRet(retVal);
  14886. }
  14887. else
  14888. AssertErrorState();
  14889. }
  14890. if (!mCurMethodState->mHadReturn)
  14891. {
  14892. // Clear off the stackallocs that have occurred after a scopeData break
  14893. EmitDeferredScopeCalls(false, &mCurMethodState->mHeadScope, mCurMethodState->mIRExitBlock);
  14894. }
  14895. if (mCurMethodState->mIRExitBlock)
  14896. {
  14897. for (auto preExitBlock : mCurMethodState->mHeadScope.mAtEndBlocks)
  14898. mBfIRBuilder->MoveBlockToEnd(preExitBlock);
  14899. mBfIRBuilder->MoveBlockToEnd(mCurMethodState->mIRExitBlock);
  14900. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRExitBlock);
  14901. if (!mCurMethodState->mDIRetVal)
  14902. CreateDIRetVal();
  14903. }
  14904. for (auto localVar : mCurMethodState->mLocals)
  14905. {
  14906. if ((skipEndChecks) || (bodyBlock == NULL))
  14907. break;
  14908. LocalVariableDone(localVar, true);
  14909. }
  14910. if (mCurMethodState->mIRExitBlock)
  14911. {
  14912. if ((mCurMethodState->mRetVal) && (!mCurMethodInstance->HasStructRet()))
  14913. {
  14914. auto loadedVal = mBfIRBuilder->CreateLoad(mCurMethodState->mRetVal.mValue);
  14915. CreateReturn(loadedVal);
  14916. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  14917. if (mCurMethodState->mDIRetVal)
  14918. mBfIRBuilder->DbgLifetimeEnd(mCurMethodState->mDIRetVal);
  14919. }
  14920. else
  14921. {
  14922. // Have something on the last line to step onto
  14923. if (mHasFullDebugInfo)
  14924. {
  14925. if ((bodyBlock != NULL) && (bodyBlock->mCloseBrace != NULL))
  14926. UpdateSrcPos(bodyBlock->mCloseBrace);
  14927. EmitEnsureInstructionAt();
  14928. if ((irParamCount == 0) && (!IsTargetingBeefBackend()) && (mCompiler->mOptions.mAllowHotSwapping))
  14929. {
  14930. // This may be a case where we only emit 4 bytes, whereas we need 5 for a hot replace jump
  14931. mBfIRBuilder->EnsureFunctionPatchable();
  14932. }
  14933. }
  14934. mBfIRBuilder->CreateRetVoid();
  14935. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  14936. if (mCurMethodState->mDIRetVal)
  14937. mBfIRBuilder->DbgLifetimeEnd(mCurMethodState->mDIRetVal);
  14938. }
  14939. }
  14940. if ((mCurMethodInstance->mReturnType == NULL) || (mCurMethodInstance->mReturnType->IsValuelessType()))
  14941. {
  14942. if ((!mCurMethodState->mHadReturn) && (!mCurMethodState->mIRExitBlock))
  14943. {
  14944. if ((irParamCount == 0) && (!IsTargetingBeefBackend()) && (mCompiler->mOptions.mAllowHotSwapping))
  14945. {
  14946. // This may be a case where we only emit 4 bytes, whereas we need 5 for a hot replace jump
  14947. mBfIRBuilder->EnsureFunctionPatchable();
  14948. }
  14949. mBfIRBuilder->CreateRetVoid();
  14950. }
  14951. }
  14952. else
  14953. {
  14954. if (!mCurMethodState->mHadReturn)
  14955. {
  14956. auto refNode = mCurMethodInstance->mMethodDef->GetRefNode();
  14957. if (bodyBlock != NULL)
  14958. {
  14959. if (bodyBlock->mCloseBrace != NULL)
  14960. {
  14961. BfAstNode* target = bodyBlock->mCloseBrace;
  14962. Fail("Method must return value", target);
  14963. }
  14964. else
  14965. {
  14966. // It's possible to not have a closing brace if the method ends in an EOF
  14967. AssertErrorState();
  14968. }
  14969. }
  14970. }
  14971. }
  14972. // Move 'init' into 'entry'
  14973. mBfIRBuilder->MergeBlockDown(mCurMethodState->mIRInitBlock, mCurMethodState->mIREntryBlock);
  14974. mBfIRBuilder->MergeBlockDown(mCurMethodState->mIRHeadBlock, mCurMethodState->mIREntryBlock);
  14975. if ((mCurMethodInstance->mIsUnspecialized) /*|| (typeDef->mIsFunction)*/ || (mCurTypeInstance->IsUnspecializedType()))
  14976. {
  14977. // Don't keep instructions for unspecialized types
  14978. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  14979. }
  14980. if ((hasExternSpecifier) && (!skipBody))
  14981. {
  14982. // If we hot swap, we want to make sure at least one method refers to this extern method so it gets pulled in
  14983. // incase it gets called later by some hot-loaded coded
  14984. if (mCompiler->mOptions.mAllowHotSwapping)
  14985. CreateFakeCallerMethod(mangledName);
  14986. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  14987. }
  14988. else if ((methodDef->mImportKind == BfImportKind_Dynamic) && (!mCompiler->IsHotCompile()))
  14989. {
  14990. // We only need the DLL stub when we may be hot swapping
  14991. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  14992. }
  14993. else if (wantsRemoveBody)
  14994. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  14995. // We don't want to hold on to pointers to LLVMFunctions of unspecialized types.
  14996. // This allows us to delete the mScratchModule LLVM module without rebuilding all
  14997. // unspecialized types
  14998. if ((mCurTypeInstance->IsUnspecializedType()) || (mCurTypeInstance->IsInterface()))
  14999. {
  15000. BfLogSysM("ProcessMethod Clearing IRFunction: %p\n", methodInstance);
  15001. methodInstance->mIRFunction = BfIRFunction();
  15002. }
  15003. CheckAddFailType();
  15004. if (mHadBuildError)
  15005. prevHadBuildError.CancelRestore();
  15006. if (mHadBuildWarning)
  15007. prevHadWarning.CancelRestore();
  15008. if (!methodDef->mIsLocalMethod)
  15009. ProcessMethod_ProcessDeferredLocals();
  15010. mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  15011. if (methodState.mHotDataReferenceBuilder != NULL)
  15012. {
  15013. AddHotDataReferences(&hotDataReferenceBuilder);
  15014. }
  15015. else
  15016. {
  15017. if ((methodInstance->mHotMethod != NULL) && (!methodInstance->mIsReified))
  15018. {
  15019. // Remove the hot method data
  15020. auto hotMethod = methodInstance->mHotMethod;
  15021. auto prevMethod = hotMethod->mPrevVersion;
  15022. if (prevMethod != NULL)
  15023. {
  15024. // If there's a prev method then pull its data into the main HotMethod.
  15025. // This, in effect, removes the 'hotMethod' data and rebases 'prevMethod'
  15026. // over to the main HotMethod definition to keep the HotMethod address
  15027. // invariant
  15028. for (auto ref : hotMethod->mReferences)
  15029. ref->Deref();
  15030. hotMethod->mReferences.Clear();
  15031. BF_ASSERT(prevMethod->mRefCount == 1);
  15032. hotMethod->mReferences = prevMethod->mReferences;
  15033. if (hotMethod->mSrcTypeVersion != NULL)
  15034. hotMethod->mSrcTypeVersion->Deref();
  15035. hotMethod->mSrcTypeVersion = prevMethod->mSrcTypeVersion;
  15036. prevMethod->mSrcTypeVersion = NULL;
  15037. prevMethod->mReferences.Clear();
  15038. hotMethod->mPrevVersion = prevMethod->mPrevVersion;
  15039. prevMethod->mPrevVersion = NULL;
  15040. prevMethod->Deref();
  15041. }
  15042. hotMethod->Deref();
  15043. methodInstance->mHotMethod = NULL;
  15044. }
  15045. }
  15046. }
  15047. String BfModule::GetLocalMethodName(const StringImpl& baseName, BfAstNode* anchorNode, BfMethodState* declMethodState, BfMixinState* declMixinState)
  15048. {
  15049. String name;
  15050. bool found = false;
  15051. auto checkMethodState = mCurMethodState;
  15052. while (checkMethodState != NULL)
  15053. {
  15054. if (checkMethodState->mClosureState == NULL)
  15055. break;
  15056. if (checkMethodState->mClosureState->mClosureMethodDef != NULL)
  15057. {
  15058. found = true;
  15059. name += checkMethodState->mClosureState->mClosureMethodDef->mName;
  15060. break;
  15061. }
  15062. checkMethodState = checkMethodState->mPrevMethodState;
  15063. }
  15064. if (!found)
  15065. name += mCurMethodInstance->mMethodDef->mName;
  15066. int prevSepPos = (int)name.LastIndexOf('$');
  15067. if (prevSepPos != -1)
  15068. {
  15069. name.RemoveToEnd(prevSepPos);
  15070. }
  15071. name += "@";
  15072. name += baseName;
  15073. HashContext hashCtx;
  15074. if (anchorNode != NULL)
  15075. {
  15076. hashCtx.Mixin(anchorNode->GetStartCharId());
  15077. }
  15078. //
  15079. {
  15080. auto checkMethodState = declMethodState;
  15081. auto checkMixinState = declMixinState;
  15082. while (checkMethodState != NULL)
  15083. {
  15084. if (checkMixinState != NULL)
  15085. {
  15086. hashCtx.Mixin(checkMixinState->mSource->GetStartCharId());
  15087. }
  15088. checkMethodState = checkMethodState->mPrevMethodState;
  15089. if (checkMethodState != NULL)
  15090. checkMixinState = checkMethodState->mMixinState;
  15091. }
  15092. }
  15093. auto rootMethodState = mCurMethodState->GetRootMethodState();
  15094. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  15095. {
  15096. for (auto methodGenericArg : rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  15097. {
  15098. StringT<128> genericTypeName;
  15099. BfMangler::Mangle(genericTypeName, mCompiler->GetMangleKind(), methodGenericArg);
  15100. hashCtx.MixinStr(genericTypeName);
  15101. }
  15102. }
  15103. uint64 hashVal = hashCtx.Finish64();
  15104. name += "$";
  15105. name += BfTypeUtils::HashEncode64(hashVal);
  15106. return name;
  15107. }
  15108. BfMethodDef* BfModule::GetLocalMethodDef(BfLocalMethod* localMethod)
  15109. {
  15110. if (localMethod->mMethodDef != NULL)
  15111. return localMethod->mMethodDef;
  15112. auto rootMethodState = mCurMethodState->GetRootMethodState();
  15113. auto declMethodState = localMethod->mDeclMethodState;
  15114. auto declMixinState = localMethod->mDeclMixinState;
  15115. auto typeInst = mCurTypeInstance;
  15116. BfAstNode* body = NULL;
  15117. BfAstNode* anchorNode = NULL;
  15118. auto _AllocDirectTypeRef = [&](BfType* type)
  15119. {
  15120. BfDirectTypeReference* directTypeRef = localMethod->mDirectTypeRefs.Alloc();
  15121. directTypeRef->Init(type);
  15122. return directTypeRef;
  15123. };
  15124. auto methodDeclaration = localMethod->mMethodDeclaration;
  15125. if (methodDeclaration != NULL)
  15126. {
  15127. body = methodDeclaration->mBody;
  15128. anchorNode = methodDeclaration->mOpenParen;
  15129. }
  15130. else
  15131. {
  15132. body = localMethod->mLambdaBindExpr->mBody;
  15133. anchorNode = localMethod->mLambdaBindExpr->mFatArrowToken;
  15134. }
  15135. BF_ASSERT(rootMethodState->mCurLocalVarId >= 0);
  15136. int methodLocalIdx = rootMethodState->mCurLocalVarId++;
  15137. BfMethodDef* methodDef;
  15138. if (methodDeclaration != NULL)
  15139. {
  15140. BfDefBuilder defBuilder(mCompiler->mSystem);
  15141. defBuilder.mPassInstance = mCompiler->mPassInstance;
  15142. defBuilder.mCurTypeDef = mCurMethodInstance->mMethodDef->mDeclaringType;
  15143. BfMethodDef* outerMethodDef = NULL;
  15144. if (localMethod->mOuterLocalMethod != NULL)
  15145. outerMethodDef = localMethod->mOuterLocalMethod->mMethodDef;
  15146. else
  15147. outerMethodDef = rootMethodState->mMethodInstance->mMethodDef;
  15148. methodDef = defBuilder.CreateMethodDef(methodDeclaration, outerMethodDef);
  15149. }
  15150. else
  15151. {
  15152. auto invokeMethod = localMethod->mLambdaInvokeMethodInstance;
  15153. methodDef = new BfMethodDef();
  15154. methodDef->mName = localMethod->mMethodName;
  15155. methodDef->mDeclaringType = mCurMethodInstance->mMethodDef->mDeclaringType;
  15156. methodDef->mReturnTypeRef = _AllocDirectTypeRef(invokeMethod->mReturnType);
  15157. methodDef->mBody = body;
  15158. for (int paramIdx = 0; paramIdx < invokeMethod->GetParamCount(); paramIdx++)
  15159. {
  15160. auto paramType = invokeMethod->GetParamType(paramIdx);
  15161. String paramName;
  15162. if (paramIdx < (int)localMethod->mLambdaBindExpr->mParams.size())
  15163. paramName = localMethod->mLambdaBindExpr->mParams[paramIdx]->ToString();
  15164. else
  15165. paramName = invokeMethod->GetParamName(paramIdx);
  15166. auto paramDef = new BfParameterDef();
  15167. paramDef->mTypeRef = _AllocDirectTypeRef(paramType);
  15168. paramDef->mName = paramName;
  15169. methodDef->mParams.Add(paramDef);
  15170. }
  15171. }
  15172. methodDef->mIdx = ~methodLocalIdx;
  15173. BF_ASSERT(!localMethod->mExpectedFullName.IsEmpty());
  15174. methodDef->mName = localMethod->mExpectedFullName;
  15175. // methodDef->mName = GetLocalMethodName(methodDef->mName, anchorNode, declMethodState, declMixinState);
  15176. //
  15177. // if (!localMethod->mExpectedFullName.IsEmpty())
  15178. // BF_ASSERT(methodDef->mName == localMethod->mExpectedFullName);
  15179. methodDef->mIsStatic = true;
  15180. methodDef->mIsLocalMethod = true;
  15181. methodDef->mIsVirtual = false;
  15182. localMethod->mMethodDef = methodDef;
  15183. auto methodInstanceGroup = new BfMethodInstanceGroup();
  15184. localMethod->mMethodInstanceGroup = methodInstanceGroup;
  15185. methodInstanceGroup->mMethodIdx = -1;
  15186. methodInstanceGroup->mOwner = mCurTypeInstance;
  15187. methodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  15188. if ((declMethodState->mMixinState != NULL) && (declMethodState->mMixinState->mTarget))
  15189. {
  15190. methodInstanceGroup->mOwner = declMethodState->mMixinState->mTarget.mType->ToTypeInstance();
  15191. BF_ASSERT(methodInstanceGroup->mOwner != NULL);
  15192. }
  15193. if ((mCompiler->mResolvePassData != NULL) && (methodDeclaration != NULL))
  15194. {
  15195. mCompiler->mResolvePassData->HandleLocalReference(methodDeclaration->mNameNode, typeInst->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, methodLocalIdx);
  15196. auto autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  15197. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(methodDeclaration->mNameNode)))
  15198. {
  15199. autoComplete->SetDefinitionLocation(methodDeclaration->mNameNode);
  15200. autoComplete->mInsertStartIdx = methodDeclaration->mNameNode->GetSrcStart();
  15201. autoComplete->mInsertEndIdx = methodDeclaration->mNameNode->GetSrcEnd();
  15202. autoComplete->mDefType = typeInst->mTypeDef;
  15203. autoComplete->mDefMethod = rootMethodState->mMethodInstance->mMethodDef;
  15204. autoComplete->mReplaceLocalId = methodLocalIdx;
  15205. }
  15206. }
  15207. return localMethod->mMethodDef;
  15208. }
  15209. BfModuleMethodInstance BfModule::GetLocalMethodInstance(BfLocalMethod* localMethod, const BfTypeVector& methodGenericArguments, BfMethodInstance* methodInstance, bool force)
  15210. {
  15211. BP_ZONE_F("GetLocalMethodInstance %s", localMethod->mMethodName.c_str());
  15212. BfLogSysM("GetLocalMethodInstance %p\n", localMethod);
  15213. auto rootMethodState = mCurMethodState->GetRootMethodState();
  15214. auto declMethodState = localMethod->mDeclMethodState;
  15215. auto declMixinState = localMethod->mDeclMixinState;
  15216. auto callerMethodState = mCurMethodState;
  15217. auto typeInst = mCurTypeInstance;
  15218. auto methodDef = GetLocalMethodDef(localMethod);
  15219. BfAstNode* body = NULL;
  15220. auto methodDeclaration = localMethod->mMethodDeclaration;
  15221. if (methodDeclaration != NULL)
  15222. {
  15223. body = methodDeclaration->mBody;
  15224. }
  15225. else
  15226. {
  15227. body = localMethod->mLambdaBindExpr->mBody;
  15228. }
  15229. bool hadConcreteInterfaceGenericArgument = false;
  15230. BfTypeVector sanitizedMethodGenericArguments;
  15231. // Ignore the outermost method's generic method arguments for the purpose of determining if we are the 'default' (ie: unspecialized)
  15232. // version of this method for this pass through the outermost method
  15233. int dependentGenericStartIdx = 0;
  15234. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  15235. dependentGenericStartIdx = (int)rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  15236. BfMethodInstance* outerMethodInstance = mCurMethodInstance;
  15237. if (methodGenericArguments.size() == 0)
  15238. {
  15239. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  15240. sanitizedMethodGenericArguments = rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments;
  15241. }
  15242. else
  15243. {
  15244. int genericArgIdx = 0;
  15245. // for (; genericArgIdx < (int)outerMethodInstance->mMethodGenericArguments.size(); genericArgIdx++)
  15246. // {
  15247. // BF_ASSERT(methodGenericArguments[genericArgIdx] == outerMethodInstance->mMethodGenericArguments[genericArgIdx]);
  15248. // sanitizedMethodGenericArguments.push_back(methodGenericArguments[genericArgIdx]);
  15249. // }
  15250. for (; genericArgIdx < (int)methodGenericArguments.size(); genericArgIdx++)
  15251. {
  15252. auto genericArgType = methodGenericArguments[genericArgIdx];
  15253. BF_ASSERT(!genericArgType->IsRef());
  15254. if (genericArgType->IsConcreteInterfaceType())
  15255. {
  15256. hadConcreteInterfaceGenericArgument = true;
  15257. auto concreteInterfaceType = (BfConcreteInterfaceType*)genericArgType;
  15258. genericArgType = concreteInterfaceType->mInterface;
  15259. }
  15260. sanitizedMethodGenericArguments.push_back(genericArgType);
  15261. }
  15262. }
  15263. bool wantPrematureMethodInstance = false;
  15264. if (!force)
  15265. {
  15266. wantPrematureMethodInstance = (callerMethodState->mClosureState != NULL) && (callerMethodState->mClosureState->mCaptureVisitingBody);
  15267. }
  15268. auto methodInstGroup = localMethod->mMethodInstanceGroup;
  15269. bool isDefaultPass = true;
  15270. BfTypeVector lookupMethodGenericArguments;
  15271. for (int genericArgIdx = dependentGenericStartIdx; genericArgIdx < (int)methodGenericArguments.size(); genericArgIdx++)
  15272. {
  15273. auto genericArgType = methodGenericArguments[genericArgIdx];
  15274. BF_ASSERT(!genericArgType->IsRef());
  15275. lookupMethodGenericArguments.Add(genericArgType);
  15276. if (genericArgType->IsGenericParam())
  15277. {
  15278. auto genericParam = (BfGenericParamType*)genericArgType;
  15279. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  15280. isDefaultPass = false;
  15281. }
  15282. else
  15283. {
  15284. isDefaultPass = false;
  15285. }
  15286. }
  15287. bool hadExistingMethodInstance = false;
  15288. if (methodInstance != NULL)
  15289. {
  15290. hadExistingMethodInstance = true;
  15291. }
  15292. else
  15293. {
  15294. if (isDefaultPass)
  15295. {
  15296. methodInstance = methodInstGroup->mDefault;
  15297. if (methodInstance != NULL)
  15298. {
  15299. hadExistingMethodInstance = true;
  15300. }
  15301. else
  15302. {
  15303. methodInstance = new BfMethodInstance();
  15304. methodInstGroup->mDefault = methodInstance;
  15305. }
  15306. }
  15307. else
  15308. {
  15309. BF_ASSERT(sanitizedMethodGenericArguments.size() != 0);
  15310. if (methodInstGroup->mMethodSpecializationMap == NULL)
  15311. methodInstGroup->mMethodSpecializationMap = new BfMethodInstanceGroup::MapType();
  15312. BfMethodInstance** methodInstancePtr = NULL;
  15313. if (!methodInstGroup->mMethodSpecializationMap->TryAdd(lookupMethodGenericArguments, NULL, &methodInstancePtr))
  15314. {
  15315. methodInstance = *methodInstancePtr;
  15316. hadExistingMethodInstance = true;
  15317. }
  15318. else
  15319. {
  15320. methodInstance = new BfMethodInstance();
  15321. *methodInstancePtr = methodInstance;
  15322. }
  15323. }
  15324. }
  15325. if (hadExistingMethodInstance)
  15326. {
  15327. if ((!methodInstance->mDisallowCalling) ||
  15328. ((wantPrematureMethodInstance) && (methodInstance->mDisallowCalling)))
  15329. return BfModuleMethodInstance(methodInstance);
  15330. BF_ASSERT((methodInstance->mMethodInfoEx == NULL) || (methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState == NULL));
  15331. }
  15332. else
  15333. {
  15334. auto methodInfoEx = methodInstance->GetMethodInfoEx();
  15335. methodInfoEx->mClosureInstanceInfo = new BfClosureInstanceInfo();
  15336. methodInfoEx->mClosureInstanceInfo->mLocalMethod = localMethod;
  15337. methodInstance->mIsReified = mCurMethodInstance->mIsReified;
  15338. methodInstance->mIsAutocompleteMethod = mCurMethodInstance->mIsAutocompleteMethod;
  15339. methodInstance->mMethodDef = methodDef;
  15340. methodInstance->mMethodInstanceGroup = localMethod->mMethodInstanceGroup;
  15341. if (hadConcreteInterfaceGenericArgument)
  15342. methodInstance->mIgnoreBody = true;
  15343. methodInfoEx->mMethodGenericArguments = sanitizedMethodGenericArguments;
  15344. for (auto genericArg : sanitizedMethodGenericArguments)
  15345. {
  15346. if (genericArg->IsPrimitiveType())
  15347. genericArg = GetWrappedStructType(genericArg);
  15348. AddDependency(genericArg, typeInst, BfDependencyMap::DependencyFlag_MethodGenericArg);
  15349. }
  15350. for (int genericParamIdx = (int)sanitizedMethodGenericArguments.size(); genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  15351. {
  15352. auto genericParamType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  15353. methodInfoEx->mMethodGenericArguments.push_back(genericParamType);
  15354. }
  15355. SetupMethodIdHash(methodInstance);
  15356. }
  15357. auto _SetupMethodInstance = [&]()
  15358. {
  15359. BF_ASSERT(methodInstance->GetNumGenericParams() == 0);
  15360. // Generic constraints
  15361. for (int genericParamIdx = 0; genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  15362. {
  15363. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, genericParamIdx);
  15364. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  15365. }
  15366. };
  15367. //////////////////////////////////////////////////////////////////////////
  15368. auto _VisitLambdaBody = [&]()
  15369. {
  15370. if (localMethod->mDeclOnly)
  15371. return;
  15372. if (mCompiler->mCanceling)
  15373. return;
  15374. if (auto blockBody = BfNodeDynCast<BfBlock>(body))
  15375. {
  15376. VisitCodeBlock(blockBody);
  15377. }
  15378. else if (auto bodyExpr = BfNodeDynCast<BfExpression>(body))
  15379. CreateValueFromExpression(bodyExpr);
  15380. };
  15381. auto _SafeResolveTypeRef = [&](BfTypeReference* typeRef)
  15382. {
  15383. SetAndRestoreValue<bool> prevIgnoreError(mIgnoreErrors, true);
  15384. auto result = ResolveTypeRef(typeRef);
  15385. if (result == NULL)
  15386. result = mContext->mBfObjectType;
  15387. return result;
  15388. };
  15389. BfTypeInstance* outerClosure = NULL;
  15390. if ((declMethodState->mClosureState != NULL) && (!declMethodState->mClosureState->mCapturing))
  15391. outerClosure = declMethodState->mClosureState->mClosureType;
  15392. BfMethodState methodState;
  15393. methodState.mPrevMethodState = declMethodState;//mCurMethodState;
  15394. BfIRFunctionType funcType;
  15395. auto voidType = GetPrimitiveType(BfTypeCode_None);
  15396. SizedArray<BfIRType, 0> paramTypes;
  15397. funcType = mBfIRBuilder->CreateFunctionType(mBfIRBuilder->MapType(voidType), paramTypes, false);
  15398. mBfIRBuilder->SaveDebugLocation();
  15399. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  15400. auto prevActiveFunction = mBfIRBuilder->GetActiveFunction();
  15401. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  15402. BfDeferredLocalAssignData deferredLocalAssignData;
  15403. //TODO: Why did we do this? It can cause us to pull in local variables that don't belong to us...
  15404. /*if (declMethodState->mDeferredLocalAssignData != NULL)
  15405. deferredLocalAssignData.ExtendFrom(declMethodState->mDeferredLocalAssignData);*/
  15406. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  15407. methodState.mIRHeadBlock = mBfIRBuilder->CreateBlock("head", true);
  15408. methodState.mIRInitBlock = mBfIRBuilder->CreateBlock("init", true);
  15409. methodState.mIREntryBlock = mBfIRBuilder->CreateBlock("entry", true);
  15410. methodState.mCurScope->mDIScope = localMethod->mDeclDIScope; //declMethodState->mCurScope->mDIScope ;
  15411. //methodState.mCurLocalVarId = declMethodState->mCurLocalVarId;
  15412. methodState.mIRFunction = declMethodState->mIRFunction;
  15413. methodState.mDeferredLocalAssignData = &deferredLocalAssignData;
  15414. mBfIRBuilder->SetInsertPoint(methodState.mIREntryBlock);
  15415. BfClosureState closureState;
  15416. if (methodDef->mMethodType == BfMethodType_Mixin)
  15417. {
  15418. if (declMethodState != NULL)
  15419. {
  15420. if ((declMethodState->mClosureState != NULL) && (declMethodState->mClosureState->mReturnType != NULL))
  15421. closureState.mReturnType = declMethodState->mClosureState->mReturnType;
  15422. else if (declMethodState->mMethodInstance != NULL)
  15423. closureState.mReturnType = declMethodState->mMethodInstance->mReturnType;
  15424. }
  15425. }
  15426. if (closureState.mReturnType == NULL)
  15427. closureState.mReturnType = _SafeResolveTypeRef(methodDef->mReturnTypeRef);
  15428. closureState.mCapturing = true;
  15429. closureState.mLocalMethod = localMethod;
  15430. closureState.mClosureInstanceInfo = methodInstance->mMethodInfoEx->mClosureInstanceInfo;
  15431. closureState.mDeclaringMethodIsMutating = mCurMethodInstance->mMethodDef->mIsMutating;
  15432. methodState.mClosureState = &closureState;
  15433. closureState.mClosureType = outerClosure;
  15434. int outerLocalsCount = (int)methodState.mLocals.size();
  15435. if (!hadExistingMethodInstance)
  15436. {
  15437. BfLogSysM("LocalMethod %p premature DoMethodDeclaration %p (Source:%p)\n", localMethod, methodInstance, (methodDeclaration != NULL) ? methodDeclaration->GetSourceData() : NULL);
  15438. SetAndRestoreValue<bool> prevIgnoreWrites(mWantsIRIgnoreWrites, true);
  15439. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  15440. // Prematurely do declaration. We will have to undo this later, so don't write this one and don't throw errors
  15441. auto declareModule = this;
  15442. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  15443. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  15444. BF_ASSERT(declareModule != NULL);
  15445. methodInstance->mDeclModule = declareModule;
  15446. _SetupMethodInstance();
  15447. declareModule->DoMethodDeclaration(localMethod->mMethodDef->GetMethodDeclaration(), false, false);
  15448. methodInstance->mDisallowCalling = true; // Don't allow us to ACTUALLY call until we add the captures
  15449. }
  15450. if (wantPrematureMethodInstance)
  15451. {
  15452. // Return a premature methodInstance -- since we are partway through determining the capture of a local method, we can't rely on its
  15453. // capture information. This returned method instance can only be used for method matching, but we will visit it later to create
  15454. // its true method instance
  15455. //auto moduleMethodInstance = _CheckReturnedMethod(methodInstance);
  15456. //BF_ASSERT(moduleMethodInstance);
  15457. return BfModuleMethodInstance(methodInstance);
  15458. }
  15459. auto checkInsertBlock = mBfIRBuilder->GetInsertBlock();
  15460. BF_ASSERT(methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState == NULL);
  15461. closureState.mCaptureStartAccessId = mCurMethodState->GetRootMethodState()->mCurAccessId;
  15462. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState = &closureState;
  15463. closureState.mClosureMethodDef = methodDef;
  15464. bool wantsVisitBody = true;
  15465. if ((methodDef->mMethodType == BfMethodType_Mixin) && (!methodGenericArguments.IsEmpty()))
  15466. wantsVisitBody = false;
  15467. if (methodInstance->mIsUnspecializedVariation)
  15468. wantsVisitBody = false;
  15469. if (wantsVisitBody)
  15470. {
  15471. BP_ZONE("VisitLambdaBody");
  15472. // For generic methods, we capture for each specialization, so make sure mIsStatic is set to 'true' for
  15473. // this capture stage for each of those times
  15474. SetAndRestoreValue<bool> prevWasStatis(methodDef->mIsStatic, true);
  15475. /*
  15476. // Only generate errors once. Also there are some errors that will occur during this scanning phase
  15477. // that will not occur during the actual lambda method generation, for example: returning a value
  15478. // when our current method is a 'void' method. This shouldn't affect capture scanning since all
  15479. // our AST nodes will still be visited
  15480. SetAndRestoreValue<bool> ignoreError(mIgnoreErrors, true);
  15481. */
  15482. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  15483. //SetAndRestoreValue<bool> wantsIgnoreWrites(mWantsISIgnoreWrites, true);
  15484. mBfIRBuilder->SaveDebugLocation();
  15485. closureState.mCaptureVisitingBody = true;
  15486. BF_ASSERT(methodInstance->mMethodInfoEx != NULL);
  15487. methodState.mGenericTypeBindings = &methodInstance->mMethodInfoEx->mGenericTypeBindings;
  15488. NewScopeState();
  15489. ProcessMethod_SetupParams(methodInstance, NULL, false, NULL);
  15490. if (methodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)
  15491. {
  15492. // Allow assigning to arguments when we're capturing - which may or may not be legal at the injection site (we throw error there)
  15493. for (auto localDef : methodState.mLocals)
  15494. {
  15495. if (localDef->mResolvedType->IsVar())
  15496. continue;
  15497. localDef->mAddr = CreateAlloca(localDef->mResolvedType);
  15498. }
  15499. }
  15500. _VisitLambdaBody();
  15501. RestoreScopeState();
  15502. //ProcessMethod(methodInstance);
  15503. closureState.mCaptureVisitingBody = false;
  15504. mBfIRBuilder->RestoreDebugLocation();
  15505. }
  15506. // If we ended up being called by a method with a lower captureStartAccessId, propagate that to whoever is calling us, too...
  15507. if ((methodState.mPrevMethodState->mClosureState != NULL) && (methodState.mPrevMethodState->mClosureState->mCapturing))
  15508. {
  15509. auto prevClosureState = methodState.mPrevMethodState->mClosureState;
  15510. if (closureState.mCaptureStartAccessId < prevClosureState->mCaptureStartAccessId)
  15511. prevClosureState->mCaptureStartAccessId = closureState.mCaptureStartAccessId;
  15512. }
  15513. //RestoreScopeState();
  15514. // Actually get the referenced local methods. It's important we wait until after visiting the body, because then our own capture information
  15515. // can be used by these methods (which will be necessary if any of these methods call us directly or indirectly)
  15516. closureState.mClosureMethodDef = NULL;
  15517. for (auto methodInstance : closureState.mLocalMethodRefs)
  15518. {
  15519. GetLocalMethodInstance(methodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod, BfTypeVector(), methodInstance);
  15520. }
  15521. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState = NULL;
  15522. prevIgnoreWrites.Restore();
  15523. std::multiset<BfClosureCapturedEntry> capturedEntries;
  15524. //
  15525. {
  15526. auto varMethodState = declMethodState;
  15527. while (varMethodState != NULL)
  15528. {
  15529. if ((varMethodState->mMixinState != NULL) && (varMethodState->mMixinState->mLastTargetAccessId >= closureState.mCaptureStartAccessId))
  15530. {
  15531. BF_ASSERT(methodInstance->GetOwner() == varMethodState->mMixinState->mTarget.mType);
  15532. methodDef->mIsStatic = false;
  15533. if (rootMethodState->mMethodInstance->mMethodDef->mIsMutating)
  15534. methodDef->mIsMutating = true;
  15535. }
  15536. bool copyOuterCaptures = false;
  15537. for (int localIdx = 0; localIdx < varMethodState->mLocals.size(); localIdx++)
  15538. {
  15539. auto localVar = varMethodState->mLocals[localIdx];
  15540. if ((localVar->mReadFromId >= closureState.mCaptureStartAccessId) || (localVar->mWrittenToId >= closureState.mCaptureStartAccessId))
  15541. {
  15542. if (localVar->mIsThis)
  15543. {
  15544. // We can only set mutating if our owning type is mutating
  15545. if (localVar->mWrittenToId >= closureState.mCaptureStartAccessId)
  15546. {
  15547. if (mCurTypeInstance->IsValueType())
  15548. {
  15549. if (rootMethodState->mMethodInstance->mMethodDef->mIsMutating)
  15550. methodDef->mIsMutating = true;
  15551. }
  15552. }
  15553. methodDef->mIsStatic = false;
  15554. continue;
  15555. }
  15556. if ((localVar->mIsThis) && (outerClosure != NULL))
  15557. {
  15558. continue;
  15559. }
  15560. if ((localVar->mConstValue) || (localVar->mResolvedType->IsValuelessType()))
  15561. {
  15562. closureState.mConstLocals.push_back(*localVar);
  15563. continue;
  15564. }
  15565. BfClosureCapturedEntry capturedEntry;
  15566. auto capturedType = localVar->mResolvedType;
  15567. bool captureByRef = false;
  15568. if (!capturedType->IsRef())
  15569. {
  15570. if (localVar->mIsThis)
  15571. {
  15572. if ((localVar->mResolvedType->IsValueType()) && (mCurMethodInstance->mMethodDef->HasNoThisSplat()))
  15573. captureByRef = true;
  15574. }
  15575. else if ((!localVar->mIsReadOnly) && (localVar->mWrittenToId >= closureState.mCaptureStartAccessId))
  15576. captureByRef = true;
  15577. }
  15578. else
  15579. {
  15580. if (localVar->mWrittenToId < closureState.mCaptureStartAccessId)
  15581. {
  15582. capturedType = ((BfRefType*)capturedType)->mElementType;
  15583. }
  15584. }
  15585. if (captureByRef)
  15586. {
  15587. //capturedEntry.mIsByReference = true;
  15588. capturedType = CreateRefType(capturedType);
  15589. }
  15590. else
  15591. {
  15592. //capturedEntry.mIsByReference = false;
  15593. }
  15594. capturedEntry.mNameNode = localVar->mNameNode;
  15595. capturedEntry.mType = capturedType;
  15596. capturedEntry.mName = localVar->mName;
  15597. //capturedEntry.mLocalVarDef = localVar;
  15598. capturedEntries.insert(capturedEntry);
  15599. }
  15600. }
  15601. varMethodState = varMethodState->mPrevMethodState;
  15602. if ((varMethodState == NULL) ||
  15603. (varMethodState->mMixinState != NULL) ||
  15604. ((varMethodState->mClosureState != NULL) && (!varMethodState->mClosureState->mCapturing)))
  15605. break;
  15606. }
  15607. }
  15608. for (auto& copyField : closureState.mReferencedOuterClosureMembers)
  15609. {
  15610. auto fieldDef = copyField->GetFieldDef();
  15611. BfClosureCapturedEntry capturedEntry;
  15612. capturedEntry.mName = copyField->GetFieldDef()->mName;
  15613. capturedEntry.mType = copyField->mResolvedType;
  15614. if (capturedEntry.mType->IsRef())
  15615. {
  15616. // Keep by ref
  15617. }
  15618. else if (!fieldDef->mIsReadOnly)
  15619. {
  15620. capturedEntry.mType = CreateRefType(capturedEntry.mType);
  15621. }
  15622. capturedEntries.insert(capturedEntry);
  15623. }
  15624. int captureIdx = 0;
  15625. for (auto& capturedEntry : capturedEntries)
  15626. {
  15627. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries.Add(capturedEntry);
  15628. }
  15629. /*if (isDefaultPass)
  15630. {
  15631. // Insert captured members a params at the start. If we added at the end then it would screw up varargs methods
  15632. int captureIdx = 0;
  15633. for (auto& capturedEntry : capturedEntries)
  15634. {
  15635. methodInstance->mClosureInstanceInfo->mCaptureNodes.Add(BfNodeDynCast<BfIdentifierNode>(capturedEntry.mNameNode));
  15636. BfParameterDef* paramDef = new BfParameterDef();
  15637. paramDef->mName = capturedEntry.mName;
  15638. BfDirectTypeReference* directTypeRef = new BfDirectTypeReference();
  15639. directTypeRef->mType = capturedEntry.mType;
  15640. typeInst->mTypeDef->mDirectAllocNodes.push_back(directTypeRef);
  15641. paramDef->mTypeRef = directTypeRef;
  15642. paramDef->mParamKind = BfParamKind_ImplicitCapture;
  15643. methodDef->mParams.Insert(captureIdx, paramDef);
  15644. captureIdx++;
  15645. }
  15646. }
  15647. else
  15648. {
  15649. auto defaultMethodInstance = methodInstGroup->mDefault;
  15650. methodInstance->mClosureInstanceInfo->mCaptureNodes = defaultMethodInstance->mClosureInstanceInfo->mCaptureNodes;
  15651. }*/
  15652. methodState.Reset();
  15653. closureState.mCapturing = false;
  15654. //////////////////////////////////////////////////////////////////////////
  15655. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, false);
  15656. if (methodInstance->mReturnType != NULL)
  15657. {
  15658. BF_ASSERT(methodInstance->mDisallowCalling);
  15659. // We did a premature declaration (without captures)
  15660. methodInstance->UndoDeclaration();
  15661. methodInstance->mDisallowCalling = false;
  15662. BfLogSysM("LocalMethod %p UndoingDeclaration %p\n", localMethod, methodInstance);
  15663. }
  15664. auto declareModule = this;
  15665. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  15666. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  15667. BF_ASSERT(declareModule != NULL);
  15668. methodInstance->mDeclModule = declareModule;
  15669. _SetupMethodInstance();
  15670. BfLogSysM("LocalMethod %p DoMethodDeclaration %p\n", localMethod, methodInstance);
  15671. declareModule->DoMethodDeclaration(localMethod->mMethodDef->GetMethodDeclaration(), false, false);
  15672. closureState.mReturnType = methodInstance->mReturnType;
  15673. mCompiler->mStats.mMethodsQueued++;
  15674. mCompiler->UpdateCompletion();
  15675. declareModule->mIncompleteMethodCount++;
  15676. mCompiler->mStats.mMethodsProcessed++;
  15677. if (!methodInstance->mIsReified)
  15678. mCompiler->mStats.mUnreifiedMethodsProcessed++;
  15679. auto deferMethodState = rootMethodState;
  15680. // 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)
  15681. if ((!localMethod->mDeclOnly) && (!methodInstance->mIsUnspecializedVariation) &&
  15682. (!mWantsIRIgnoreWrites) && (methodDef->mMethodType != BfMethodType_Mixin))
  15683. {
  15684. BP_ZONE("BfDeferredLocalMethod:create");
  15685. BfDeferredLocalMethod* deferredLocalMethod = new BfDeferredLocalMethod();
  15686. deferredLocalMethod->mLocalMethod = localMethod;
  15687. deferredLocalMethod->mConstLocals = closureState.mConstLocals;
  15688. deferredLocalMethod->mMethodInstance = methodInstance;
  15689. auto checkMethodState = declMethodState;
  15690. while (checkMethodState != NULL)
  15691. {
  15692. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mActiveDeferredLocalMethod != NULL))
  15693. {
  15694. for (auto& mixinRecord : checkMethodState->mClosureState->mActiveDeferredLocalMethod->mMixinStateRecords)
  15695. deferredLocalMethod->mMixinStateRecords.Add(mixinRecord);
  15696. }
  15697. if (checkMethodState->mMixinState != NULL)
  15698. {
  15699. BfMixinRecord mixinRecord;
  15700. mixinRecord.mSource = checkMethodState->mMixinState->mSource;
  15701. deferredLocalMethod->mMixinStateRecords.Add(mixinRecord);
  15702. }
  15703. checkMethodState = checkMethodState->mPrevMethodState;
  15704. }
  15705. rootMethodState->mDeferredLocalMethods.Add(deferredLocalMethod);
  15706. }
  15707. mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  15708. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  15709. mBfIRBuilder->RestoreDebugLocation();
  15710. if (methodInstance == localMethod->mMethodInstanceGroup->mDefault)
  15711. {
  15712. auto checkMethodState = mCurMethodState;
  15713. while (checkMethodState != NULL)
  15714. {
  15715. BfLocalMethod* nextLocalMethod = NULL;
  15716. if (checkMethodState->mLocalMethodMap.TryGetValue(localMethod->mMethodName, &nextLocalMethod))
  15717. {
  15718. while (nextLocalMethod != NULL)
  15719. {
  15720. auto checkLocalMethod = nextLocalMethod;
  15721. nextLocalMethod = nextLocalMethod->mNextWithSameName;
  15722. if (checkLocalMethod == localMethod)
  15723. continue;
  15724. if (checkLocalMethod->mMethodInstanceGroup == NULL)
  15725. continue;
  15726. auto checkMethodInstance = checkLocalMethod->mMethodInstanceGroup->mDefault;
  15727. if (checkMethodInstance == NULL)
  15728. continue; // Not generated yet
  15729. if (CompareMethodSignatures(localMethod->mMethodInstanceGroup->mDefault, checkMethodInstance))
  15730. {
  15731. auto bfError = Fail("Method already declared with the same parameter types", methodInstance->mMethodDef->GetRefNode(), true);
  15732. if (bfError != NULL)
  15733. mCompiler->mPassInstance->MoreInfo("First declaration", checkMethodInstance->mMethodDef->GetRefNode());
  15734. }
  15735. }
  15736. }
  15737. checkMethodState = checkMethodState->mPrevMethodState;
  15738. }
  15739. }
  15740. return BfModuleMethodInstance(methodInstance);
  15741. }
  15742. int BfModule::GetLocalInferrableGenericArgCount(BfMethodDef* methodDef)
  15743. {
  15744. if ((!methodDef->mIsLocalMethod) || (methodDef->mGenericParams.size() == 0))
  15745. return 0;
  15746. auto rootMethodState = mCurMethodState->GetRootMethodState();
  15747. int rootMethodGenericParamCount = 0;
  15748. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  15749. rootMethodGenericParamCount = (int)rootMethodState->mMethodInstance->mMethodInfoEx->mGenericParams.size();
  15750. if (mCurMethodInstance == NULL)
  15751. return rootMethodGenericParamCount;
  15752. if ((mCurMethodInstance->mMethodInfoEx == NULL) || (mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo == NULL))
  15753. return rootMethodGenericParamCount;
  15754. BfLocalMethod* callerLocalMethod = mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod;
  15755. if (callerLocalMethod == NULL)
  15756. return rootMethodGenericParamCount;
  15757. BfLocalMethod* calledLocalMethod = NULL;
  15758. rootMethodState->mLocalMethodCache.TryGetValue(methodDef->mName, &calledLocalMethod);
  15759. while ((calledLocalMethod != NULL) && (callerLocalMethod != NULL))
  15760. {
  15761. if (calledLocalMethod->mOuterLocalMethod == callerLocalMethod)
  15762. return (int)callerLocalMethod->mMethodDef->mGenericParams.size();
  15763. callerLocalMethod = calledLocalMethod->mOuterLocalMethod;
  15764. }
  15765. return rootMethodGenericParamCount;
  15766. }
  15767. void BfModule::GetMethodCustomAttributes(BfMethodInstance* methodInstance)
  15768. {
  15769. auto methodDef = methodInstance->mMethodDef;
  15770. if (methodInstance->GetCustomAttributes() != NULL)
  15771. return;
  15772. auto methodDeclaration = methodDef->GetMethodDeclaration();
  15773. auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration();
  15774. auto typeInstance = methodInstance->GetOwner();
  15775. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  15776. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  15777. if ((methodDeclaration != NULL) && (methodDeclaration->mAttributes != NULL))
  15778. {
  15779. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes == NULL)
  15780. methodInstance->mMethodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  15781. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes = GetCustomAttributes(methodDeclaration->mAttributes,
  15782. ((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend)) ? BfAttributeTargets_Constructor : BfAttributeTargets_Method);
  15783. }
  15784. else if ((propertyMethodDeclaration != NULL) && (propertyMethodDeclaration->mAttributes != NULL))
  15785. {
  15786. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes == NULL)
  15787. methodInstance->mMethodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  15788. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes = GetCustomAttributes(propertyMethodDeclaration->mAttributes, BfAttributeTargets_Method);
  15789. }
  15790. }
  15791. void BfModule::SetupIRFunction(BfMethodInstance* methodInstance, StringImpl& mangledName, bool isTemporaryFunc, bool* outIsIntrinsic)
  15792. {
  15793. if (methodInstance->GetImportCallKind() == BfImportCallKind_GlobalVar)
  15794. {
  15795. // Don't create a func
  15796. return;
  15797. }
  15798. auto typeInstance = methodInstance->GetOwner();
  15799. auto methodDef = methodInstance->mMethodDef;
  15800. BfIRFunctionType funcType = mBfIRBuilder->MapMethod(methodInstance);
  15801. // Don't set these pointers during resolve pass because they may become invalid if it's just a temporary autocomplete method
  15802. if (mCompiler->mResolvePassData == NULL)
  15803. {
  15804. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mIsStatic))
  15805. {
  15806. typeInstance->mHasStaticInitMethod = true;
  15807. }
  15808. if ((methodDef->mMethodType == BfMethodType_Dtor) && (methodDef->mIsStatic))
  15809. {
  15810. typeInstance->mHasStaticDtorMethod = true;
  15811. }
  15812. if ((methodDef->mMethodType == BfMethodType_Normal) && (methodDef->mIsStatic) && (methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC))
  15813. {
  15814. typeInstance->mHasStaticMarkMethod = true;
  15815. }
  15816. if ((methodDef->mMethodType == BfMethodType_Normal) && (methodDef->mIsStatic) && (methodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS))
  15817. {
  15818. typeInstance->mHasTLSFindMethod = true;
  15819. }
  15820. }
  15821. if (isTemporaryFunc)
  15822. {
  15823. BF_ASSERT((mCompiler->mIsResolveOnly) && (mCompiler->mResolvePassData->mAutoComplete != NULL));
  15824. mangledName = "autocomplete_tmp";
  15825. }
  15826. if (!mBfIRBuilder->mIgnoreWrites)
  15827. {
  15828. BfIRFunction prevFunc;
  15829. // Remove old version (if we have one)
  15830. prevFunc = mBfIRBuilder->GetFunction(mangledName);
  15831. if (prevFunc)
  15832. {
  15833. if (methodDef->mIsExtern)
  15834. {
  15835. // Allow this
  15836. BfLogSysM("Function collision allowed multiple extern functions for %p: %d\n", methodInstance, prevFunc.mId);
  15837. }
  15838. else if (typeInstance->IsIRFuncUsed(prevFunc))
  15839. {
  15840. // We can have a collision of names when we have generic methods that differ only in
  15841. // their constraints, but they should only collide in their unspecialized form
  15842. // since only one will be chosen for a given concrete type
  15843. mCurMethodInstance->mMangleWithIdx = true;
  15844. mangledName.Clear();
  15845. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  15846. prevFunc = mBfIRBuilder->GetFunction(mangledName);
  15847. BfLogSysM("Function collision forced mangleWithIdx for %p: %d\n", methodInstance, prevFunc.mId);
  15848. }
  15849. else
  15850. {
  15851. BfLogSysM("Function collision erased prevFunc %p: %d\n", methodInstance, prevFunc.mId);
  15852. mBfIRBuilder->Func_EraseFromParent(prevFunc);
  15853. }
  15854. }
  15855. }
  15856. if (typeInstance != mContext->mBfObjectType)
  15857. {
  15858. // Only allow attributes on System.Object methods that can be handled inside the DefBuilder
  15859. GetMethodCustomAttributes(methodInstance);
  15860. }
  15861. // if (prevFunc)
  15862. // {
  15863. // if (methodDef->mIsExtern)
  15864. // {
  15865. // BfLogSysM("Reusing function for %p: %d\n", methodInstance, prevFunc.mId);
  15866. // methodInstance->mIRFunction = prevFunc;
  15867. // }
  15868. // else
  15869. // {
  15870. // if ((methodInstance->IsSpecializedByAutoCompleteMethod()) ||
  15871. // ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mResolveType >= BfResolveType_GoToDefinition)))
  15872. // {
  15873. // // If we're doing re-pass over the methods for something like BfResolveType_ShowFileSymbolReferences, then allow this collision
  15874. // BfLogSysM("Ignoring function name collision\n");
  15875. // }
  15876. // else
  15877. // {
  15878. // if (methodDef->mMethodDeclaration == NULL)
  15879. // {
  15880. // AssertErrorState();
  15881. // }
  15882. // else
  15883. // {
  15884. // BF_ASSERT(mIsSpecialModule);
  15885. // if ((mCompiler->mRevision == 1) && (HasCompiledOutput()))
  15886. // {
  15887. // // We shouldn't have name collisions on the first run!
  15888. // AssertErrorState();
  15889. // }
  15890. // }
  15891. // }
  15892. // BfLogSysM("Before erase\n");
  15893. // mBfIRBuilder->Func_EraseFromParent(prevFunc);
  15894. // }
  15895. // }
  15896. bool isIntrinsic = false;
  15897. if (!methodInstance->mIRFunction)
  15898. {
  15899. BfIRFunction func;
  15900. bool wantsLLVMFunc = ((!typeInstance->IsUnspecializedType()) && (!methodDef->IsEmptyPartial())) && (funcType);
  15901. /*if (mCurTypeInstance->mTypeDef->mName->ToString() == "ClassA")
  15902. {
  15903. if (!mIsReified)
  15904. wantsLLVMFunc = false;
  15905. }*/
  15906. if (wantsLLVMFunc)
  15907. {
  15908. func = GetIntrinsic(methodInstance, true);
  15909. if (func)
  15910. {
  15911. isIntrinsic = true;
  15912. }
  15913. else
  15914. {
  15915. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, mangledName);
  15916. BfLogSysM("Creating FuncId:%d %s in module %p\n", func.mId, mangledName.c_str(), this);
  15917. if (methodInstance->mAlwaysInline)
  15918. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_AlwaysInline);
  15919. // if (prevFunc)
  15920. // BfLogSysM("Removing Func %d, replacing with %d\n", prevFunc.mId, func.mId);
  15921. }
  15922. methodInstance->mIRFunction = func;
  15923. //if (!ignoreWrites)
  15924. //BF_ASSERT(!func.IsFake());
  15925. }
  15926. }
  15927. if (outIsIntrinsic != NULL)
  15928. *outIsIntrinsic = isIntrinsic;
  15929. if (!isIntrinsic)
  15930. SetupIRMethod(methodInstance, methodInstance->mIRFunction, methodInstance->mAlwaysInline);
  15931. }
  15932. void BfModule::CheckHotMethod(BfMethodInstance* methodInstance, const StringImpl& inMangledName)
  15933. {
  15934. if (methodInstance->mHotMethod != NULL)
  15935. return;
  15936. if ((mCompiler->mOptions.mAllowHotSwapping) && (!methodInstance->mIsUnspecialized))
  15937. {
  15938. auto srcTypeInst = methodInstance->GetOwner();
  15939. StringT<128> mangledName = inMangledName;
  15940. if (mangledName.IsEmpty())
  15941. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  15942. // We always keep the current primary method at the same address
  15943. BfHotMethod* hotMethod;
  15944. BfHotMethod** hotMethodPtr;
  15945. if (mCompiler->mHotData->mMethodMap.TryAdd(mangledName, NULL, &hotMethodPtr))
  15946. {
  15947. hotMethod = new BfHotMethod();
  15948. *hotMethodPtr = hotMethod;
  15949. hotMethod->mRefCount = 1;
  15950. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  15951. #ifdef BF_DBG_HOTMETHOD_IDX
  15952. static int sMethodIdx = 0;
  15953. hotMethod->mMethodIdx = sMethodIdx++;
  15954. #endif
  15955. BfLogSysM("HotMethodData %p created for method %p %s - %s\n", hotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  15956. }
  15957. else
  15958. {
  15959. hotMethod = *hotMethodPtr;
  15960. if ((hotMethod->mFlags & BfHotDepDataFlag_IsBound) != 0)
  15961. {
  15962. // This is a duplicate mangled name - we link to this new entry via a 'BfHotDupMethod'
  15963. auto prevHotMethod = *hotMethodPtr;
  15964. hotMethod = new BfHotMethod();
  15965. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  15966. BfHotDupMethod* hotDupMethod = new BfHotDupMethod(hotMethod);
  15967. hotDupMethod->mRefCount++;
  15968. prevHotMethod->mReferences.Add(hotDupMethod);
  15969. prevHotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_HasDup);
  15970. BfLogSysM("HotMethodData %p (duplicate of %p) created for method %p %s - %s\n", hotMethod, prevHotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  15971. }
  15972. else if (mCompiler->IsHotCompile())
  15973. {
  15974. // Link the previous version into the mPrevVersion
  15975. BfHotMethod* prevMethod = new BfHotMethod();
  15976. prevMethod->mRefCount = 1;
  15977. prevMethod->mPrevVersion = hotMethod->mPrevVersion;
  15978. hotMethod->mPrevVersion = prevMethod;
  15979. prevMethod->mSrcTypeVersion = hotMethod->mSrcTypeVersion;
  15980. hotMethod->mSrcTypeVersion = NULL;
  15981. prevMethod->mFlags = hotMethod->mFlags;
  15982. hotMethod->mFlags = BfHotDepDataFlag_IsBound;
  15983. hotMethod->mReferences.MoveTo(prevMethod->mReferences);
  15984. #ifdef BF_DBG_HOTMETHOD_NAME
  15985. prevMethod->mMangledName = hotMethod->mMangledName;
  15986. #endif
  15987. BfLogSysM("HotMethodData %p created for prevmethod of %p for method %p %s\n", prevMethod, hotMethod, methodInstance, MethodToString(methodInstance).c_str());
  15988. }
  15989. else
  15990. {
  15991. BfLogSysM("HotMethodData %p used for method %p %s - %s\n", hotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  15992. hotMethod->Clear(true);
  15993. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  15994. }
  15995. }
  15996. if (methodInstance->mIsClosure)
  15997. {
  15998. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_RetainMethodWithoutBinding);
  15999. }
  16000. hotMethod->mSrcTypeVersion = srcTypeInst->mHotTypeData->GetLatestVersion();
  16001. hotMethod->mSrcTypeVersion->mRefCount++;
  16002. hotMethod->mRefCount++;
  16003. #ifdef BF_DBG_HOTMETHOD_NAME
  16004. hotMethod->mMangledName = mangledName;
  16005. #endif
  16006. methodInstance->mHotMethod = hotMethod;
  16007. }
  16008. }
  16009. // methodDeclaration is NULL for default constructors
  16010. void BfModule::DoMethodDeclaration(BfMethodDeclaration* methodDeclaration, bool isTemporaryFunc, bool addToWorkList)
  16011. {
  16012. BP_ZONE("BfModule::BfMethodDeclaration");
  16013. // We could trigger a DoMethodDeclaration from a const resolver or other location, so we reset it here
  16014. // to effectively make mIgnoreWrites method-scoped
  16015. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mWantsIRIgnoreWrites || mCurMethodInstance->mIsUnspecialized);
  16016. SetAndRestoreValue<bool> prevIsCapturingMethodMatchInfo;
  16017. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, NULL);
  16018. if (mCompiler->IsAutocomplete())
  16019. prevIsCapturingMethodMatchInfo.Init(mCompiler->mResolvePassData->mAutoComplete->mIsCapturingMethodMatchInfo, false);
  16020. if (mCurMethodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference)
  16021. mCurMethodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingReference;
  16022. bool ignoreWrites = mBfIRBuilder->mIgnoreWrites;
  16023. if (mAwaitingInitFinish)
  16024. FinishInit();
  16025. auto typeInstance = mCurTypeInstance;
  16026. auto typeDef = typeInstance->mTypeDef;
  16027. auto methodDef = mCurMethodInstance->mMethodDef;
  16028. BF_ASSERT(methodDef->mName != "__ASSERTNAME");
  16029. if (typeInstance->IsClosure())
  16030. {
  16031. if (methodDef->mName == "Invoke")
  16032. return;
  16033. }
  16034. auto methodInstance = mCurMethodInstance;
  16035. if ((methodInstance->IsSpecializedByAutoCompleteMethod()) || (mCurTypeInstance->IsFunction()))
  16036. addToWorkList = false;
  16037. bool hasNonGenericParams = false;
  16038. bool hasGenericParams = false;
  16039. int dependentGenericStartIdx = 0;
  16040. if (methodDef->mIsLocalMethod)
  16041. {
  16042. // If we're a local generic method inside an outer generic method, we can still be considered unspecialized
  16043. // if our outer method's generic args are specialized but ours are unspecialized. This is because locals get
  16044. // instantiated uniquely for each specialized or unspecialized pass through the outer method, but the local
  16045. // method still 'inherits' the outer's generic arguments -- but we still need to make an unspecialized pass
  16046. // over the local method each time
  16047. auto rootMethodInstance = prevMethodState.mPrevVal->GetRootMethodState()->mMethodInstance;
  16048. dependentGenericStartIdx = 0;
  16049. if (rootMethodInstance->mMethodInfoEx != NULL)
  16050. dependentGenericStartIdx = (int)rootMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  16051. methodInstance->mIsUnspecialized = rootMethodInstance->mIsUnspecialized;
  16052. methodInstance->mIsUnspecializedVariation = rootMethodInstance->mIsUnspecializedVariation;
  16053. }
  16054. for (int genericArgIdx = dependentGenericStartIdx; genericArgIdx < (int) methodInstance->GetNumGenericArguments(); genericArgIdx++)
  16055. {
  16056. auto genericArgType = methodInstance->mMethodInfoEx->mMethodGenericArguments[genericArgIdx];
  16057. if (genericArgType->IsGenericParam())
  16058. {
  16059. hasGenericParams = true;
  16060. auto genericParam = (BfGenericParamType*)genericArgType;
  16061. methodInstance->mIsUnspecialized = true;
  16062. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  16063. methodInstance->mIsUnspecializedVariation = true;
  16064. }
  16065. else
  16066. {
  16067. hasNonGenericParams = true;
  16068. if (genericArgType->IsUnspecializedType())
  16069. {
  16070. methodInstance->mIsUnspecialized = true;
  16071. methodInstance->mIsUnspecializedVariation = true;
  16072. }
  16073. }
  16074. }
  16075. if ((hasGenericParams) && (hasNonGenericParams))
  16076. {
  16077. methodInstance->mIsUnspecializedVariation = true;
  16078. }
  16079. if (typeInstance->IsUnspecializedType())
  16080. {
  16081. // A specialized method within an unspecialized type is considered an unspecialized variation -- in the sense that we don't
  16082. // actually want to do method processing on it
  16083. if ((!methodInstance->mIsUnspecialized) && (methodInstance->GetNumGenericArguments() != 0))
  16084. methodInstance->mIsUnspecializedVariation = true;
  16085. methodInstance->mIsUnspecialized = true;
  16086. }
  16087. methodInstance->mIsUnspecializedVariation |= typeInstance->IsUnspecializedTypeVariation();
  16088. for (auto genericParamDef : methodDef->mGenericParams)
  16089. {
  16090. if (mCompiler->IsAutocomplete())
  16091. {
  16092. auto autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  16093. //autoComplete->CheckTypeRef()
  16094. }
  16095. }
  16096. if (methodInstance->mIsUnspecializedVariation)
  16097. {
  16098. }
  16099. if (methodInstance->mIsUnspecializedVariation)
  16100. BF_ASSERT(methodInstance->mIsUnspecialized);
  16101. if (methodDef->mMethodType == BfMethodType_Mixin)
  16102. methodInstance->mIsUnspecialized = true;
  16103. BfAutoComplete* bfAutocomplete = NULL;
  16104. if (mCompiler->mResolvePassData != NULL)
  16105. bfAutocomplete = mCompiler->mResolvePassData->mAutoComplete;
  16106. for (int genericParamIdx = 0; genericParamIdx < (int)methodInstance->GetNumGenericArguments(); genericParamIdx++)
  16107. {
  16108. auto genericParamDef = methodDef->mGenericParams[genericParamIdx];
  16109. ResolveGenericParamConstraints(methodInstance->mMethodInfoEx->mGenericParams[genericParamIdx], methodDef->mGenericParams, genericParamIdx);
  16110. if (bfAutocomplete != NULL)
  16111. {
  16112. for (auto nameNode : genericParamDef->mNameNodes)
  16113. {
  16114. HandleMethodGenericParamRef(nameNode, typeDef, methodDef, genericParamIdx);
  16115. }
  16116. }
  16117. }
  16118. if (methodInstance->mMethodInfoEx != NULL)
  16119. {
  16120. for (auto genericParam : methodInstance->mMethodInfoEx->mGenericParams)
  16121. {
  16122. for (auto constraintTypeInst : genericParam->mInterfaceConstraints)
  16123. AddDependency(constraintTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  16124. if (genericParam->mTypeConstraint != NULL)
  16125. AddDependency(genericParam->mTypeConstraint, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  16126. }
  16127. }
  16128. if ((methodInstance->mIsAutocompleteMethod) && (methodDeclaration != NULL) && (!methodInstance->IsSpecializedGenericMethod()) && (methodDef->mIdx >= 0))
  16129. {
  16130. auto autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  16131. BfAstNode* nameNode = methodDeclaration->mNameNode;
  16132. if (nameNode == NULL)
  16133. {
  16134. if (auto ctorDeclaration = BfNodeDynCast<BfConstructorDeclaration>(methodDeclaration))
  16135. nameNode = ctorDeclaration->mThisToken;
  16136. }
  16137. if (autoComplete->IsAutocompleteNode(nameNode))
  16138. {
  16139. autoComplete->mInsertStartIdx = nameNode->GetSrcStart();
  16140. autoComplete->mInsertEndIdx = nameNode->GetSrcEnd();
  16141. autoComplete->mDefType = typeDef;
  16142. autoComplete->mDefMethod = methodDef;
  16143. autoComplete->SetDefinitionLocation(nameNode);
  16144. if (methodDef->mIsOverride)
  16145. {
  16146. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  16147. {
  16148. auto& ventry = typeInstance->mVirtualMethodTable[virtIdx];
  16149. if (ventry.mDeclaringMethod.mMethodNum == -1)
  16150. continue;
  16151. BfMethodInstance* virtMethod = ventry.mImplementingMethod;
  16152. if (virtMethod != NULL)
  16153. {
  16154. auto virtMethodDeclaration = virtMethod->mMethodDef->GetMethodDeclaration();
  16155. if ((virtMethod->GetOwner() == typeInstance) && (virtMethodDeclaration != NULL) &&
  16156. (virtMethodDeclaration->GetSrcStart() == methodDeclaration->GetSrcStart()))
  16157. {
  16158. // Is matching method
  16159. if (virtIdx < (int)typeInstance->mBaseType->mVirtualMethodTable.size())
  16160. {
  16161. auto baseType = typeInstance->mBaseType;
  16162. if (baseType != NULL)
  16163. {
  16164. while ((baseType->mBaseType != NULL) && (virtIdx < baseType->mBaseType->mVirtualMethodTableSize))
  16165. baseType = baseType->mBaseType;
  16166. BfMethodInstance* baseVirtMethod = baseType->mVirtualMethodTable[virtIdx].mImplementingMethod;
  16167. autoComplete->SetDefinitionLocation(baseVirtMethod->mMethodDef->GetRefNode(), true);
  16168. autoComplete->mDefType = baseType->mTypeDef;
  16169. autoComplete->mDefMethod = baseVirtMethod->mMethodDef;
  16170. }
  16171. }
  16172. break;
  16173. }
  16174. }
  16175. }
  16176. }
  16177. }
  16178. }
  16179. bool reportErrors = true;
  16180. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  16181. reportErrors = true;
  16182. // Only the defining contexts needs to report errors here
  16183. SetAndRestoreValue<bool> prevReporErrors(mReportErrors, reportErrors);
  16184. if (methodDef->mMethodType == BfMethodType_Dtor)
  16185. {
  16186. if (methodDef->mIsStatic)
  16187. {
  16188. }
  16189. else
  16190. {
  16191. if ((typeInstance->IsStruct()) || (typeInstance->IsTypedPrimitive()))
  16192. {
  16193. BfAstNode* refNode = methodDeclaration;
  16194. if (refNode == NULL)
  16195. {
  16196. // Whatever caused this ctor to be generated should have caused another failure
  16197. // But that failure might not be generated until the ctor is generated
  16198. }
  16199. else
  16200. {
  16201. auto dtorDecl = BfNodeDynCast<BfDestructorDeclaration>(methodDeclaration);
  16202. if (dtorDecl != NULL)
  16203. refNode = dtorDecl->mThisToken;
  16204. Fail("Structs cannot have destructors", refNode);
  16205. }
  16206. }
  16207. auto methodDeclaration = methodDef->GetMethodDeclaration();
  16208. if ((methodDeclaration != NULL) && (methodDeclaration->mVirtualSpecifier != NULL) &&
  16209. (mCurTypeInstance != mContext->mBfObjectType))
  16210. {
  16211. Fail("Virtual specifier is not required, all destructors are implicitly virtual.", methodDeclaration->mVirtualSpecifier);
  16212. }
  16213. }
  16214. }
  16215. BfType* resolvedReturnType = NULL;
  16216. if (((methodDef->mMethodType == BfMethodType_Normal) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend) || (methodDef->mMethodType == BfMethodType_PropertyGetter) || (methodDef->mMethodType == BfMethodType_Operator)) &&
  16217. (methodDef->mReturnTypeRef != NULL))
  16218. {
  16219. SetAndRestoreValue<bool> prevIngoreErrors(mIgnoreErrors, mIgnoreErrors || (methodDef->GetPropertyDeclaration() != NULL));
  16220. resolvedReturnType = ResolveTypeRef(methodDef->mReturnTypeRef, BfPopulateType_Declaration,
  16221. (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_AllowRef | BfResolveTypeRefFlag_AllowRefGeneric));
  16222. if ((resolvedReturnType != NULL) && (resolvedReturnType->IsVar()) && (methodDef->mMethodType != BfMethodType_Mixin))
  16223. {
  16224. Fail("Cannot declare var return types", methodDef->mReturnTypeRef);
  16225. resolvedReturnType = GetPrimitiveType(BfTypeCode_Var);
  16226. }
  16227. if (resolvedReturnType == NULL)
  16228. resolvedReturnType = GetPrimitiveType(BfTypeCode_Var);
  16229. }
  16230. else
  16231. {
  16232. resolvedReturnType = ResolveTypeDef(mSystem->mTypeVoid);
  16233. }
  16234. BF_ASSERT(resolvedReturnType != NULL);
  16235. mCurMethodInstance->mReturnType = resolvedReturnType;
  16236. //TODO: We used to NOT add the return value dependency for specialized methods, but when we have types that are
  16237. // specialized based on the method's generic param then they can get deleted if no one else has referred to them (yet)
  16238. //if (!methodInstance->IsSpecializedGenericMethod())
  16239. AddDependency(resolvedReturnType, typeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  16240. if (methodDef->mExplicitInterface != NULL)
  16241. {
  16242. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  16243. mCompiler->mResolvePassData->mAutoComplete->CheckTypeRef(methodDef->mExplicitInterface, false);
  16244. auto explicitInterface = ResolveTypeRef(methodDef->mExplicitInterface, BfPopulateType_Declaration);
  16245. if (explicitInterface != NULL)
  16246. mCurMethodInstance->GetMethodInfoEx()->mExplicitInterface = explicitInterface->ToTypeInstance();
  16247. if ((mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mExplicitInterface != NULL))
  16248. {
  16249. bool interfaceFound = false;
  16250. for (auto ifaceInst : typeInstance->mInterfaces)
  16251. interfaceFound |= ifaceInst.mInterfaceType == mCurMethodInstance->mMethodInfoEx->mExplicitInterface;
  16252. if (!interfaceFound)
  16253. {
  16254. if (methodDef->mMethodDeclaration != NULL)
  16255. Fail("Containing class has not declared to implement this interface", methodDef->mMethodDeclaration);
  16256. else
  16257. {
  16258. // For property decls, we should have already given the error during type population
  16259. if (mCompiler->mRevision == 1)
  16260. AssertErrorState();
  16261. }
  16262. }
  16263. }
  16264. }
  16265. bool isThisStruct = mCurTypeInstance->IsStruct();
  16266. BfType* thisType = NULL;
  16267. if ((!methodDef->mIsStatic) && (!mCurTypeInstance->IsValuelessType()))
  16268. {
  16269. if ((isThisStruct) || (mCurTypeInstance->IsTypedPrimitive()))
  16270. {
  16271. thisType = mCurTypeInstance;
  16272. if (thisType == NULL)
  16273. return;
  16274. if ((thisType->IsSplattable()) && (!methodDef->HasNoThisSplat()))
  16275. {
  16276. BfTypeUtils::SplatIterate([&](BfType* checkType)
  16277. {
  16278. PopulateType(checkType, BfPopulateType_Data);
  16279. }, thisType);
  16280. }
  16281. }
  16282. else
  16283. {
  16284. thisType = mCurTypeInstance;
  16285. PopulateType(thisType, BfPopulateType_Declaration);
  16286. }
  16287. }
  16288. int implicitParamCount = 0;
  16289. if ((mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo != NULL))
  16290. implicitParamCount = (int)methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries.size();
  16291. methodInstance->mMethodDef->mParams.Reserve((int)methodDef->mParams.size());
  16292. bool hadDelegateParams = false;
  16293. bool hadParams = false;
  16294. for (int paramIdx = 0; paramIdx < (int)methodDef->mParams.size() + implicitParamCount; paramIdx++)
  16295. {
  16296. BfClosureCapturedEntry* closureCaptureEntry = NULL;
  16297. BfParameterDef* paramDef = NULL;
  16298. int paramDefIdx = -1;
  16299. if (paramIdx < implicitParamCount)
  16300. closureCaptureEntry = &methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries[paramIdx];
  16301. else
  16302. {
  16303. paramDefIdx = paramIdx - implicitParamCount;
  16304. paramDef = methodDef->mParams[paramDefIdx];
  16305. }
  16306. if (hadParams)
  16307. break;
  16308. if ((paramDef != NULL) && (mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL) &&
  16309. (paramDef->mParamKind != BfParamKind_AppendIdx))
  16310. mCompiler->mResolvePassData->mAutoComplete->CheckTypeRef(paramDef->mTypeRef, false);
  16311. if ((paramDef != NULL) && (paramDef->mParamDeclaration != NULL) && (paramDef->mParamDeclaration->mAttributes != NULL))
  16312. {
  16313. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes == NULL)
  16314. methodInstance->mMethodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  16315. while ((int)methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.size() < paramIdx)
  16316. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.push_back(NULL);
  16317. auto customAttributes = GetCustomAttributes(paramDef->mParamDeclaration->mAttributes, BfAttributeTargets_Parameter);
  16318. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.push_back(customAttributes);
  16319. }
  16320. BfType* resolvedParamType = NULL;
  16321. if (closureCaptureEntry != NULL)
  16322. resolvedParamType = closureCaptureEntry->mType;
  16323. else if (paramDef->mTypeRef->IsA<BfLetTypeReference>())
  16324. {
  16325. Fail("Cannot declare 'let' parameters", paramDef->mTypeRef);
  16326. resolvedParamType = mContext->mBfObjectType;
  16327. }
  16328. else if (paramDef->mTypeRef->IsA<BfVarTypeReference>())
  16329. {
  16330. if (methodDef->mMethodType != BfMethodType_Mixin)
  16331. {
  16332. Fail("Cannot declare var parameters", paramDef->mTypeRef);
  16333. resolvedParamType = mContext->mBfObjectType;
  16334. }
  16335. else
  16336. resolvedParamType = GetPrimitiveType(BfTypeCode_Var);
  16337. }
  16338. BfType* unresolvedParamType = resolvedParamType;
  16339. bool wasGenericParam = false;
  16340. if (resolvedParamType == NULL)
  16341. {
  16342. SetAndRestoreValue<bool> prevIngoreErrors(mIgnoreErrors, mIgnoreErrors || (methodDef->GetPropertyDeclaration() != NULL));
  16343. resolvedParamType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration,
  16344. (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_AllowRef | BfResolveTypeRefFlag_AllowRefGeneric | BfResolveTypeRefFlag_AllowGenericMethodParamConstValue));
  16345. }
  16346. if (resolvedParamType == NULL)
  16347. {
  16348. resolvedParamType = GetPrimitiveType(BfTypeCode_Var);
  16349. unresolvedParamType = resolvedParamType;
  16350. if (mCurTypeInstance->IsBoxed())
  16351. {
  16352. auto boxedType = (BfBoxedType*)mCurTypeInstance;
  16353. // If we failed a lookup here then we better have also failed it in the original type
  16354. BF_ASSERT(boxedType->mElementType->mModule->mHadBuildError || mContext->mFailTypes.Contains(boxedType->mElementType));
  16355. }
  16356. }
  16357. if (!methodInstance->IsSpecializedGenericMethod())
  16358. AddDependency(resolvedParamType, typeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  16359. PopulateType(resolvedParamType, BfPopulateType_Declaration);
  16360. AddDependency(resolvedParamType, mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
  16361. if ((paramDef != NULL) && (paramDef->mParamDeclaration != NULL) && (paramDef->mParamDeclaration->mInitializer != NULL) &&
  16362. (!paramDef->mParamDeclaration->mInitializer->IsA<BfBlock>()))
  16363. {
  16364. BfMethodState methodState;
  16365. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  16366. methodState.mTempKind = BfMethodState::TempKind_Static;
  16367. BfTypedValue defaultValue;
  16368. if (resolvedParamType->IsConstExprValue())
  16369. {
  16370. auto constExprType = (BfConstExprValueType*)resolvedParamType;
  16371. BfExprEvaluator exprEvaluator(this);
  16372. exprEvaluator.mExpectingType = constExprType->mType;
  16373. exprEvaluator.GetLiteral(NULL, constExprType->mValue);
  16374. defaultValue = exprEvaluator.GetResult();
  16375. }
  16376. else
  16377. {
  16378. BfConstResolver constResolver(this);
  16379. defaultValue = constResolver.Resolve(paramDef->mParamDeclaration->mInitializer, resolvedParamType, BfConstResolveFlag_NoCast);
  16380. if ((defaultValue) && (defaultValue.mType != resolvedParamType))
  16381. {
  16382. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  16383. auto castedDefaultValue = Cast(paramDef->mParamDeclaration->mInitializer, defaultValue, resolvedParamType, (BfCastFlags)(BfCastFlags_SilentFail | BfCastFlags_NoConversionOperator));
  16384. if ((castedDefaultValue) && (castedDefaultValue.mValue.IsConst()))
  16385. {
  16386. defaultValue = castedDefaultValue; // Good!
  16387. }
  16388. else if (!CanImplicitlyCast(defaultValue, resolvedParamType))
  16389. {
  16390. // We only care that we get a constant value that can be implicitly casted at the callsite- even if that requires
  16391. // a conversion operator.
  16392. // This should throw an error
  16393. defaultValue = Cast(paramDef->mParamDeclaration->mInitializer, defaultValue, resolvedParamType);
  16394. AssertErrorState();
  16395. if (!defaultValue.mValue.IsConst())
  16396. defaultValue = BfTypedValue();
  16397. }
  16398. }
  16399. }
  16400. if (!defaultValue)
  16401. {
  16402. defaultValue = GetDefaultTypedValue(resolvedParamType);
  16403. if (!defaultValue.mValue.IsConst())
  16404. defaultValue = BfTypedValue();
  16405. }
  16406. if (defaultValue)
  16407. {
  16408. BF_ASSERT(defaultValue.mValue.IsConst());
  16409. while ((int)mCurMethodInstance->mDefaultValues.size() < paramDefIdx)
  16410. mCurMethodInstance->mDefaultValues.Add(BfIRValue());
  16411. CurrentAddToConstHolder(defaultValue.mValue);
  16412. mCurMethodInstance->mDefaultValues.Add(defaultValue.mValue);
  16413. }
  16414. }
  16415. if ((paramDef != NULL) && (paramDef->mParamKind == BfParamKind_Params))
  16416. {
  16417. bool addParams = true;
  16418. bool isValid = false;
  16419. auto resolvedParamTypeInst = resolvedParamType->ToTypeInstance();
  16420. if ((resolvedParamTypeInst != NULL) && (resolvedParamTypeInst->mTypeDef == mCompiler->mSpanTypeDef))
  16421. {
  16422. // Span<T>
  16423. isValid = true;
  16424. }
  16425. else if (resolvedParamType->IsArray())
  16426. {
  16427. // Array is the 'normal' params type
  16428. isValid = true;
  16429. }
  16430. else if ((resolvedParamType->IsDelegate()) || (resolvedParamType->IsFunction()))
  16431. {
  16432. hadDelegateParams = true;
  16433. // This means we copy the params from a delegate
  16434. BfMethodParam methodParam;
  16435. methodParam.mResolvedType = resolvedParamType;
  16436. methodParam.mParamDefIdx = paramDefIdx;
  16437. methodParam.mDelegateParamIdx = 0;
  16438. auto invokeMethodInstance = methodParam.GetDelegateParamInvoke();
  16439. for (int delegateParamIdx = 0; delegateParamIdx < invokeMethodInstance->GetParamCount(); delegateParamIdx++)
  16440. {
  16441. methodParam.mDelegateParamIdx = delegateParamIdx;
  16442. mCurMethodInstance->mParams.Add(methodParam);
  16443. auto paramType = invokeMethodInstance->GetParamType(delegateParamIdx);
  16444. if (!methodInstance->IsSpecializedGenericMethod())
  16445. AddDependency(paramType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  16446. }
  16447. isValid = true;
  16448. addParams = false;
  16449. }
  16450. else if (resolvedParamType->IsGenericParam())
  16451. {
  16452. auto genericParamInstance = GetGenericParamInstance((BfGenericParamType*)resolvedParamType);
  16453. if (genericParamInstance->mTypeConstraint != NULL)
  16454. {
  16455. auto typeInstConstraint = genericParamInstance->mTypeConstraint->ToTypeInstance();
  16456. if (genericParamInstance->mTypeConstraint->IsArray())
  16457. {
  16458. BfMethodParam methodParam;
  16459. methodParam.mResolvedType = resolvedParamType;
  16460. methodParam.mParamDefIdx = paramDefIdx;
  16461. mCurMethodInstance->mParams.Add(methodParam);
  16462. isValid = true;
  16463. }
  16464. else if ((genericParamInstance->mTypeConstraint->IsDelegate()) || (genericParamInstance->mTypeConstraint->IsFunction()) ||
  16465. ((genericParamInstance != NULL) && (typeInstConstraint != NULL) &&
  16466. ((typeInstConstraint->mTypeDef == mCompiler->mDelegateTypeDef) || (typeInstConstraint->mTypeDef == mCompiler->mFunctionTypeDef))))
  16467. {
  16468. mCurMethodInstance->mHadGenericDelegateParams = true;
  16469. isValid = true;
  16470. addParams = false;
  16471. }
  16472. }
  16473. }
  16474. else
  16475. {
  16476. auto paramTypeInst = resolvedParamType->ToTypeInstance();
  16477. if ((paramTypeInst != NULL) &&
  16478. ((paramTypeInst->mTypeDef == mCompiler->mDelegateTypeDef) || (paramTypeInst->mTypeDef == mCompiler->mFunctionTypeDef)))
  16479. {
  16480. // If we have a 'params T' and 'T' gets specialized with actually 'Delegate' or 'Function' then just ignore it
  16481. isValid = true;
  16482. addParams = false;
  16483. }
  16484. }
  16485. if (!isValid)
  16486. {
  16487. Fail("Parameters with 'params' specifiers can only be used for array, span, delegate, or function types", paramDef->mParamDeclaration->mModToken);
  16488. // Failure case, make it an Object[]
  16489. resolvedParamType = CreateArrayType(mContext->mBfObjectType, 1);
  16490. }
  16491. if (addParams)
  16492. {
  16493. BfMethodParam methodParam;
  16494. methodParam.mResolvedType = resolvedParamType;
  16495. methodParam.mParamDefIdx = paramDefIdx;
  16496. mCurMethodInstance->mParams.push_back(methodParam);
  16497. }
  16498. if (paramDefIdx < (int)methodDef->mParams.size() - 1)
  16499. {
  16500. Fail("Only the last parameter can specify 'params'", paramDef->mParamDeclaration->mModToken);
  16501. }
  16502. }
  16503. else
  16504. {
  16505. BfMethodParam methodParam;
  16506. methodParam.mResolvedType = resolvedParamType;
  16507. methodParam.mParamDefIdx = paramDefIdx;
  16508. mCurMethodInstance->mParams.Add(methodParam);
  16509. }
  16510. }
  16511. if (hadDelegateParams)
  16512. {
  16513. HashSet<String> usedNames;
  16514. Dictionary<int, int> usedParamDefIdx;
  16515. for (auto methodParam : methodDef->mParams)
  16516. {
  16517. usedNames.Add(methodParam->mName);
  16518. }
  16519. for (auto& methodParam : mCurMethodInstance->mParams)
  16520. {
  16521. if ((methodParam.mParamDefIdx != -1) && (methodParam.mDelegateParamIdx == 0))
  16522. {
  16523. int* refCount = NULL;
  16524. usedParamDefIdx.TryAdd(methodParam.mParamDefIdx, NULL, &refCount);
  16525. (*refCount)++;
  16526. }
  16527. }
  16528. for (auto& methodParam : mCurMethodInstance->mParams)
  16529. {
  16530. if (methodParam.mDelegateParamIdx != -1)
  16531. {
  16532. if (usedParamDefIdx[methodParam.mParamDefIdx] > 1)
  16533. methodParam.mDelegateParamNameCombine = true;
  16534. BfMethodInstance* invokeMethodInstance = methodParam.GetDelegateParamInvoke();
  16535. String paramName = invokeMethodInstance->GetParamName(methodParam.mDelegateParamIdx);
  16536. if (usedNames.Contains(paramName))
  16537. methodParam.mDelegateParamNameCombine = true;
  16538. }
  16539. }
  16540. }
  16541. int argIdx = 0;
  16542. PopulateType(methodInstance->mReturnType, BfPopulateType_Data);
  16543. if (methodInstance->HasStructRet())
  16544. argIdx++;
  16545. if (!methodDef->mIsStatic)
  16546. {
  16547. if (methodInstance->GetParamIsSplat(-1))
  16548. argIdx += methodInstance->GetParamType(-1)->GetSplatCount();
  16549. else if (!methodInstance->GetOwner()->IsValuelessType())
  16550. argIdx++;
  16551. }
  16552. for (auto& methodParam : mCurMethodInstance->mParams)
  16553. {
  16554. if (methodParam.mResolvedType->IsMethodRef())
  16555. {
  16556. methodParam.mIsSplat = true;
  16557. }
  16558. else if (methodParam.mResolvedType->IsComposite())
  16559. {
  16560. PopulateType(methodParam.mResolvedType, BfPopulateType_Data);
  16561. if (methodParam.mResolvedType->IsSplattable())
  16562. {
  16563. int splatCount = methodParam.mResolvedType->GetSplatCount();
  16564. if (argIdx + splatCount <= mCompiler->mOptions.mMaxSplatRegs)
  16565. {
  16566. methodParam.mIsSplat = true;
  16567. argIdx += splatCount;
  16568. continue;
  16569. }
  16570. }
  16571. }
  16572. argIdx++;
  16573. }
  16574. bool hasExternSpecifier = (methodDeclaration != NULL) && (methodDeclaration->mExternSpecifier != NULL);
  16575. if ((hasExternSpecifier) && (methodDeclaration->mBody != NULL))
  16576. {
  16577. Fail("Cannot 'extern' and declare a body", methodDeclaration->mExternSpecifier);
  16578. }
  16579. else if ((methodDeclaration != NULL) && (methodDeclaration->mBody == NULL) && (!hasExternSpecifier) &&
  16580. (!typeInstance->IsInterface()) && (!mCurTypeInstance->IsDelegate()) && (!mCurTypeInstance->IsFunction()) &&
  16581. (!methodDef->mIsPartial) && (!methodDef->mIsAbstract) &&
  16582. (!methodDef->mIsSkipCall))
  16583. {
  16584. if (methodDeclaration->mEndSemicolon == NULL)
  16585. {
  16586. AssertParseErrorState();
  16587. }
  16588. else
  16589. {
  16590. bool isError = true;
  16591. if (typeInstance->IsTypedPrimitive())
  16592. {
  16593. if (auto operatorDeclaration = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  16594. {
  16595. if ((operatorDeclaration->mIsConvOperator) && (methodInstance->mParams.size() == 1))
  16596. {
  16597. if (((methodInstance->mReturnType == typeInstance) && (methodInstance->GetParamType(0) == typeInstance->GetUnderlyingType())) ||
  16598. ((methodInstance->mReturnType == typeInstance->GetUnderlyingType()) && (methodInstance->GetParamType(0) == typeInstance)))
  16599. {
  16600. isError = false;
  16601. }
  16602. }
  16603. }
  16604. }
  16605. if (isError)
  16606. {
  16607. Fail(StrFormat("'%s' must declare a body because it is not marked abstract, extern, or partial",
  16608. MethodToString(methodInstance).c_str()),
  16609. methodDef->GetRefNode());
  16610. }
  16611. }
  16612. }
  16613. if (methodDef->IsEmptyPartial())
  16614. hasExternSpecifier = true;
  16615. if (!methodInstance->IsAutocompleteMethod())
  16616. {
  16617. auto defaultMethodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  16618. int implicitParamCount = methodInstance->GetImplicitParamCount();
  16619. int defaultImplicitParamCount = defaultMethodInstance->GetImplicitParamCount();
  16620. int actualParamCount = (int)methodInstance->mParams.size() - implicitParamCount;
  16621. BF_ASSERT((actualParamCount == defaultMethodInstance->mParams.size() - defaultImplicitParamCount) || (defaultMethodInstance->mHadGenericDelegateParams));
  16622. mCurMethodInstance->mHadGenericDelegateParams = defaultMethodInstance->mHadGenericDelegateParams;
  16623. int paramIdx = 0;
  16624. int defaultParamIdx = 0;
  16625. while (true)
  16626. {
  16627. bool isDone = paramIdx + implicitParamCount >= (int)methodInstance->mParams.size();
  16628. bool isDefaultDone = defaultParamIdx + defaultImplicitParamCount >= (int)defaultMethodInstance->mParams.size();
  16629. if ((!isDone) && (methodInstance->mParams[paramIdx + implicitParamCount].mDelegateParamIdx >= 0))
  16630. {
  16631. paramIdx++;
  16632. continue;
  16633. }
  16634. if ((!isDefaultDone) && (defaultMethodInstance->mParams[defaultParamIdx + defaultImplicitParamCount].mDelegateParamIdx >= 0))
  16635. {
  16636. defaultParamIdx++;
  16637. continue;
  16638. }
  16639. if ((isDone) || (isDefaultDone))
  16640. {
  16641. // 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
  16642. // to cause us to throw an assertion in the declaration here
  16643. if (!defaultMethodInstance->mHadGenericDelegateParams)
  16644. BF_ASSERT((isDone) && (isDefaultDone));
  16645. break;
  16646. }
  16647. methodInstance->mParams[paramIdx + implicitParamCount].mWasGenericParam = defaultMethodInstance->mParams[defaultParamIdx + defaultImplicitParamCount].mResolvedType->IsGenericParam();
  16648. paramIdx++;
  16649. defaultParamIdx++;
  16650. }
  16651. }
  16652. StringT<128> mangledName;
  16653. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  16654. for (int paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  16655. {
  16656. auto paramType = methodInstance->GetParamType(paramIdx);
  16657. if (paramType->IsComposite())
  16658. PopulateType(paramType, BfPopulateType_Data);
  16659. if (!methodInstance->IsParamSkipped(paramIdx))
  16660. {
  16661. if (paramType->IsStruct())
  16662. {
  16663. //
  16664. }
  16665. else
  16666. {
  16667. PopulateType(paramType, BfPopulateType_Declaration);
  16668. }
  16669. }
  16670. }
  16671. // Only process method in default unspecialized mode, not in variations
  16672. if (methodInstance->mIsUnspecializedVariation)
  16673. return;
  16674. PopulateType(resolvedReturnType, BfPopulateType_Data);
  16675. auto retLLVMType = mBfIRBuilder->MapType(resolvedReturnType);
  16676. if (resolvedReturnType->IsValuelessType())
  16677. retLLVMType = mBfIRBuilder->GetPrimitiveType(BfTypeCode_None);
  16678. if (!mBfIRBuilder->mIgnoreWrites)
  16679. {
  16680. bool isIntrinsic = false;
  16681. if (!methodInstance->mIRFunction)
  16682. SetupIRFunction(methodInstance, mangledName, isTemporaryFunc, &isIntrinsic);
  16683. if (isIntrinsic)
  16684. {
  16685. addToWorkList = false;
  16686. }
  16687. }
  16688. auto func = methodInstance->mIRFunction;
  16689. // if (methodInstance->mIsReified)
  16690. // CheckHotMethod(methodInstance, mangledName);
  16691. 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);
  16692. SizedArray<BfIRMDNode, 8> diParams;
  16693. diParams.push_back(mBfIRBuilder->DbgGetType(resolvedReturnType));
  16694. if ((!methodDef->mIsStatic) && (typeDef->mIsStatic) && (methodDef->mMethodDeclaration != NULL))
  16695. {
  16696. //CS0708
  16697. Fail("Cannot declare instance members in a static class", methodDef->GetRefNode());
  16698. }
  16699. if ((methodDef->mIsVirtual) && (methodDef->mGenericParams.size() != 0))
  16700. {
  16701. Fail("Virtual generic methods not supported", methodDeclaration->mVirtualSpecifier);
  16702. methodDef->mIsVirtual = false;
  16703. }
  16704. if ((methodDeclaration != NULL) && (methodDeclaration->mMutSpecifier != NULL) && (!mCurTypeInstance->IsBoxed()) && (!methodInstance->mIsForeignMethodDef))
  16705. {
  16706. if (methodDef->mIsStatic)
  16707. Warn(0, "Unnecessary 'mut' specifier, static methods have no implicit 'this' target to mutate", methodDeclaration->mMutSpecifier);
  16708. else if ((!mCurTypeInstance->IsValueType()) && (!mCurTypeInstance->IsInterface()))
  16709. Warn(0, "Unnecessary 'mut' specifier, methods of reference types are implicitly mutating", methodDeclaration->mMutSpecifier);
  16710. else if (methodDef->mMethodType == BfMethodType_Ctor)
  16711. Warn(0, "Unnecessary 'mut' specifier, constructors are implicitly mutating", methodDeclaration->mMutSpecifier);
  16712. else if (methodDef->mMethodType == BfMethodType_Dtor)
  16713. Warn(0, "Unnecessary 'mut' specifier, destructors are implicitly mutating", methodDeclaration->mMutSpecifier);
  16714. }
  16715. if (isTemporaryFunc)
  16716. {
  16717. // This handles temporary methods for autocomplete types
  16718. BF_ASSERT(mIsScratchModule);
  16719. BF_ASSERT(mCompiler->IsAutocomplete());
  16720. BfLogSysM("DoMethodDeclaration autocomplete bailout\n");
  16721. return; // Bail out early for autocomplete pass
  16722. }
  16723. //TODO: We used to have this (this != mContext->mExternalFuncModule) check, but it caused us to keep around
  16724. // an invalid mFuncRefernce (which came from GetMethodInstanceAtIdx) which later got remapped by the
  16725. // autocompleter. Why did we have this check anyway?
  16726. /*if ((typeInstance->mContext != mContext) && (!methodDef->IsEmptyPartial()))
  16727. {
  16728. AddMethodReference(methodInstance);
  16729. mFuncReferences[methodInstance] = func;
  16730. BfLogSysM("Adding func reference (DoMethodDeclaration). Module:%p MethodInst:%p LLVMFunc:%p\n", this, methodInstance, func);
  16731. }*/
  16732. if (mParentModule != NULL)
  16733. {
  16734. // For extension modules we need to keep track of our own methods so we can know which methods
  16735. // we have defined ourselves and which are from the parent module or other extensions
  16736. if (!func.IsFake())
  16737. mFuncReferences[methodInstance] = func;
  16738. }
  16739. if (addToWorkList)
  16740. {
  16741. bool wasAwaitingDecl = methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl;
  16742. if (wasAwaitingDecl)
  16743. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingReference;
  16744. if ((!methodDef->mIsAbstract) && (!methodInstance->mIgnoreBody))
  16745. {
  16746. if (!wasAwaitingDecl)
  16747. AddMethodToWorkList(methodInstance);
  16748. }
  16749. else
  16750. {
  16751. BfLogSysM("DoMethodDeclaration ignoring method body %d %d %d\n", hasExternSpecifier, methodDef->mIsAbstract, methodInstance->mIgnoreBody);
  16752. methodInstance->mIgnoreBody = true;
  16753. if (typeInstance->IsUnspecializedType())
  16754. {
  16755. // Don't hold on to actual Function for unspecialized types
  16756. methodInstance->mIRFunction = BfIRFunction();
  16757. }
  16758. }
  16759. }
  16760. if ((!methodInstance->IsSpecializedGenericMethodOrType()) && (!mCurTypeInstance->IsBoxed()) &&
  16761. (!methodDef->mIsLocalMethod) &&
  16762. (!CheckDefineMemberProtection(methodDef->mProtection, methodInstance->mReturnType)))
  16763. {
  16764. if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  16765. {
  16766. //TODO:
  16767. //CS0053
  16768. Fail(StrFormat("Inconsistent accessibility: property type '%s' is less accessible than property '%s'",
  16769. TypeToString(methodInstance->mReturnType).c_str(), MethodToString(methodInstance).c_str()),
  16770. methodDef->mReturnTypeRef, true);
  16771. }
  16772. else
  16773. {
  16774. //CS0050
  16775. Fail(StrFormat("Inconsistent accessibility: return type '%s' is less accessible than method '%s'",
  16776. TypeToString(methodInstance->mReturnType).c_str(), MethodToString(methodInstance).c_str()),
  16777. methodDef->mReturnTypeRef, true);
  16778. }
  16779. }
  16780. if ((typeInstance->IsInterface()) && (methodDef->mMethodType == BfMethodType_Ctor))
  16781. {
  16782. Fail("Interfaces cannot contain constructors", methodDeclaration);
  16783. }
  16784. // Don't compare specialized generic methods against normal methods
  16785. if ((((mCurMethodInstance->mIsUnspecialized) || (mCurMethodInstance->mMethodDef->mGenericParams.size() == 0))) &&
  16786. (!methodDef->mIsLocalMethod))
  16787. {
  16788. if (!methodInstance->mIsForeignMethodDef)
  16789. {
  16790. typeDef->PopulateMemberSets();
  16791. BfMethodDef* nextMethod = NULL;
  16792. BfMemberSetEntry* entry = NULL;
  16793. if (typeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  16794. nextMethod = (BfMethodDef*)entry->mMemberDef;
  16795. while (nextMethod != NULL)
  16796. {
  16797. auto checkMethod = nextMethod;
  16798. nextMethod = nextMethod->mNextWithSameName;
  16799. if ((checkMethod != methodDef) && (typeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault != NULL))
  16800. {
  16801. auto checkMethodInstance = typeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  16802. if (((checkMethodInstance->mChainType == BfMethodChainType_None) || (checkMethodInstance->mChainType == BfMethodChainType_ChainHead)) &&
  16803. (checkMethodInstance->GetExplicitInterface() == methodInstance->GetExplicitInterface()) &&
  16804. (CompareMethodSignatures(checkMethodInstance, mCurMethodInstance)))
  16805. {
  16806. bool canChain = false;
  16807. if ((methodDef->mParams.empty()) &&
  16808. (checkMethodInstance->mMethodDef->mIsStatic == methodInstance->mMethodDef->mIsStatic))
  16809. {
  16810. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) || (methodDef->mMethodType == BfMethodType_Dtor))
  16811. canChain = true;
  16812. else if (methodDef->mMethodType == BfMethodType_Normal)
  16813. {
  16814. if ((methodDef->mName == BF_METHODNAME_MARKMEMBERS) ||
  16815. (methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC) ||
  16816. (methodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS))
  16817. canChain = true;
  16818. }
  16819. }
  16820. if (canChain)
  16821. {
  16822. bool isBetter;
  16823. bool isWorse;
  16824. CompareDeclTypes(checkMethodInstance->mMethodDef->mDeclaringType, methodInstance->mMethodDef->mDeclaringType, isBetter, isWorse);
  16825. if (isBetter && !isWorse)
  16826. {
  16827. methodInstance->mChainType = BfMethodChainType_ChainHead;
  16828. checkMethodInstance->mChainType = BfMethodChainType_ChainMember;
  16829. }
  16830. else
  16831. {
  16832. checkMethodInstance->mChainType = BfMethodChainType_ChainHead;
  16833. methodInstance->mChainType = BfMethodChainType_ChainMember;
  16834. }
  16835. }
  16836. else if ((checkMethod->mBody == NULL) && (methodDef->mBody != NULL) &&
  16837. (checkMethod->mDeclaringType != methodDef->mDeclaringType))
  16838. {
  16839. // We're allowed to override an empty-bodied method
  16840. checkMethodInstance->mChainType = BfMethodChainType_ChainSkip;
  16841. }
  16842. else
  16843. {
  16844. if (!typeInstance->IsTypeMemberAccessible(checkMethod->mDeclaringType, methodDef->mDeclaringType))
  16845. continue;
  16846. bool silentlyAllow = false;
  16847. if (checkMethod->mDeclaringType != methodDef->mDeclaringType)
  16848. {
  16849. if (typeInstance->IsInterface())
  16850. {
  16851. if (methodDef->mIsOverride)
  16852. silentlyAllow = true;
  16853. }
  16854. else
  16855. silentlyAllow = true;
  16856. }
  16857. if (!silentlyAllow)
  16858. {
  16859. if (!methodDef->mName.IsEmpty())
  16860. {
  16861. auto refNode = methodDef->GetRefNode();
  16862. auto bfError = Fail("Method already declared with the same parameter types", refNode, true);
  16863. if (bfError != NULL)
  16864. mCompiler->mPassInstance->MoreInfo("First declaration", checkMethod->GetRefNode());
  16865. }
  16866. }
  16867. }
  16868. }
  16869. }
  16870. }
  16871. }
  16872. // Virtual methods give their error while slotting
  16873. if ((!typeInstance->IsBoxed()) && (!methodDef->mIsVirtual) && (methodDef->mProtection != BfProtection_Private) &&
  16874. (!methodDef->mIsLocalMethod) &&
  16875. (!methodInstance->mIsForeignMethodDef) && (typeInstance->mBaseType != NULL) &&
  16876. (methodDef->mMethodType == BfMethodType_Normal) && (methodDef->mMethodDeclaration != NULL))
  16877. {
  16878. bool foundHiddenMethod = false;
  16879. auto baseType = typeInstance->mBaseType;
  16880. while (baseType != NULL)
  16881. {
  16882. //for (int checkMethodIdx = 0; checkMethodIdx < (int) baseType->mTypeDef->mMethods.size(); checkMethodIdx++)
  16883. auto baseTypeDef = baseType->mTypeDef;
  16884. baseTypeDef->PopulateMemberSets();
  16885. BfMethodDef* checkMethod = NULL;
  16886. BfMemberSetEntry* entry = NULL;
  16887. if (baseTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  16888. checkMethod = (BfMethodDef*)entry->mMemberDef;
  16889. while (checkMethod != NULL)
  16890. {
  16891. if (checkMethod->mMethodDeclaration == NULL)
  16892. continue;
  16893. if (baseType->mMethodInstanceGroups.size() == 0)
  16894. {
  16895. BF_ASSERT(baseType->IsIncomplete() && mCompiler->IsAutocomplete());
  16896. break;
  16897. }
  16898. if (checkMethod == methodDef)
  16899. continue;
  16900. if (checkMethod->mName != methodDef->mName)
  16901. continue;
  16902. auto checkMethodInstance = GetRawMethodInstanceAtIdx(baseType, checkMethod->mIdx);
  16903. if (checkMethodInstance != NULL)
  16904. {
  16905. if ((checkMethodInstance->GetExplicitInterface() == methodInstance->GetExplicitInterface()) &&
  16906. (checkMethod->mProtection != BfProtection_Private) &&
  16907. (CompareMethodSignatures(checkMethodInstance, mCurMethodInstance)))
  16908. {
  16909. if (!methodDef->mIsNew)
  16910. {
  16911. BfAstNode* refNode = methodInstance->mMethodDef->GetRefNode();
  16912. if (refNode != NULL)
  16913. {
  16914. 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?
  16915. if (bfError != NULL)
  16916. bfError->mIsPersistent = true;
  16917. }
  16918. }
  16919. foundHiddenMethod = true;
  16920. break;
  16921. }
  16922. }
  16923. checkMethod = checkMethod->mNextWithSameName;
  16924. }
  16925. if (foundHiddenMethod)
  16926. break;
  16927. baseType = baseType->mBaseType;
  16928. }
  16929. if ((methodDef->mIsNew) && (!foundHiddenMethod))
  16930. {
  16931. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  16932. auto tokenNode = (propertyDeclaration != NULL) ? propertyDeclaration->mNewSpecifier :
  16933. methodDeclaration->mNewSpecifier;
  16934. Fail("Method does not hide an inherited member. The 'new' keyword is not required", tokenNode, true);
  16935. }
  16936. }
  16937. }
  16938. mCompiler->mStats.mMethodDeclarations++;
  16939. mCompiler->UpdateCompletion();
  16940. }
  16941. void BfModule::UniqueSlotVirtualMethod(BfMethodInstance* methodInstance)
  16942. {
  16943. BF_ASSERT(methodInstance->GetOwner() == mCurTypeInstance);
  16944. auto typeInstance = mCurTypeInstance;
  16945. auto methodDef = methodInstance->mMethodDef;
  16946. int virtualMethodMatchIdx = -1;
  16947. if (typeInstance->mHotTypeData != NULL)
  16948. {
  16949. if (typeInstance->mHotTypeData->mVTableOrigLength != -1)
  16950. {
  16951. BF_ASSERT(mCompiler->IsHotCompile());
  16952. // In the 'normal' case we'd assert that mIsOverride is false, but if we can't find the declaring method then we
  16953. // may slot this override anyway (?)
  16954. int vTableStart = 0;
  16955. if (typeInstance->mBaseType != NULL)
  16956. vTableStart = typeInstance->mBaseType->mVirtualMethodTableSize;
  16957. StringT<128> mangledName;
  16958. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  16959. for (int checkIdxOfs = 0; checkIdxOfs < (int)typeInstance->mHotTypeData->mVTableEntries.size(); checkIdxOfs++)
  16960. {
  16961. // O(1) checking when virtual methods haven't changed
  16962. int checkIdx = (typeInstance->mVirtualMethodTableSize - vTableStart + checkIdxOfs) % (int)typeInstance->mHotTypeData->mVTableEntries.size();
  16963. auto& entry = typeInstance->mHotTypeData->mVTableEntries[checkIdx];
  16964. if (mangledName == entry.mFuncName)
  16965. {
  16966. virtualMethodMatchIdx = vTableStart + checkIdx;
  16967. break;
  16968. }
  16969. }
  16970. if (virtualMethodMatchIdx != -1)
  16971. {
  16972. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  16973. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod = methodInstance;
  16974. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod = methodInstance;
  16975. }
  16976. typeInstance->mVirtualMethodTableSize = (int)typeInstance->mVirtualMethodTable.size();
  16977. }
  16978. }
  16979. if (virtualMethodMatchIdx == -1)
  16980. {
  16981. methodInstance->mVirtualTableIdx = typeInstance->mVirtualMethodTableSize++;
  16982. BfVirtualMethodEntry entry = { methodInstance, methodInstance };
  16983. typeInstance->mVirtualMethodTable.push_back(entry);
  16984. }
  16985. }
  16986. void BfModule::CompareDeclTypes(BfTypeDef* newDeclType, BfTypeDef* prevDeclType, bool& isBetter, bool& isWorse)
  16987. {
  16988. if ((!prevDeclType->IsExtension()) && (newDeclType->IsExtension()))
  16989. {
  16990. // When we provide an extension override in the same project a root type override
  16991. isBetter = true;
  16992. isWorse = false;
  16993. }
  16994. else
  16995. {
  16996. isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  16997. isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  16998. }
  16999. }
  17000. bool BfModule::SlotVirtualMethod(BfMethodInstance* methodInstance, BfAmbiguityContext* ambiguityContext)
  17001. {
  17002. BP_ZONE("BfModule::SlotVirtualMethod");
  17003. if (mCurTypeInstance->IsUnspecializedTypeVariation())
  17004. return false;
  17005. auto _AddVirtualDecl = [&](BfMethodInstance* declMethodInstance)
  17006. {
  17007. if (!mCompiler->mOptions.mAllowHotSwapping)
  17008. return;
  17009. if ((!methodInstance->mIsReified) || (!declMethodInstance->mIsReified))
  17010. return;
  17011. if (methodInstance->mHotMethod == NULL)
  17012. CheckHotMethod(methodInstance, "");
  17013. if (methodInstance->mHotMethod == NULL)
  17014. return;
  17015. //BF_ASSERT(declMethodInstance->mHotMethod != NULL);
  17016. if (declMethodInstance->mHotMethod == NULL)
  17017. CheckHotMethod(declMethodInstance, "");
  17018. auto virtualDecl = mCompiler->mHotData->GetVirtualDeclaration(declMethodInstance->mHotMethod);
  17019. virtualDecl->mRefCount++;
  17020. methodInstance->mHotMethod->mReferences.Add(virtualDecl);
  17021. };
  17022. auto typeInstance = mCurTypeInstance;
  17023. auto typeDef = typeInstance->mTypeDef;
  17024. auto methodDef = methodInstance->mMethodDef;
  17025. auto methodDeclaration = methodDef->GetMethodDeclaration();
  17026. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  17027. auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration();
  17028. BfAstNode* declaringNode = methodDeclaration;
  17029. if (propertyMethodDeclaration != NULL)
  17030. declaringNode = propertyMethodDeclaration->mNameNode;
  17031. BfMethodInstance* methodOverriden = NULL;
  17032. bool usedMethod = false;
  17033. BfTokenNode* virtualToken = NULL;
  17034. if (propertyDeclaration != NULL)
  17035. virtualToken = propertyDeclaration->mVirtualSpecifier;
  17036. else if (methodDeclaration != NULL)
  17037. virtualToken = methodDeclaration->mVirtualSpecifier;
  17038. if ((methodDef->mIsVirtual) && (methodDef->mIsStatic))
  17039. {
  17040. Fail("Static members cannot be marked as override, virtual, or abstract", virtualToken, true);
  17041. }
  17042. else if (methodDef->mIsVirtual)
  17043. {
  17044. if (mCompiler->IsHotCompile())
  17045. mContext->EnsureHotMangledVirtualMethodName(methodInstance);
  17046. if ((methodDef->mProtection == BfProtection_Private) && (virtualToken != NULL))
  17047. Fail("Virtual or abstract members cannot be private", virtualToken, true);
  17048. BfTypeInstance* checkBase = typeInstance;
  17049. // If we are in an extension, look in ourselves first
  17050. if (methodDef->mDeclaringType->mTypeDeclaration == typeInstance->mTypeDef->mTypeDeclaration)
  17051. checkBase = checkBase->mBaseType;
  17052. if (typeInstance->IsValueType())
  17053. {
  17054. if (typeInstance->mBaseType == NULL)
  17055. return false; // It's actually ValueType
  17056. // We allow structs to override object methods for when they get boxed, so just ignore 'override' keyword until it gets boxed
  17057. if (!methodDef->mIsOverride)
  17058. {
  17059. Fail("Structs cannot have virtual methods", virtualToken, true);
  17060. return false;
  17061. }
  17062. checkBase = mContext->mBfObjectType;
  17063. if (checkBase->mVirtualMethodTableSize == 0)
  17064. PopulateType(checkBase, BfPopulateType_Full);
  17065. if (checkBase->mDefineState < BfTypeDefineState_DefinedAndMethodsSlotted)
  17066. return false; // System circular ref, don't do struct checking on those
  17067. }
  17068. int virtualMethodMatchIdx = -1;
  17069. bool hadHidingError = false;
  17070. BfMethodInstance* bestOverrideMethodInstance = NULL;
  17071. BfMethodInstance* ambiguousOverrideMethodInstance = NULL;
  17072. int bestOverrideMethodIdx = -1;
  17073. int ambiguousOverrideMethodIdx = -1;
  17074. if (checkBase != NULL)
  17075. {
  17076. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  17077. auto lookupType = checkBase;
  17078. while (lookupType != NULL)
  17079. {
  17080. lookupType->mTypeDef->PopulateMemberSets();
  17081. BfMethodDef* nextMethodDef = NULL;
  17082. BfMemberSetEntry* entry;
  17083. if (lookupType->mTypeDef->mMethodSet.TryGetWith(methodInstance->mMethodDef->mName, &entry))
  17084. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  17085. while (nextMethodDef != NULL)
  17086. {
  17087. auto checkMethodDef = nextMethodDef;
  17088. nextMethodDef = nextMethodDef->mNextWithSameName;
  17089. if ((!checkMethodDef->mIsVirtual) || (checkMethodDef->mIsOverride))
  17090. continue;
  17091. BfMethodInstance* lookupMethodInstance = lookupType->mMethodInstanceGroups[checkMethodDef->mIdx].mDefault;
  17092. if ((lookupMethodInstance == NULL) || (lookupMethodInstance->mVirtualTableIdx == -1))
  17093. continue;
  17094. int checkMethodIdx = lookupMethodInstance->mVirtualTableIdx;
  17095. auto& baseMethodRef = baseVirtualMethodTable[checkMethodIdx];
  17096. if (baseMethodRef.mDeclaringMethod.mMethodNum == -1)
  17097. {
  17098. BF_ASSERT(mCompiler->mOptions.mHasVDataExtender);
  17099. continue;
  17100. }
  17101. BfMethodInstance* baseMethodInstance = baseVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  17102. if (baseMethodInstance == NULL)
  17103. {
  17104. AssertErrorState();
  17105. continue;
  17106. }
  17107. if ((baseMethodInstance != NULL) && (CompareMethodSignatures(baseMethodInstance, methodInstance)))
  17108. {
  17109. if (methodDef->mIsOverride)
  17110. {
  17111. BfMethodInstance* checkMethodInstance;
  17112. if (typeInstance->IsValueType())
  17113. checkMethodInstance = checkBase->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  17114. else
  17115. checkMethodInstance = typeInstance->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  17116. auto newDeclType = checkMethodInstance->mMethodDef->mDeclaringType;
  17117. if (!typeInstance->IsTypeMemberAccessible(newDeclType, methodDef->mDeclaringType->mProject))
  17118. continue;
  17119. if (bestOverrideMethodInstance != NULL)
  17120. {
  17121. auto prevDeclType = bestOverrideMethodInstance->mMethodDef->mDeclaringType;
  17122. bool isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  17123. bool isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  17124. if (isBetter == isWorse)
  17125. {
  17126. ambiguousOverrideMethodInstance = bestOverrideMethodInstance;
  17127. }
  17128. else
  17129. {
  17130. if (isWorse)
  17131. continue;
  17132. ambiguousOverrideMethodInstance = NULL;
  17133. }
  17134. }
  17135. bestOverrideMethodInstance = checkMethodInstance;
  17136. bestOverrideMethodIdx = checkMethodIdx;
  17137. }
  17138. else
  17139. {
  17140. if ((baseMethodInstance->GetOwner() != methodInstance->GetOwner()) && (!methodDef->mIsNew))
  17141. {
  17142. if (!hadHidingError)
  17143. Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use either 'override' or 'new'.", TypeToString(checkBase).c_str()), declaringNode);
  17144. hadHidingError = true;
  17145. }
  17146. }
  17147. }
  17148. }
  17149. lookupType = lookupType->mBaseType;
  17150. }
  17151. }
  17152. //TODO:
  17153. if ((checkBase != NULL)
  17154. && (false)
  17155. )
  17156. {
  17157. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  17158. for (int checkMethodIdx = (int) baseVirtualMethodTable.size() - 1; checkMethodIdx >= 0; checkMethodIdx--)
  17159. {
  17160. auto& baseMethodRef = baseVirtualMethodTable[checkMethodIdx];
  17161. if (baseMethodRef.mDeclaringMethod.mMethodNum == -1)
  17162. {
  17163. BF_ASSERT(mCompiler->mOptions.mHasVDataExtender);
  17164. continue;
  17165. }
  17166. BfMethodInstance* baseMethodInstance = baseVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  17167. if (baseMethodInstance == NULL)
  17168. {
  17169. AssertErrorState();
  17170. continue;
  17171. }
  17172. if ((baseMethodInstance != NULL) && (CompareMethodSignatures(baseMethodInstance, methodInstance)))
  17173. {
  17174. if (methodDef->mIsOverride)
  17175. {
  17176. BfMethodInstance* checkMethodInstance;
  17177. if (typeInstance->IsValueType())
  17178. checkMethodInstance = checkBase->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  17179. else
  17180. checkMethodInstance = typeInstance->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  17181. auto newDeclType = checkMethodInstance->mMethodDef->mDeclaringType;
  17182. if (!typeInstance->IsTypeMemberAccessible(newDeclType, methodDef->mDeclaringType->mProject))
  17183. continue;
  17184. if (bestOverrideMethodInstance != NULL)
  17185. {
  17186. auto prevDeclType = bestOverrideMethodInstance->mMethodDef->mDeclaringType;
  17187. bool isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  17188. bool isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  17189. if (isBetter == isWorse)
  17190. {
  17191. ambiguousOverrideMethodInstance = bestOverrideMethodInstance;
  17192. }
  17193. else
  17194. {
  17195. if (isWorse)
  17196. continue;
  17197. ambiguousOverrideMethodInstance = NULL;
  17198. }
  17199. }
  17200. bestOverrideMethodInstance = checkMethodInstance;
  17201. bestOverrideMethodIdx = checkMethodIdx;
  17202. }
  17203. else
  17204. {
  17205. if ((baseMethodInstance->GetOwner() != methodInstance->GetOwner()) && (!methodDef->mIsNew))
  17206. {
  17207. if (!hadHidingError)
  17208. Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use either 'override' or 'new'.", TypeToString(checkBase).c_str()), declaringNode);
  17209. hadHidingError = true;
  17210. }
  17211. }
  17212. }
  17213. }
  17214. }
  17215. if (bestOverrideMethodInstance != NULL)
  17216. {
  17217. if (ambiguousOverrideMethodInstance != NULL)
  17218. {
  17219. bool allow = false;
  17220. // 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.
  17221. // When when specialize, the specialized type will determine wither it has illegally pulled in both declarations or not
  17222. bool canSeeEachOther = false;
  17223. //
  17224. {
  17225. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, ambiguousOverrideMethodInstance);
  17226. if (bestOverrideMethodInstance->GetOwner()->IsTypeMemberIncluded(bestOverrideMethodInstance->mMethodDef->mDeclaringType, ambiguousOverrideMethodInstance->mMethodDef->mDeclaringType, this))
  17227. canSeeEachOther = true;
  17228. }
  17229. //
  17230. {
  17231. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, bestOverrideMethodInstance);
  17232. if (ambiguousOverrideMethodInstance->GetOwner()->IsTypeMemberIncluded(ambiguousOverrideMethodInstance->mMethodDef->mDeclaringType, bestOverrideMethodInstance->mMethodDef->mDeclaringType, this))
  17233. canSeeEachOther = true;
  17234. }
  17235. if (!canSeeEachOther)
  17236. {
  17237. BF_ASSERT(bestOverrideMethodInstance->GetOwner()->IsUnspecializedType() && ambiguousOverrideMethodInstance->GetOwner()->IsUnspecializedType());
  17238. }
  17239. else
  17240. {
  17241. auto error = Fail(StrFormat("Method '%s' is an ambiguous override", MethodToString(methodInstance).c_str()), methodDef->GetRefNode());
  17242. if (error != NULL)
  17243. {
  17244. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", MethodToString(bestOverrideMethodInstance).c_str()), bestOverrideMethodInstance->mMethodDef->GetRefNode());
  17245. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", MethodToString(ambiguousOverrideMethodInstance).c_str()), ambiguousOverrideMethodInstance->mMethodDef->GetRefNode());
  17246. }
  17247. }
  17248. }
  17249. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  17250. BfMethodInstance* baseVirtualMethodInstance = baseVirtualMethodTable[bestOverrideMethodIdx].mDeclaringMethod;
  17251. if ((baseVirtualMethodInstance != methodInstance) && (methodDef->mIsOverride))
  17252. {
  17253. if (baseVirtualMethodInstance->mReturnType != methodInstance->mReturnType)
  17254. {
  17255. BfTypeReference* returnTypeRef;
  17256. if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  17257. {
  17258. returnTypeRef = propertyDeclaration->mTypeRef;
  17259. Fail("Property differs from overridden property by type", returnTypeRef, true);
  17260. }
  17261. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  17262. {
  17263. returnTypeRef = methodDeclaration->mReturnType;
  17264. Fail("Method differs from overridden method by return value", returnTypeRef, true);
  17265. }
  17266. else
  17267. {
  17268. Fail(StrFormat("Internal error with method '%s'", MethodToString(methodInstance).c_str()));
  17269. }
  17270. return usedMethod;
  17271. }
  17272. }
  17273. if (methodDef->mIsOverride)
  17274. {
  17275. // We can have multiple matches when a virtual method is used to implement interface methods
  17276. // It doesn't matter what we set mVirtualTableIdx, as all base classes will override all matching
  17277. // vtable entries for this method signature
  17278. virtualMethodMatchIdx = bestOverrideMethodIdx;
  17279. if (!typeInstance->IsValueType())
  17280. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  17281. if (typeInstance->IsValueType())
  17282. {
  17283. methodOverriden = checkBase->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod;
  17284. }
  17285. else
  17286. {
  17287. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  17288. auto& overridenRef = typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod;
  17289. if (overridenRef.mKind != BfMethodRefKind_AmbiguousRef)
  17290. {
  17291. methodOverriden = overridenRef;
  17292. BfMethodInstance* setMethodInstance = methodInstance;
  17293. bool doOverride = true;
  17294. if (methodOverriden->GetOwner() == methodInstance->GetOwner())
  17295. {
  17296. bool isBetter = false;
  17297. bool isWorse = false;
  17298. CompareDeclTypes(methodInstance->mMethodDef->mDeclaringType, methodOverriden->mMethodDef->mDeclaringType, isBetter, isWorse);
  17299. if (isBetter == isWorse)
  17300. {
  17301. // We have to resolve later per-project
  17302. if ((ambiguityContext != NULL) && (ambiguityContext->mIsProjectSpecific))
  17303. {
  17304. auto declMethodInstance = checkBase->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod;
  17305. ambiguityContext->Add(virtualMethodMatchIdx, NULL, -1, methodOverriden, methodInstance);
  17306. }
  17307. if ((ambiguityContext == NULL) || (!ambiguityContext->mIsProjectSpecific))
  17308. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod.mKind = BfMethodRefKind_AmbiguousRef;
  17309. doOverride = false;
  17310. }
  17311. else
  17312. {
  17313. if ((isBetter) && (ambiguityContext != NULL))
  17314. {
  17315. ambiguityContext->Remove(virtualMethodMatchIdx);
  17316. }
  17317. doOverride = isBetter;
  17318. }
  17319. }
  17320. if (doOverride)
  17321. {
  17322. auto declMethodInstance = (BfMethodInstance*)typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod;
  17323. _AddVirtualDecl(declMethodInstance);
  17324. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod = setMethodInstance;
  17325. }
  17326. }
  17327. }
  17328. if (methodOverriden != NULL)
  17329. {
  17330. auto prevProtection = methodOverriden->mMethodDef->mProtection;
  17331. if ((methodDef->mProtection != prevProtection) && (methodDef->mMethodType != BfMethodType_Dtor))
  17332. {
  17333. const char* protectionNames[] = {"hidden", "private", "protected", "public"};
  17334. BfAstNode* protectionRefNode = NULL;
  17335. if (auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration())
  17336. {
  17337. protectionRefNode = propertyMethodDeclaration->mProtectionSpecifier;
  17338. if (protectionRefNode == NULL)
  17339. protectionRefNode = propertyMethodDeclaration->mPropertyDeclaration->mProtectionSpecifier;
  17340. if (protectionRefNode == NULL)
  17341. protectionRefNode = propertyMethodDeclaration->mPropertyDeclaration->mNameNode;
  17342. }
  17343. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  17344. {
  17345. protectionRefNode = methodDeclaration->mProtectionSpecifier;
  17346. if (protectionRefNode == NULL)
  17347. protectionRefNode = methodDeclaration->mNameNode;
  17348. }
  17349. if (protectionRefNode != NULL)
  17350. Fail(StrFormat("Cannot change access modifiers when overriding '%s' inherited member", protectionNames[(int)prevProtection]), protectionRefNode, true);
  17351. }
  17352. }
  17353. }
  17354. }
  17355. if ((virtualMethodMatchIdx == -1) && ((ambiguityContext == NULL) || (!ambiguityContext->mIsReslotting)))
  17356. {
  17357. if (methodDef->mIsOverride)
  17358. {
  17359. BfTokenNode* overrideToken = NULL;
  17360. if (auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration())
  17361. overrideToken = propertyMethodDeclaration->mPropertyDeclaration->mVirtualSpecifier;
  17362. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  17363. overrideToken = methodDeclaration->mVirtualSpecifier;
  17364. if (overrideToken != NULL)
  17365. {
  17366. if ((propertyDeclaration != NULL) && (propertyDeclaration->mNameNode != NULL) &&
  17367. ((methodDef->mMethodType == BfMethodType_PropertyGetter) || (methodDef->mMethodType == BfMethodType_PropertySetter)))
  17368. Fail(StrFormat("No suitable method found to override for '%s.%s'",
  17369. propertyDeclaration->mNameNode->ToString().c_str(), (methodDef->mMethodType == BfMethodType_PropertyGetter) ? "get" : "set"), overrideToken, true);
  17370. else
  17371. Fail("No suitable method found to override", overrideToken, true);
  17372. }
  17373. return usedMethod;
  17374. }
  17375. UniqueSlotVirtualMethod(methodInstance);
  17376. }
  17377. else
  17378. usedMethod = true;
  17379. if (typeInstance->IsValueType())
  17380. return usedMethod;
  17381. }
  17382. bool foundInterface = false;
  17383. bool hadAnyMatch = false;
  17384. // See if this method matches interfaces
  17385. for (auto& ifaceTypeInst : typeInstance->mInterfaces)
  17386. {
  17387. auto ifaceInst = ifaceTypeInst.mInterfaceType;
  17388. if (ifaceInst->IsIncomplete())
  17389. PopulateType(ifaceInst, BfPopulateType_DataAndMethods);
  17390. int startIdx = ifaceTypeInst.mStartInterfaceTableIdx;
  17391. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  17392. // See "bidirectional" rules mentioned in DoTypeInstanceMethodProcessing
  17393. if ((!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, ifaceTypeInst.mDeclaringType)) &&
  17394. (!typeInstance->IsTypeMemberAccessible(ifaceTypeInst.mDeclaringType, methodDef->mDeclaringType)))
  17395. continue;
  17396. if (!typeInstance->IsTypeMemberIncluded(methodDef->mDeclaringType, ifaceTypeInst.mDeclaringType, this))
  17397. continue;
  17398. bool hadMatch = false;
  17399. bool hadNameMatch = false;
  17400. BfType* expectedReturnType = NULL;
  17401. bool showedError = false;
  17402. // We go through our VTable looking for NULL entries within the interface sections
  17403. // The only instance of finding a "better" method is when we have explicitly interface-dotted method
  17404. // because a normal method declared in this type could have matched earlier
  17405. //for (int iMethodIdx = 0; iMethodIdx < iMethodCount; iMethodIdx++)
  17406. ifaceInst->mTypeDef->PopulateMemberSets();
  17407. BfMethodDef* checkMethodDef = NULL;
  17408. BfMemberSetEntry* entry;
  17409. if (ifaceInst->mTypeDef->mMethodSet.TryGetWith(methodInstance->mMethodDef->mName, &entry))
  17410. checkMethodDef = (BfMethodDef*)entry->mMemberDef;
  17411. while (checkMethodDef != NULL)
  17412. {
  17413. int iMethodIdx = checkMethodDef->mIdx;
  17414. int iTableIdx = iMethodIdx + startIdx;
  17415. BfTypeInterfaceMethodEntry* interfaceMethodEntry = &typeInstance->mInterfaceMethodTable[iTableIdx];
  17416. auto iMethodPtr = &interfaceMethodEntry->mMethodRef;
  17417. bool storeIFaceMethod = false;
  17418. if ((mCompiler->mPassInstance->HasFailed()) && (iMethodIdx >= (int)ifaceInst->mMethodInstanceGroups.size()))
  17419. continue;
  17420. auto& iMethodGroup = ifaceInst->mMethodInstanceGroups[iMethodIdx];
  17421. auto iMethodInst = iMethodGroup.mDefault;
  17422. if (iMethodInst == NULL)
  17423. {
  17424. if ((!ifaceInst->IsGenericTypeInstance()) || (!ifaceInst->mTypeDef->mIsCombinedPartial))
  17425. AssertErrorState();
  17426. continue;
  17427. }
  17428. if (iMethodInst->mMethodDef->mName == methodInstance->mMethodDef->mName)
  17429. hadNameMatch = true;
  17430. bool doesMethodSignatureMatch = CompareMethodSignatures(iMethodInst, methodInstance);
  17431. if ((!doesMethodSignatureMatch) && (iMethodInst->GetNumGenericParams() == 0) && (interfaceMethodEntry->mMethodRef.IsNull()))
  17432. {
  17433. doesMethodSignatureMatch = IsCompatibleInterfaceMethod(iMethodInst, methodInstance);
  17434. }
  17435. if ((doesMethodSignatureMatch) && (methodInstance->GetOwner()->IsValueType()))
  17436. {
  17437. if ((!iMethodInst->mMethodDef->mIsMutating) && (methodInstance->mMethodDef->mIsMutating))
  17438. {
  17439. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface == ifaceInst))
  17440. {
  17441. auto error = mCompiler->mPassInstance->Fail(StrFormat("Implementation method '%s' cannot specify 'mut' because the interface method does not allow it",
  17442. MethodToString(methodInstance).c_str()), methodInstance->mMethodDef->GetMutNode());
  17443. if (error != NULL)
  17444. mCompiler->mPassInstance->MoreInfo(StrFormat("Declare the interface method as 'mut' to allow matching 'mut' implementations"), iMethodInst->mMethodDef->mMethodDeclaration);
  17445. showedError = true;
  17446. }
  17447. }
  17448. }
  17449. if (doesMethodSignatureMatch)
  17450. {
  17451. usedMethod = true;
  17452. hadMatch = true;
  17453. hadAnyMatch = true;
  17454. storeIFaceMethod = true;
  17455. if ((iMethodPtr->mKind != BfMethodRefKind_AmbiguousRef) && (iMethodPtr->mTypeInstance != NULL))
  17456. {
  17457. auto prevMethod = (BfMethodInstance*)*iMethodPtr;
  17458. if ((mCompiler->mIsResolveOnly) && (prevMethod == methodInstance))
  17459. {
  17460. // When autocompletion regenerates a single method body but not the whole type then
  17461. // we will see ourselves in the vtable already
  17462. return usedMethod;
  17463. }
  17464. bool isBetter = false;
  17465. bool isWorse = false;
  17466. isBetter = (methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL);
  17467. isWorse = (prevMethod->mMethodInfoEx != NULL) && (prevMethod->mMethodInfoEx->mExplicitInterface != NULL);
  17468. if (isBetter == isWorse)
  17469. CompareDeclTypes(methodInstance->mMethodDef->mDeclaringType, prevMethod->mMethodDef->mDeclaringType, isBetter, isWorse);
  17470. if (isBetter == isWorse)
  17471. {
  17472. if (ambiguityContext != NULL)
  17473. {
  17474. ambiguityContext->Add(~iTableIdx, &ifaceTypeInst, iMethodIdx, prevMethod, methodInstance);
  17475. }
  17476. iMethodPtr->mKind = BfMethodRefKind_AmbiguousRef;
  17477. storeIFaceMethod = true;
  17478. }
  17479. else
  17480. {
  17481. if ((isBetter) && (ambiguityContext != NULL))
  17482. ambiguityContext->Remove(~iTableIdx);
  17483. storeIFaceMethod = isBetter;
  17484. }
  17485. }
  17486. }
  17487. if (storeIFaceMethod)
  17488. {
  17489. _AddVirtualDecl(iMethodInst);
  17490. *iMethodPtr = methodInstance;
  17491. }
  17492. checkMethodDef = checkMethodDef->mNextWithSameName;
  17493. }
  17494. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface == ifaceInst) && (!hadMatch) && (!showedError))
  17495. {
  17496. if (expectedReturnType != NULL)
  17497. Fail(StrFormat("Wrong return type, expected '%s'", TypeToString(expectedReturnType).c_str()), declaringNode, true);
  17498. else if (hadNameMatch)
  17499. Fail("Method parameters don't match interface method", declaringNode, true);
  17500. else
  17501. Fail("Method name not found in interface", methodDef->GetRefNode(), true);
  17502. }
  17503. }
  17504. // Any overriden virtual methods that were used in interfaces also need to be replaced
  17505. if (methodOverriden != NULL)
  17506. {
  17507. for (auto& methodEntry : typeInstance->mInterfaceMethodTable)
  17508. {
  17509. if (methodEntry.mMethodRef == methodOverriden)
  17510. methodEntry.mMethodRef = methodInstance;
  17511. }
  17512. }
  17513. return usedMethod;
  17514. }
  17515. bool BfModule::SlotInterfaceMethod(BfMethodInstance* methodInstance)
  17516. {
  17517. auto typeInstance = mCurTypeInstance;
  17518. auto methodDef = methodInstance->mMethodDef;
  17519. if (methodDef->mMethodType == BfMethodType_Ctor)
  17520. return true;
  17521. bool foundOverride = false;
  17522. if ((methodDef->mBody == NULL) && (methodDef->mProtection == BfProtection_Private))
  17523. {
  17524. Fail("Private interface methods must provide a body", methodDef->GetMethodDeclaration()->mProtectionSpecifier);
  17525. }
  17526. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL) && (!methodDef->mIsOverride))
  17527. {
  17528. Fail("Explicit interfaces can only be specified for overrides in interface declarations", methodDef->GetMethodDeclaration()->mExplicitInterface);
  17529. }
  17530. BfAstNode* declaringNode = methodDef->GetRefNode();
  17531. for (auto& ifaceTypeInst : typeInstance->mInterfaces)
  17532. {
  17533. auto ifaceInst = ifaceTypeInst.mInterfaceType;
  17534. int startIdx = ifaceTypeInst.mStartInterfaceTableIdx;
  17535. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  17536. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != ifaceInst))
  17537. continue;
  17538. ifaceInst->mTypeDef->PopulateMemberSets();
  17539. BfMethodDef* nextMethod = NULL;
  17540. BfMemberSetEntry* entry = NULL;
  17541. if (ifaceInst->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  17542. nextMethod = (BfMethodDef*)entry->mMemberDef;
  17543. while (nextMethod != NULL)
  17544. {
  17545. auto checkMethod = nextMethod;
  17546. nextMethod = nextMethod->mNextWithSameName;
  17547. auto ifaceMethod = ifaceInst->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  17548. if (ifaceMethod == NULL)
  17549. continue;
  17550. if (CompareMethodSignatures(ifaceMethod, methodInstance))
  17551. {
  17552. if (methodDef->mIsOverride)
  17553. {
  17554. if (ifaceMethod->mMethodDef->mProtection == BfProtection_Private)
  17555. {
  17556. auto error = Fail(StrFormat("Interface method '%s' cannot override private interface method '%s'", MethodToString(methodInstance).c_str(), MethodToString(ifaceMethod).c_str()), declaringNode);
  17557. if (error != NULL)
  17558. {
  17559. mCompiler->mPassInstance->MoreInfo("See base interface method", ifaceMethod->mMethodDef->GetRefNode());
  17560. }
  17561. }
  17562. foundOverride = true;
  17563. }
  17564. else if (!methodDef->mIsNew)
  17565. {
  17566. Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use the 'new' keyword if hiding was intentional.", TypeToString(ifaceInst).c_str()), declaringNode);
  17567. }
  17568. }
  17569. }
  17570. }
  17571. if ((methodDef->mIsOverride) && (!foundOverride))
  17572. {
  17573. // This allows us to declare a method in the base definition or in an extension and then provide
  17574. // an implementation in a more-specific extension
  17575. typeInstance->mTypeDef->PopulateMemberSets();
  17576. BfMethodDef* nextMethod = NULL;
  17577. BfMemberSetEntry* entry = NULL;
  17578. if (typeInstance->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  17579. nextMethod = (BfMethodDef*)entry->mMemberDef;
  17580. while (nextMethod != NULL)
  17581. {
  17582. auto checkMethod = nextMethod;
  17583. nextMethod = nextMethod->mNextWithSameName;
  17584. auto ifaceMethod = typeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  17585. if (ifaceMethod == NULL)
  17586. continue;
  17587. if (ifaceMethod->mMethodDef->mDeclaringType == methodInstance->mMethodDef->mDeclaringType)
  17588. continue;
  17589. if (CompareMethodSignatures(ifaceMethod, methodInstance))
  17590. {
  17591. foundOverride = true;
  17592. }
  17593. }
  17594. // for (int methodIdx = 0; methodIdx < typeInstance->mMethodInstanceGroups.size(); methodIdx++)
  17595. // {
  17596. // auto ifaceMethod = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  17597. // if (ifaceMethod == NULL)
  17598. // continue;
  17599. // if (ifaceMethod->mMethodDef->mDeclaringType == methodInstance->mMethodDef->mDeclaringType)
  17600. // continue;
  17601. //
  17602. // if (CompareMethodSignatures(ifaceMethod, methodInstance))
  17603. // {
  17604. // foundOverride = true;
  17605. // }
  17606. // }
  17607. }
  17608. if (methodDef->mIsOverride)
  17609. {
  17610. if (!foundOverride)
  17611. {
  17612. BfTokenNode* overrideToken = NULL;
  17613. if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  17614. overrideToken = propertyDeclaration->mVirtualSpecifier;
  17615. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  17616. overrideToken = methodDeclaration->mVirtualSpecifier;
  17617. if (overrideToken != NULL)
  17618. {
  17619. Fail("No suitable method found to override", overrideToken, true);
  17620. }
  17621. else
  17622. {
  17623. // Possible cause - DTOR with params
  17624. AssertErrorState();
  17625. }
  17626. }
  17627. return true;
  17628. }
  17629. // Generic methods can't be called virtually
  17630. if (methodInstance->GetNumGenericParams() != 0)
  17631. return true;
  17632. // Only public methods can be called virtually
  17633. if (methodDef->mProtection != BfProtection_Public)
  17634. return true;
  17635. UniqueSlotVirtualMethod(methodInstance);
  17636. return true;
  17637. }
  17638. void BfModule::DbgFinish()
  17639. {
  17640. if ((mBfIRBuilder == NULL) || (mExtensionCount != 0))
  17641. return;
  17642. if (mAwaitingInitFinish)
  17643. FinishInit();
  17644. if (mHasForceLinkMarker)
  17645. return;
  17646. String markerName;
  17647. BfIRValue linkMarker;
  17648. if (mBfIRBuilder->DbgHasInfo())
  17649. {
  17650. bool needForceLinking = false;
  17651. for (auto& ownedType : mOwnedTypeInstances)
  17652. {
  17653. bool hasConfirmedReference = false;
  17654. for (auto& methodInstGroup : ownedType->mMethodInstanceGroups)
  17655. {
  17656. if ((methodInstGroup.IsImplemented()) && (methodInstGroup.mDefault != NULL) &&
  17657. (!methodInstGroup.mDefault->mMethodDef->mIsStatic) && (methodInstGroup.mDefault->mIsReified) &&
  17658. ((methodInstGroup.mOnDemandKind == BfMethodOnDemandKind_AlwaysInclude) || (methodInstGroup.mOnDemandKind == BfMethodOnDemandKind_Referenced)))
  17659. {
  17660. hasConfirmedReference = true;
  17661. }
  17662. }
  17663. if ((!hasConfirmedReference) || (ownedType->IsBoxed()))
  17664. needForceLinking = true;
  17665. }
  17666. if ((needForceLinking) && (mProject->mCodeGenOptions.mAsmKind == BfAsmKind_None))
  17667. {
  17668. BfMethodState methodState;
  17669. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  17670. methodState.mTempKind = BfMethodState::TempKind_Static;
  17671. mHasForceLinkMarker = true;
  17672. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  17673. SizedArray<BfIRType, 0> paramTypes;
  17674. BfIRFunctionType funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  17675. String linkName = "FORCELINKMOD_" + mModuleName;
  17676. BfIRFunction func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, linkName);
  17677. mBfIRBuilder->SetActiveFunction(func);
  17678. auto entryBlock = mBfIRBuilder->CreateBlock("main", true);
  17679. mBfIRBuilder->SetInsertPoint(entryBlock);
  17680. auto firstType = mOwnedTypeInstances[0];
  17681. UpdateSrcPos(mContext->mBfObjectType->mTypeDef->GetRefNode());
  17682. SizedArray<BfIRMDNode, 1> diParamTypes;
  17683. diParamTypes.Add(mBfIRBuilder->DbgGetType(GetPrimitiveType(BfTypeCode_None)));
  17684. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParamTypes);
  17685. auto diScope = mBfIRBuilder->DbgCreateFunction(mDICompileUnit, "FORCELINKMOD", linkName, mCurFilePosition.mFileInstance->mDIFile,
  17686. mCurFilePosition.mCurLine + 1, diFuncType, false, true, mCurFilePosition.mCurLine + 1, 0, false, func);
  17687. methodState.mCurScope->mDIScope = diScope;
  17688. UpdateSrcPos(mContext->mBfObjectType->mTypeDef->GetRefNode(), BfSrcPosFlag_Force);
  17689. SizedArray<BfIRValue, 8> args;
  17690. BfExprEvaluator exprEvaluator(this);
  17691. for (auto& ownedType : mOwnedTypeInstances)
  17692. {
  17693. auto alloca = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int8)));
  17694. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(diScope, "variable", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(ownedType));
  17695. mBfIRBuilder->DbgInsertDeclare(alloca, diVariable);
  17696. }
  17697. mBfIRBuilder->CreateRetVoid();
  17698. mBfIRBuilder->SetActiveFunction(BfIRFunction());
  17699. }
  17700. }
  17701. }
  17702. bool BfModule::Finish()
  17703. {
  17704. BP_ZONE("BfModule::Finish");
  17705. BfLogSysM("BfModule finish: %p\n", this);
  17706. if (mHadBuildError)
  17707. {
  17708. // Don't AssertErrorState here, this current pass may not have failed but
  17709. // the module was still queued in mFinishedModuleWorkList
  17710. ClearModule();
  17711. return true;
  17712. }
  17713. if (mUsedSlotCount != -1)
  17714. {
  17715. BF_ASSERT(mCompiler->mMaxInterfaceSlots != -1);
  17716. mUsedSlotCount = mCompiler->mMaxInterfaceSlots;
  17717. }
  17718. BF_ASSERT(mAddedToCount);
  17719. mAddedToCount = false;
  17720. mAwaitingFinish = false;
  17721. mCompiler->mStats.mModulesFinished++;
  17722. if (HasCompiledOutput())
  17723. {
  17724. DbgFinish();
  17725. if (mAwaitingInitFinish)
  17726. FinishInit();
  17727. for (auto ownedTypeInst : mOwnedTypeInstances)
  17728. {
  17729. // Generate dbg info and add global variables if we haven't already
  17730. mBfIRBuilder->PopulateType(ownedTypeInst);
  17731. }
  17732. if (mBfIRBuilder->DbgHasInfo())
  17733. {
  17734. mBfIRBuilder->DbgFinalize();
  17735. }
  17736. String objOutputPath;
  17737. String irOutputPath;
  17738. mIsModuleMutable = false;
  17739. //mOutFileNames.Clear();
  17740. BF_ASSERT((int)mOutFileNames.size() >= mExtensionCount);
  17741. bool writeModule = mBfIRBuilder->HasExports();
  17742. String outputPath;
  17743. BfCodeGenOptions codeGenOptions = mProject->mCodeGenOptions;
  17744. auto& compilerOpts = mCompiler->mOptions;
  17745. codeGenOptions.mSIMDSetting = compilerOpts.mSIMDSetting;
  17746. auto moduleOptions = GetModuleOptions();
  17747. codeGenOptions.mOptLevel = moduleOptions.mOptLevel;
  17748. codeGenOptions.mSIMDSetting = moduleOptions.mSIMDSetting;
  17749. codeGenOptions.mWriteLLVMIR = mCompiler->mOptions.mWriteIR;
  17750. codeGenOptions.mWriteObj = mCompiler->mOptions.mGenerateObj;
  17751. codeGenOptions.mVirtualMethodOfs = 1 + mCompiler->GetDynCastVDataCount() + mCompiler->mMaxInterfaceSlots;
  17752. codeGenOptions.mDynSlotOfs = mSystem->mPtrSize - mCompiler->GetDynCastVDataCount() * 4;
  17753. mCompiler->mStats.mIRBytes += mBfIRBuilder->mStream.GetSize();
  17754. mCompiler->mStats.mConstBytes += mBfIRBuilder->mTempAlloc.GetAllocSize();
  17755. bool allowWriteToLib = true;
  17756. if ((allowWriteToLib) && (codeGenOptions.mOptLevel == BfOptLevel_OgPlus) && (mModuleName != "vdata"))
  17757. {
  17758. codeGenOptions.mWriteToLib = true;
  17759. mWroteToLib = true;
  17760. }
  17761. else
  17762. {
  17763. mWroteToLib = false;
  17764. }
  17765. for (int fileIdx = 0; fileIdx <= mExtensionCount; fileIdx++)
  17766. {
  17767. outputPath = mModuleName;
  17768. outputPath = mCompiler->mOutputDirectory + "/" + mProject->mName + "/" + outputPath;
  17769. BfModuleFileName moduleFileName;
  17770. if (mParentModule != NULL)
  17771. {
  17772. for (auto&& checkPair : mParentModule->mSpecializedMethodModules)
  17773. {
  17774. if (checkPair.mValue == this)
  17775. moduleFileName.mProjects = checkPair.mKey;
  17776. }
  17777. }
  17778. moduleFileName.mProjects.Add(mProject);
  17779. if (fileIdx > 0)
  17780. outputPath += StrFormat("@%d", fileIdx + 1);
  17781. if (mCompiler->mOptions.mWriteIR)
  17782. irOutputPath = outputPath + ".ll";
  17783. if (mCompiler->mOptions.mGenerateObj)
  17784. {
  17785. objOutputPath = outputPath + BF_OBJ_EXT;
  17786. moduleFileName.mFileName = objOutputPath;
  17787. }
  17788. else if (mCompiler->mOptions.mWriteIR)
  17789. {
  17790. moduleFileName.mFileName = irOutputPath;
  17791. }
  17792. else if ((!mCompiler->mOptions.mGenerateObj) && (!mCompiler->mOptions.mWriteIR))
  17793. {
  17794. BF_FATAL("Neither obj nor IR specified");
  17795. }
  17796. moduleFileName.mModuleWritten = writeModule;
  17797. moduleFileName.mWroteToLib = mWroteToLib;
  17798. if (!mOutFileNames.Contains(moduleFileName))
  17799. mOutFileNames.Add(moduleFileName);
  17800. }
  17801. if (mCompiler->IsHotCompile())
  17802. {
  17803. codeGenOptions.mIsHotCompile = true;
  17804. //TODO: Why did we have this 'mWroteToLib' check? 'vdata' didn't get this flag set, which
  17805. // is required for rebuilding vdata after we hot create a vdata
  17806. //if (mWroteToLib)
  17807. {
  17808. if (mParentModule != NULL)
  17809. mParentModule->mHadHotObjectWrites = true;
  17810. mHadHotObjectWrites = true;
  17811. }
  17812. }
  17813. //TODO: Testing VDATA
  17814. /*if (mModuleName == "vdata")
  17815. {
  17816. codeGenOptions.mOptLevel = 4;
  17817. }*/
  17818. codeGenOptions.GenerateHash();
  17819. BP_ZONE("BfModule::Finish.WriteObjectFile");
  17820. if ((writeModule) && (!mBfIRBuilder->mIgnoreWrites))
  17821. mCompiler->mCodeGen.WriteObjectFile(this, outputPath, codeGenOptions);
  17822. mLastModuleWrittenRevision = mCompiler->mRevision;
  17823. }
  17824. else
  17825. {
  17826. for (auto type : mOwnedTypeInstances)
  17827. {
  17828. BF_ASSERT(!type->IsIncomplete());
  17829. }
  17830. }
  17831. for (auto& specModulePair : mSpecializedMethodModules)
  17832. {
  17833. auto specModule = specModulePair.mValue;
  17834. if ((specModule->mIsModuleMutable) && (!specModule->mAwaitingFinish))
  17835. {
  17836. BfLogSysM(" Mutable spec module remaining: %p\n", specModule);
  17837. }
  17838. }
  17839. CleanupFileInstances();
  17840. // We can't ClearModuleData here because we need the mSpecializedMethodModules to remain valid until we Finish them too
  17841. return true;
  17842. }
  17843. void BfModule::ReportMemory(MemReporter* memReporter)
  17844. {
  17845. memReporter->Add(sizeof(BfModule));
  17846. if (mBfIRBuilder != NULL)
  17847. {
  17848. memReporter->BeginSection("IRBuilder_ConstData");
  17849. memReporter->Add("Used", mBfIRBuilder->mTempAlloc.GetAllocSize());
  17850. memReporter->Add("Unused", mBfIRBuilder->mTempAlloc.GetTotalAllocSize() - mBfIRBuilder->mTempAlloc.GetAllocSize());
  17851. memReporter->EndSection();
  17852. memReporter->BeginSection("IRBuilder_BFIR");
  17853. memReporter->Add("Used", (int)(mBfIRBuilder->mStream.GetSize()));
  17854. memReporter->Add("Unused", (int)(mBfIRBuilder->mStream.mPools.size() * ChunkedDataBuffer::ALLOC_SIZE) - mBfIRBuilder->mStream.GetSize());
  17855. memReporter->EndSection();
  17856. memReporter->Add(sizeof(BfIRBuilder));
  17857. }
  17858. memReporter->BeginSection("FileInstanceMap");
  17859. memReporter->AddMap(mFileInstanceMap);
  17860. memReporter->AddMap(mNamedFileInstanceMap);
  17861. memReporter->Add((int)mNamedFileInstanceMap.size() * sizeof(BfFileInstance));
  17862. memReporter->EndSection();
  17863. memReporter->AddVec(mOwnedTypeInstances, false);
  17864. memReporter->AddVec(mSpecializedMethodModules, false);
  17865. memReporter->AddVec(mOutFileNames, false);
  17866. memReporter->AddMap("FuncReferences", mFuncReferences, false);
  17867. memReporter->AddMap(mInterfaceSlotRefs, false);
  17868. memReporter->AddMap(mStaticFieldRefs, false);
  17869. memReporter->AddMap(mClassVDataRefs, false);
  17870. memReporter->AddMap("VDataExtMap", mClassVDataExtRefs, false);
  17871. memReporter->AddMap(mTypeDataRefs, false);
  17872. memReporter->AddMap(mDbgRawAllocDataRefs, false);
  17873. memReporter->AddMap(mDeferredMethodCallData, false);
  17874. memReporter->AddHashSet(mDeferredMethodIds, false);
  17875. memReporter->AddHashSet("ModuleRefs", mModuleRefs, false);
  17876. }
  17877. // ClearModuleData is called immediately after the module is compiled, so don't clear out any data that needs to
  17878. // be transient through the next compile
  17879. void BfModule::ClearModuleData()
  17880. {
  17881. BfLogSysM("ClearModuleData %p\n", this);
  17882. if (mAddedToCount)
  17883. {
  17884. mCompiler->mStats.mModulesFinished++;
  17885. mAddedToCount = false;
  17886. }
  17887. mDICompileUnit = BfIRMDNode();
  17888. mIsModuleMutable = false;
  17889. mIncompleteMethodCount = 0;
  17890. mHasGenericMethods = false;
  17891. // We don't want to clear these because we want it to persist through module extensions-
  17892. // otherwise we may think an extension succeeds even though the base module failed
  17893. //mHadBuildError = false;
  17894. //mHadBuildWarning = false;
  17895. mClassVDataRefs.Clear();
  17896. mClassVDataExtRefs.Clear();
  17897. for (auto& kv : mTypeDataRefs)
  17898. kv.mValue = BfIRValue();
  17899. mStringCharPtrPool.Clear();
  17900. mStringObjectPool.Clear();
  17901. mStaticFieldRefs.Clear();
  17902. BF_ASSERT(!mIgnoreErrors);
  17903. for (auto prevIRBuilder : mPrevIRBuilders)
  17904. delete prevIRBuilder;
  17905. mPrevIRBuilders.Clear();
  17906. for (auto& specPair : mSpecializedMethodModules)
  17907. {
  17908. auto specModule = specPair.mValue;
  17909. specModule->ClearModuleData();
  17910. }
  17911. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  17912. mBuiltInFuncs[i] = BfIRFunction();
  17913. if (mNextAltModule != NULL)
  17914. mNextAltModule->ClearModuleData();
  17915. BfLogSysM("ClearModuleData. Deleting IRBuilder: %p\n", mBfIRBuilder);
  17916. delete mBfIRBuilder;
  17917. mBfIRBuilder = NULL;
  17918. mWantsIRIgnoreWrites = false;
  17919. }
  17920. void BfModule::DisownMethods()
  17921. {
  17922. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  17923. mBuiltInFuncs[i] = BfIRFunction();
  17924. BfModule* methodModule = this;
  17925. if (mParentModule != NULL)
  17926. methodModule = mParentModule;
  17927. for (auto typeInst : methodModule->mOwnedTypeInstances)
  17928. {
  17929. for (auto& methodGroup : typeInst->mMethodInstanceGroups)
  17930. {
  17931. if (methodGroup.mDefault != NULL)
  17932. {
  17933. if (methodGroup.mDefault->mIRFunction)
  17934. {
  17935. BF_ASSERT(methodGroup.mDefault->mDeclModule != NULL);
  17936. if (methodGroup.mDefault->mDeclModule == this)
  17937. {
  17938. methodGroup.mDefault->mIRFunction = BfIRFunction();
  17939. }
  17940. }
  17941. }
  17942. if (methodGroup.mMethodSpecializationMap != NULL)
  17943. {
  17944. for (auto& mapPair : *methodGroup.mMethodSpecializationMap)
  17945. {
  17946. auto methodInstance = mapPair.mValue;
  17947. if (methodInstance->mDeclModule == this)
  17948. {
  17949. methodInstance->mIRFunction = BfIRFunction();
  17950. }
  17951. }
  17952. }
  17953. }
  17954. }
  17955. }
  17956. void BfModule::ClearModule()
  17957. {
  17958. ClearModuleData();
  17959. DisownMethods();
  17960. for (auto& specPair : mSpecializedMethodModules)
  17961. {
  17962. auto specModule = specPair.mValue;
  17963. specModule->ClearModule();
  17964. }
  17965. if (mNextAltModule != NULL)
  17966. mNextAltModule->ClearModule();
  17967. }