BfModule.cpp 775 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878
  1. //#define USE_THUNKED_MddLLOC..
  2. #include "BeefySysLib/util/AllocDebug.h"
  3. #pragma warning(disable:4996)
  4. #pragma warning(push) // 6
  5. #include "BfCompiler.h"
  6. #include "BfSystem.h"
  7. #include "BfParser.h"
  8. #include "BfCodeGen.h"
  9. #include "BfExprEvaluator.h"
  10. #include "../Backend/BeLibManger.h"
  11. #include <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. mAssignedKind = BfLocalVarAssignKind_Unconditional;
  35. return;
  36. }
  37. if (mAssignedKind != BfLocalVarAssignKind_None)
  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. mAssignedKind = BfLocalVarAssignKind_Unconditional;
  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. for (int i = 0; i < (int)mAssignedLocals.size(); )
  103. {
  104. auto& local = mAssignedLocals[i];
  105. bool wantRemove = true;
  106. bool foundOtherFields = false;
  107. for (auto& otherLocalAssignData : otherLocalAssignData.mAssignedLocals)
  108. {
  109. if (otherLocalAssignData.mLocalVar == local.mLocalVar)
  110. {
  111. if ((otherLocalAssignData.mLocalVarField == local.mLocalVarField) || (otherLocalAssignData.mLocalVarField == -1))
  112. {
  113. if (otherLocalAssignData.mAssignKind == BfLocalVarAssignKind_Conditional)
  114. local.mAssignKind = BfLocalVarAssignKind_Conditional;
  115. wantRemove = false;
  116. }
  117. else
  118. foundOtherFields = true;
  119. }
  120. }
  121. if ((wantRemove) && (foundOtherFields))
  122. {
  123. for (auto& otherLocalAssignData : otherLocalAssignData.mAssignedLocals)
  124. {
  125. if (otherLocalAssignData.mLocalVar == local.mLocalVar)
  126. {
  127. mAssignedLocals.Add(otherLocalAssignData);
  128. }
  129. }
  130. }
  131. if (wantRemove)
  132. {
  133. mAssignedLocals.RemoveAt(i);
  134. }
  135. else
  136. i++;
  137. }
  138. mHadFallthrough = mHadFallthrough && otherLocalAssignData.mHadFallthrough;
  139. }
  140. void BfDeferredLocalAssignData::Validate() const
  141. {
  142. for (auto var : mAssignedLocals)
  143. {
  144. BF_ASSERT((uintptr)var.mLocalVar->mName.length() < 100000);
  145. }
  146. }
  147. void BfDeferredLocalAssignData::SetUnion(const BfDeferredLocalAssignData& otherLocalAssignData)
  148. {
  149. BreakExtendChain();
  150. Validate();
  151. otherLocalAssignData.Validate();
  152. auto otherItr = otherLocalAssignData.mAssignedLocals.begin();
  153. while (otherItr != otherLocalAssignData.mAssignedLocals.end())
  154. {
  155. if (!mAssignedLocals.Contains(*otherItr))
  156. mAssignedLocals.push_back(*otherItr);
  157. ++otherItr;
  158. }
  159. mHadFallthrough = mHadFallthrough || otherLocalAssignData.mHadFallthrough;
  160. }
  161. BfMethodState::~BfMethodState()
  162. {
  163. BF_ASSERT(mPendingNullConditional == NULL);
  164. if (mPrevMethodState != NULL)
  165. {
  166. BF_ASSERT(mCurAccessId == 1);
  167. BF_ASSERT(mCurLocalVarId <= 0);
  168. }
  169. for (auto local : mLocals)
  170. delete local;
  171. for (auto& kv : mLambdaCache)
  172. delete kv.mValue;
  173. }
  174. BfMethodState* BfMethodState::GetMethodStateForLocal(BfLocalVariable* localVar)
  175. {
  176. auto checkMethodState = this;
  177. while (checkMethodState != NULL)
  178. {
  179. if ((localVar->mLocalVarIdx < checkMethodState->mLocals.size()) &&
  180. (checkMethodState->mLocals[localVar->mLocalVarIdx] == localVar))
  181. return checkMethodState;
  182. checkMethodState = checkMethodState->mPrevMethodState;
  183. }
  184. BF_FATAL("Failed to find method state for localvar");
  185. return NULL;
  186. }
  187. void BfMethodState::LocalDefined(BfLocalVariable* localVar, int fieldIdx, BfLocalVarAssignKind assignKind, bool isFromDeferredAssignData)
  188. {
  189. auto localVarMethodState = GetMethodStateForLocal(localVar);
  190. if (localVarMethodState != this)
  191. {
  192. return;
  193. }
  194. //BF_ASSERT(localVarMethodState == this);
  195. // if (assignKind == BfLocalVarAssignKind_None)
  196. // assignKind = ((localVarMethodState->mLeftBlockCond) && ((mDeferredLocalAssignData != NULL) || isFromDeferredAssignData)) ? BfLocalVarAssignKind_Conditional : BfLocalVarAssignKind_Unconditional;
  197. //
  198. // //assignKind = BfLocalVarAssignKind_Unconditional;
  199. if (localVar->mAssignedKind == BfLocalVarAssignKind_None)
  200. {
  201. BfDeferredLocalAssignData* ifDeferredLocalAssignData = NULL;
  202. // 'a' is always defined, but 'b' isn't:
  203. // if (Check(out a) || Check(out b)) { } int z = a;
  204. auto deferredLocalAssignData = mDeferredLocalAssignData;
  205. if ((deferredLocalAssignData != NULL) &&
  206. (deferredLocalAssignData->mIsIfCondition) &&
  207. (!deferredLocalAssignData->mIfMayBeSkipped))
  208. {
  209. ifDeferredLocalAssignData = deferredLocalAssignData;
  210. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  211. }
  212. while ((deferredLocalAssignData != NULL) &&
  213. ((deferredLocalAssignData->mIsChained) || (deferredLocalAssignData->mIsUnconditional)))
  214. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  215. if (assignKind == BfLocalVarAssignKind_None)
  216. assignKind = ((deferredLocalAssignData != NULL) && (deferredLocalAssignData->mLeftBlock)) ? BfLocalVarAssignKind_Conditional : BfLocalVarAssignKind_Unconditional;
  217. if (localVar->mAssignedKind >= assignKind)
  218. {
  219. // Leave it alone
  220. }
  221. else if ((deferredLocalAssignData == NULL) || (localVar->mLocalVarId >= deferredLocalAssignData->mVarIdBarrier))
  222. {
  223. if (fieldIdx >= 0)
  224. {
  225. localVar->mUnassignedFieldFlags &= ~((int64)1 << fieldIdx);
  226. if (localVar->mUnassignedFieldFlags == 0)
  227. {
  228. if (localVar->mAssignedKind == BfLocalVarAssignKind_None)
  229. localVar->mAssignedKind = assignKind;
  230. }
  231. }
  232. else
  233. {
  234. localVar->mAssignedKind = assignKind;
  235. }
  236. }
  237. else
  238. {
  239. BF_ASSERT(deferredLocalAssignData->mVarIdBarrier != -1);
  240. BfAssignedLocal defineVal = {localVar, fieldIdx, assignKind};
  241. if (!deferredLocalAssignData->Contains(defineVal))
  242. deferredLocalAssignData->mAssignedLocals.push_back(defineVal);
  243. if (ifDeferredLocalAssignData != NULL)
  244. {
  245. if (!ifDeferredLocalAssignData->Contains(defineVal))
  246. ifDeferredLocalAssignData->mAssignedLocals.push_back(defineVal);
  247. }
  248. }
  249. }
  250. localVar->mWrittenToId = GetRootMethodState()->mCurAccessId++;
  251. }
  252. void BfMethodState::ApplyDeferredLocalAssignData(const BfDeferredLocalAssignData& deferredLocalAssignData)
  253. {
  254. BF_ASSERT(&deferredLocalAssignData != mDeferredLocalAssignData);
  255. for (auto& assignedLocal : deferredLocalAssignData.mAssignedLocals)
  256. {
  257. LocalDefined(assignedLocal.mLocalVar, assignedLocal.mLocalVarField, assignedLocal.mAssignKind, true);
  258. }
  259. }
  260. void BfMethodState::Reset()
  261. {
  262. mHeadScope.mDeferredCallEntries.DeleteAll();
  263. }
  264. //////////////////////////////////////////////////////////////////////////
  265. void BfAmbiguityContext::Add(int id, BfTypeInterfaceEntry* interfaceEntry, int methodIdx, BfMethodInstance* candidateA, BfMethodInstance* candidateB)
  266. {
  267. Entry* entry = NULL;
  268. if (mEntries.TryAdd(id, NULL, &entry))
  269. {
  270. entry->mInterfaceEntry = interfaceEntry;
  271. entry->mMethodIdx = methodIdx;
  272. }
  273. if (!entry->mCandidates.Contains(candidateA))
  274. entry->mCandidates.push_back(candidateA);
  275. if (!entry->mCandidates.Contains(candidateB))
  276. entry->mCandidates.push_back(candidateB);
  277. }
  278. void BfAmbiguityContext::Remove(int id)
  279. {
  280. mEntries.Remove(id);
  281. }
  282. void BfAmbiguityContext::Finish()
  283. {
  284. for (auto& entryPair : mEntries)
  285. {
  286. int id = entryPair.mKey;
  287. auto entry = &entryPair.mValue;
  288. if (id >= 0)
  289. {
  290. auto declMethodInstance = mTypeInstance->mVirtualMethodTable[id].mDeclaringMethod;
  291. auto error = mModule->Fail(StrFormat("Method '%s' has ambiguous overrides", mModule->MethodToString(declMethodInstance).c_str()), declMethodInstance->mMethodDef->GetRefNode());
  292. for (auto candidate : entry->mCandidates)
  293. {
  294. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", mModule->MethodToString(candidate).c_str()), candidate->mMethodDef->GetRefNode());
  295. }
  296. }
  297. else
  298. {
  299. auto iMethodInst = entry->mInterfaceEntry->mInterfaceType->mMethodInstanceGroups[entry->mMethodIdx].mDefault;
  300. auto error = mModule->Fail(StrFormat("Interface method '%s' has ambiguous implementations", mModule->MethodToString(iMethodInst).c_str()), entry->mInterfaceEntry->mDeclaringType->GetRefNode());
  301. for (auto candidate : entry->mCandidates)
  302. {
  303. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", mModule->MethodToString(candidate).c_str()), candidate->mMethodDef->GetRefNode());
  304. }
  305. }
  306. }
  307. }
  308. //////////////////////////////////////////////////////////////////////////
  309. class HasAppendAllocVisitor : BfElementVisitor
  310. {
  311. public:
  312. bool mHas;
  313. public:
  314. HasAppendAllocVisitor()
  315. {
  316. mHas = false;
  317. }
  318. void Visit(BfObjectCreateExpression* objCreateExpr)
  319. {
  320. if (auto newToken = BfNodeDynCast<BfTokenNode>(objCreateExpr->mNewNode))
  321. {
  322. if (newToken->GetToken() == BfToken_Append)
  323. {
  324. mHas = true;
  325. }
  326. }
  327. }
  328. bool HasAppendAlloc(BfAstNode* node)
  329. {
  330. mHas = false;
  331. VisitChild(node);
  332. return mHas;
  333. }
  334. };
  335. class AppendAllocVisitor : public BfStructuralVisitor
  336. {
  337. public:
  338. BfModule* mModule;
  339. HasAppendAllocVisitor mHasAppendAllocVisitor;
  340. BfTypedValue mConstAccum;
  341. bool mFailed;
  342. bool mIsFirstConstPass;
  343. int mCurAppendAlign;
  344. public:
  345. AppendAllocVisitor()
  346. {
  347. mFailed = false;
  348. mIsFirstConstPass = false;
  349. mCurAppendAlign = 0;
  350. }
  351. void EmitAppendAlign(int align, int sizeMultiple = 0)
  352. {
  353. if (mIsFirstConstPass)
  354. mModule->mCurMethodInstance->mAppendAllocAlign = BF_MAX((int)mModule->mCurMethodInstance->mAppendAllocAlign, align);
  355. if (sizeMultiple == 0)
  356. sizeMultiple = align;
  357. if (mCurAppendAlign == 0)
  358. mCurAppendAlign = sizeMultiple;
  359. else
  360. {
  361. if (sizeMultiple % align == 0)
  362. mCurAppendAlign = align;
  363. else
  364. mCurAppendAlign = sizeMultiple % align;
  365. }
  366. if (mConstAccum)
  367. {
  368. auto constant = mModule->mBfIRBuilder->GetConstant(mConstAccum.mValue);
  369. if (constant != NULL)
  370. mConstAccum.mValue = mModule->GetConstValue(BF_ALIGN(constant->mInt64, align));
  371. else
  372. BF_ASSERT(mIsFirstConstPass);
  373. return;
  374. }
  375. mModule->EmitAppendAlign(align, sizeMultiple);
  376. }
  377. void Visit(BfAstNode* astNode) override
  378. {
  379. mModule->VisitChild(astNode);
  380. }
  381. void DoObjectCreate(BfObjectCreateExpression* objCreateExpr, BfVariableDeclaration* variableDecl)
  382. {
  383. if (auto newToken = BfNodeDynCast<BfTokenNode>(objCreateExpr->mNewNode))
  384. {
  385. if (newToken->GetToken() == BfToken_Append)
  386. {
  387. //auto variableDecl = BfNodeDynCast<BfVariableDeclaration>(objCreateExpr->mParent);
  388. auto accumValuePtr = mModule->mCurMethodState->mRetVal.mValue;
  389. auto intPtrType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  390. BfArrayType* arrayType = NULL;
  391. bool isArrayAlloc = false;
  392. bool isRawArrayAlloc = objCreateExpr->mStarToken != NULL;
  393. SizedArray<BfIRValue, 2> dimLengthVals;
  394. BfType* origResolvedTypeRef = NULL;
  395. if (auto dotTypeRef = BfNodeDynCast<BfDotTypeReference>(objCreateExpr->mTypeRef))
  396. {
  397. if (variableDecl != NULL)
  398. {
  399. origResolvedTypeRef = mModule->ResolveTypeRef(variableDecl->mTypeRef, BfPopulateType_Data, BfResolveTypeRefFlag_NoResolveGenericParam);
  400. if (origResolvedTypeRef->IsObject())
  401. {
  402. if (origResolvedTypeRef->IsArray())
  403. {
  404. arrayType = (BfArrayType*)origResolvedTypeRef;
  405. origResolvedTypeRef = origResolvedTypeRef->GetUnderlyingType();
  406. isArrayAlloc = true;
  407. }
  408. }
  409. else if (origResolvedTypeRef->IsPointer())
  410. {
  411. origResolvedTypeRef = origResolvedTypeRef->GetUnderlyingType();
  412. }
  413. }
  414. }
  415. else if (auto arrayTypeRef = BfNodeDynCast<BfArrayTypeRef>(objCreateExpr->mTypeRef))
  416. {
  417. isArrayAlloc = true;
  418. origResolvedTypeRef = mModule->ResolveTypeRef(arrayTypeRef->mElementType);
  419. int dimensions = 1;
  420. if (arrayTypeRef->mParams.size() != 0)
  421. {
  422. auto intType = mModule->ResolveTypeDef(mModule->mSystem->mTypeIntPtr);
  423. for (auto arg : arrayTypeRef->mParams)
  424. {
  425. if (auto tokenNode = BfNodeDynCastExact<BfTokenNode>(arg))
  426. {
  427. if (tokenNode->GetToken() == BfToken_Comma)
  428. {
  429. if (isRawArrayAlloc)
  430. {
  431. mModule->Fail("Sized arrays cannot be multidimensional", tokenNode);
  432. continue;
  433. }
  434. dimensions++;
  435. continue;
  436. }
  437. }
  438. auto expr = BfNodeDynCast<BfExpression>(arg);
  439. if ((isRawArrayAlloc) && (!dimLengthVals.IsEmpty()))
  440. {
  441. mModule->CreateValueFromExpression(expr, intType);
  442. continue;
  443. }
  444. BfTypedValue dimLength;
  445. if (expr == NULL)
  446. {
  447. // Not specified
  448. dimLengthVals.push_back(BfIRValue());
  449. continue;
  450. }
  451. if (arg != NULL)
  452. dimLength = mModule->CreateValueFromExpression(expr, intType);
  453. if (!dimLength)
  454. {
  455. dimLength = mModule->GetDefaultTypedValue(intType);
  456. }
  457. dimLengthVals.push_back(dimLength.mValue);
  458. }
  459. }
  460. if (!isRawArrayAlloc)
  461. arrayType = mModule->CreateArrayType(origResolvedTypeRef, dimensions);
  462. }
  463. if (origResolvedTypeRef == NULL)
  464. origResolvedTypeRef = mModule->ResolveTypeRef(objCreateExpr->mTypeRef, BfPopulateType_Data, BfResolveTypeRefFlag_NoResolveGenericParam);
  465. if (origResolvedTypeRef == NULL)
  466. {
  467. mModule->AssertErrorState();
  468. return;
  469. }
  470. bool isGenericParam = origResolvedTypeRef->IsGenericParam();
  471. auto resolvedTypeRef = origResolvedTypeRef;
  472. auto resultType = resolvedTypeRef;
  473. BfIRValue sizeValue;
  474. int curAlign = 0;
  475. if (isArrayAlloc)
  476. {
  477. int dimensions = 1;
  478. if (arrayType != NULL)
  479. dimensions = arrayType->mDimensions;
  480. bool sizeFailed = false;
  481. //
  482. {
  483. BfAstNode* initNode = objCreateExpr;
  484. for (int dim = 0; dim < dimensions; dim++)
  485. {
  486. BfAstNode* nextInitNode = NULL;
  487. int dimSize = -1;
  488. if (initNode == objCreateExpr)
  489. {
  490. dimSize = objCreateExpr->mArguments.size();
  491. if (!objCreateExpr->mArguments.IsEmpty())
  492. nextInitNode = objCreateExpr->mArguments[0];
  493. }
  494. else if (auto tupleNode = BfNodeDynCast<BfTupleExpression>(initNode))
  495. {
  496. dimSize = (int)tupleNode->mCommas.size() + 1;
  497. }
  498. if (dimSize >= 0)
  499. {
  500. if (dim >= dimLengthVals.size())
  501. dimLengthVals.Add(mModule->GetConstValue(dimSize));
  502. }
  503. else
  504. {
  505. sizeFailed = true;
  506. }
  507. }
  508. }
  509. BfIRValue allocCount;
  510. if (!sizeFailed)
  511. {
  512. if (!dimLengthVals.IsEmpty())
  513. {
  514. allocCount = dimLengthVals[0];
  515. for (int dim = 1; dim < (int)dimLengthVals.size(); dim++)
  516. allocCount = mModule->mBfIRBuilder->CreateMul(allocCount, dimLengthVals[dim]);
  517. }
  518. }
  519. if (!allocCount)
  520. {
  521. mFailed = true;
  522. if (!mIsFirstConstPass)
  523. {
  524. if (!mConstAccum)
  525. mModule->Fail("Unable to determine append alloc size", objCreateExpr->mNewNode);
  526. return;
  527. }
  528. }
  529. if (isRawArrayAlloc)
  530. {
  531. curAlign = resultType->mAlign;
  532. EmitAppendAlign(resultType->mAlign);
  533. sizeValue = mModule->mBfIRBuilder->CreateMul(mModule->GetConstValue(resultType->mSize), allocCount);
  534. }
  535. else
  536. {
  537. if (arrayType == NULL)
  538. arrayType = mModule->CreateArrayType(resultType, 1);
  539. // Array is a special case where the total size isn't aligned with mAlign
  540. // since we add arbitrary elements to the end without padding the end to align
  541. EmitAppendAlign(arrayType->mAlign, resultType->mAlign);
  542. curAlign = arrayType->mAlign;
  543. auto firstElementField = &arrayType->mFieldInstances.back();
  544. int arrayClassSize = arrayType->mInstSize - firstElementField->mDataSize;
  545. sizeValue = mModule->GetConstValue(arrayClassSize);
  546. BfIRValue elementDataSize = mModule->mBfIRBuilder->CreateMul(mModule->GetConstValue(resultType->mSize), allocCount);
  547. sizeValue = mModule->mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  548. }
  549. }
  550. else
  551. {
  552. auto typeInst = resultType->ToTypeInstance();
  553. if (typeInst != NULL)
  554. {
  555. curAlign = typeInst->mInstAlign;
  556. EmitAppendAlign(typeInst->mInstAlign, typeInst->mInstSize);
  557. sizeValue = mModule->GetConstValue(typeInst->mInstSize);
  558. }
  559. else
  560. {
  561. curAlign = resultType->mAlign;
  562. EmitAppendAlign(resultType->mAlign, resultType->mSize);
  563. sizeValue = mModule->GetConstValue(resultType->mSize);
  564. }
  565. BfTypedValue emtpyThis(mModule->mBfIRBuilder->GetFakeVal(), resultType, (typeInst == NULL) || (typeInst->IsComposite()));
  566. BfExprEvaluator exprEvaluator(mModule);
  567. SetAndRestoreValue<bool> prevNoBind(exprEvaluator.mNoBind, exprEvaluator.mNoBind || isGenericParam);
  568. BfFunctionBindResult bindResult;
  569. bindResult.mWantsArgs = true;
  570. exprEvaluator.mFunctionBindResult = &bindResult;
  571. SizedArray<BfExpression*, 8> copiedArgs;
  572. for (BfExpression* arg : objCreateExpr->mArguments)
  573. copiedArgs.push_back(arg);
  574. BfSizedArray<BfExpression*> sizedArgExprs(copiedArgs);
  575. BfResolvedArgs argValues(&sizedArgExprs);
  576. if (typeInst != NULL)
  577. {
  578. exprEvaluator.ResolveArgValues(argValues);
  579. exprEvaluator.MatchConstructor(objCreateExpr->mTypeRef, objCreateExpr, emtpyThis, typeInst, argValues, false, true);
  580. }
  581. exprEvaluator.mFunctionBindResult = NULL;
  582. if (bindResult.mMethodInstance != NULL)
  583. {
  584. if (bindResult.mMethodInstance->mMethodDef->mHasAppend)
  585. {
  586. auto calcAppendArgs = bindResult.mIRArgs;
  587. BF_ASSERT(calcAppendArgs[0].IsFake());
  588. calcAppendArgs.RemoveRange(0, 2); // Remove 'this' and 'appendIdx'
  589. auto calcAppendMethodModule = mModule->GetMethodInstanceAtIdx(bindResult.mMethodInstance->GetOwner(), bindResult.mMethodInstance->mMethodDef->mIdx + 1, BF_METHODNAME_CALCAPPEND);
  590. auto subDependSize = mModule->TryConstCalcAppend(bindResult.mMethodInstance, calcAppendArgs);
  591. if (calcAppendMethodModule.mMethodInstance->mAppendAllocAlign > 0)
  592. {
  593. EmitAppendAlign(calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  594. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign > -1);
  595. mModule->mCurMethodState->mCurAppendAlign = BF_MAX(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign, 0);
  596. }
  597. curAlign = std::max(curAlign, (int)calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  598. if ((!subDependSize) && (!mConstAccum))
  599. {
  600. BF_ASSERT(calcAppendMethodModule.mFunc);
  601. subDependSize = exprEvaluator.CreateCall(calcAppendMethodModule.mMethodInstance, calcAppendMethodModule.mFunc, false, calcAppendArgs);
  602. BF_ASSERT(subDependSize.mType == mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  603. }
  604. if (subDependSize)
  605. sizeValue = mModule->mBfIRBuilder->CreateAdd(sizeValue, subDependSize.mValue);
  606. else
  607. mFailed = true;
  608. }
  609. }
  610. }
  611. if (sizeValue)
  612. {
  613. if (mConstAccum)
  614. {
  615. if (!sizeValue.IsConst())
  616. {
  617. mFailed = true;
  618. if (!mIsFirstConstPass)
  619. return;
  620. }
  621. mConstAccum.mValue = mModule->mBfIRBuilder->CreateAdd(sizeValue, mConstAccum.mValue);
  622. }
  623. else
  624. {
  625. auto prevVal = mModule->mBfIRBuilder->CreateLoad(accumValuePtr);
  626. auto addedVal = mModule->mBfIRBuilder->CreateAdd(sizeValue, prevVal);
  627. mModule->mBfIRBuilder->CreateStore(addedVal, accumValuePtr);
  628. }
  629. }
  630. }
  631. }
  632. }
  633. void Visit(BfObjectCreateExpression* objCreateExpr) override
  634. {
  635. DoObjectCreate(objCreateExpr, NULL);
  636. }
  637. void Visit(BfVariableDeclaration* varDecl) override
  638. {
  639. if (mHasAppendAllocVisitor.HasAppendAlloc(varDecl))
  640. {
  641. if (auto objectCreateExpr = BfNodeDynCast<BfObjectCreateExpression>(varDecl->mInitializer))
  642. DoObjectCreate(objectCreateExpr, varDecl);
  643. else
  644. VisitChild(varDecl->mInitializer);
  645. if (varDecl->mNameNode != NULL)
  646. {
  647. BfLocalVariable* localDef = new BfLocalVariable();
  648. localDef->mName = varDecl->mNameNode->ToString();
  649. localDef->mNameNode = BfNodeDynCast<BfIdentifierNode>(varDecl->mNameNode);
  650. localDef->mResolvedType = mModule->GetPrimitiveType(BfTypeCode_None);
  651. localDef->mIsReadOnly = true;
  652. localDef->mParamFailed = true;
  653. localDef->mReadFromId = 0;
  654. mModule->AddLocalVariableDef(localDef);
  655. }
  656. }
  657. else
  658. {
  659. mModule->Visit(varDecl);
  660. }
  661. }
  662. void Visit(BfExpressionStatement* exprStatement) override
  663. {
  664. VisitChild(exprStatement->mExpression);
  665. }
  666. // void Visit(BfIfStatement* ifStmt) override
  667. // {
  668. // mModule->DoIfStatement(ifStmt,
  669. // mHasAppendAllocVisitor.HasAppendAlloc(ifStmt->mTrueStatement),
  670. // mHasAppendAllocVisitor.HasAppendAlloc(ifStmt->mFalseStatement));
  671. // }
  672. void Visit(BfBlock* block) override
  673. {
  674. if (!mHasAppendAllocVisitor.HasAppendAlloc(block))
  675. return;
  676. int appendAllocIdx = -1;
  677. for (int childIdx = block->mChildArr.mSize - 1; childIdx >= 0; childIdx--)
  678. {
  679. auto child = block->mChildArr.mVals[childIdx];
  680. if (mHasAppendAllocVisitor.HasAppendAlloc(child))
  681. {
  682. for (int emitIdx = 0; emitIdx <= childIdx; emitIdx++)
  683. {
  684. auto emitChild = block->mChildArr.mVals[emitIdx];
  685. mModule->UpdateSrcPos(emitChild);
  686. VisitChild(emitChild);
  687. if ((mFailed) && (!mIsFirstConstPass))
  688. break;
  689. }
  690. break;
  691. }
  692. }
  693. }
  694. };
  695. //////////////////////////////////////////////////////////////////////////
  696. BfModule* gLastCreatedModule = NULL;
  697. BfModule::BfModule(BfContext* context, const StringImpl& moduleName)
  698. {
  699. BfLogSys(context->mSystem, "BfModule::BFModule %p %s\n", this, moduleName.c_str());
  700. gLastCreatedModule = this;
  701. mContext = context;
  702. mModuleName = moduleName;
  703. if (!moduleName.empty())
  704. mContext->mUsedModuleNames.Add(ToUpper(moduleName));
  705. mAddedToCount = false;
  706. mParentModule = NULL;
  707. mNextAltModule = NULL;
  708. mBfIRBuilder = NULL;
  709. mWantsIRIgnoreWrites = false;
  710. mModuleOptions = NULL;
  711. mLastUsedRevision = -1;
  712. mUsedSlotCount = -1;
  713. mIsReified = true;
  714. mReifyQueued = false;
  715. mIsSpecialModule = false;
  716. mIsScratchModule = false;
  717. mIsSpecializedMethodModuleRoot = false; // There may be mNextAltModules extending from this
  718. mHadBuildError = false;
  719. mHadBuildWarning = false;
  720. mIgnoreErrors = false;
  721. mIgnoreWarnings = false;
  722. mReportErrors = true;
  723. mIsInsideAutoComplete = false;
  724. mIsDeleting = false;
  725. mSkipInnerLookup = false;
  726. mIsHotModule = false;
  727. mSetIllegalSrcPosition = false;
  728. mNoResolveGenericParams = false;
  729. mWroteToLib = false;
  730. mContext = context;
  731. mCompiler = context->mCompiler;
  732. mSystem = mCompiler->mSystem;
  733. mProject = NULL;
  734. mCurMethodState = NULL;
  735. mAttributeState = NULL;
  736. mCurLocalMethodId = 0;
  737. mParentNodeEntry = NULL;
  738. mRevision = -1;
  739. mRebuildIdx = 0;
  740. mLastModuleWrittenRevision = 0;
  741. mIsModuleMutable = false;
  742. mExtensionCount = 0;
  743. mIncompleteMethodCount = 0;
  744. mOnDemandMethodCount = 0;
  745. mHasGenericMethods = false;
  746. mCurMethodInstance = NULL;
  747. mCurTypeInstance = NULL;
  748. mAwaitingInitFinish = false;
  749. mAwaitingFinish = false;
  750. mHasFullDebugInfo = false;
  751. mHadHotObjectWrites = false;
  752. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  753. mBuiltInFuncs[i] = BfIRFunction();
  754. BfLogSysM("Creating module %p: %s Reified: %d ResolveOnly: %d\n", this, mModuleName.c_str(), mIsReified, mCompiler->mIsResolveOnly);
  755. }
  756. void BfReportMemory();
  757. BfModule::~BfModule()
  758. {
  759. BfLogSysM("Deleting module %p: %s \n", this, mModuleName.c_str());
  760. if (!mIsDeleting)
  761. RemoveModuleData();
  762. }
  763. void BfModule::RemoveModuleData()
  764. {
  765. BF_ASSERT(!mIsDeleting);
  766. if (!mModuleName.empty())
  767. {
  768. // Note: module names not necessarily unique
  769. mContext->mUsedModuleNames.Remove(ToUpper(mModuleName));
  770. }
  771. CleanupFileInstances();
  772. delete mBfIRBuilder;
  773. mBfIRBuilder = NULL;
  774. //delete mCpu;
  775. for (auto prevModule : mPrevIRBuilders)
  776. delete prevModule;
  777. mPrevIRBuilders.Clear();
  778. for (auto& pairVal : mDeferredMethodCallData)
  779. delete pairVal.mValue;
  780. mDeferredMethodCallData.Clear();
  781. mDeferredMethodIds.Clear();
  782. for (auto& specModulePair : mSpecializedMethodModules)
  783. delete specModulePair.mValue;
  784. mSpecializedMethodModules.Clear();
  785. if (mNextAltModule != NULL)
  786. delete mNextAltModule;
  787. mNextAltModule = NULL;
  788. if (mModuleOptions != NULL)
  789. delete mModuleOptions;
  790. mModuleOptions = NULL;
  791. BfReportMemory();
  792. }
  793. void BfModule::Init(bool isFullRebuild)
  794. {
  795. mContext->mFinishedModuleWorkList.Remove(this);
  796. if ((mCompiler->mIsResolveOnly) && (this != mContext->mUnreifiedModule))
  797. BF_ASSERT(mIsReified);
  798. if (!mIsScratchModule)
  799. {
  800. mCompiler->mStats.mModulesStarted++;
  801. if (mIsReified)
  802. mCompiler->mStats.mReifiedModuleCount++;
  803. mAddedToCount = true;
  804. }
  805. mIsHotModule = (mProject != NULL) && (mCompiler->mOptions.mHotProject != NULL) && (mCompiler->mOptions.mHotProject->ContainsReference(mProject));
  806. mFuncReferences.Clear();
  807. mClassVDataRefs.Clear();
  808. mClassVDataExtRefs.Clear();
  809. //mTypeDataRefs.Clear();
  810. mDbgRawAllocDataRefs.Clear();
  811. CleanupFileInstances();
  812. mStaticFieldRefs.Clear();
  813. //mInterfaceSlotRefs.Clear();
  814. // If we are just doing an extension then the ownede types aren't rebuilt.
  815. // If we set mRevision then QueueMethodSpecializations wouldn't actually queue up required specializations
  816. // and we'd end up with link errors if the original module uniquely referred to any generic methods
  817. if (isFullRebuild)
  818. mRevision = mCompiler->mRevision;
  819. BF_ASSERT(mCurTypeInstance == NULL);
  820. mIsModuleMutable = true;
  821. BF_ASSERT((mBfIRBuilder == NULL) || (mCompiler->mIsResolveOnly));
  822. #ifdef _DEBUG
  823. EnsureIRBuilder(mCompiler->mLastAutocompleteModule == this);
  824. #else
  825. EnsureIRBuilder(false);
  826. #endif
  827. mCurMethodState = NULL;
  828. mAwaitingInitFinish = true;
  829. mOnDemandMethodCount = 0;
  830. mAwaitingFinish = false;
  831. mHasForceLinkMarker = false;
  832. mUsedSlotCount = -1;
  833. }
  834. bool BfModule::WantsFinishModule()
  835. {
  836. return (mIncompleteMethodCount == 0) && (mOnDemandMethodCount == 0) && (!mHasGenericMethods) && (!mIsScratchModule) && (mExtensionCount == 0) && (mParentModule == NULL);
  837. }
  838. void BfModule::FinishInit()
  839. {
  840. BF_ASSERT(mAwaitingInitFinish);
  841. auto moduleOptions = GetModuleOptions();
  842. mBfIRBuilder->Start(mModuleName, mCompiler->mSystem->mPtrSize, IsOptimized());
  843. mBfIRBuilder->Module_SetTargetTriple(mCompiler->mOptions.mTargetTriple);
  844. mBfIRBuilder->SetBackend(IsTargetingBeefBackend());
  845. if (moduleOptions.mOptLevel == BfOptLevel_OgPlus)
  846. {
  847. // Og+ requires debug info
  848. moduleOptions.mEmitDebugInfo = 1;
  849. }
  850. mHasFullDebugInfo = moduleOptions.mEmitDebugInfo == 1;
  851. if ((!mCompiler->mIsResolveOnly) && (!mIsScratchModule) && (moduleOptions.mEmitDebugInfo != 0) && (mIsReified))
  852. {
  853. mBfIRBuilder->DbgInit();
  854. }
  855. else
  856. mHasFullDebugInfo = false;
  857. if ((mBfIRBuilder->DbgHasInfo()) && (mModuleName != "") &&
  858. ((moduleOptions.mEmitDebugInfo != 0)))
  859. {
  860. if (mCompiler->mOptions.IsCodeView())
  861. {
  862. mBfIRBuilder->Module_AddModuleFlag("CodeView", 1);
  863. }
  864. else
  865. {
  866. mBfIRBuilder->Module_AddModuleFlag("Dwarf Version", 4);
  867. }
  868. mBfIRBuilder->Module_AddModuleFlag("Debug Info Version", 3);
  869. mDICompileUnit = mBfIRBuilder->DbgCreateCompileUnit(llvm::dwarf::DW_LANG_C_plus_plus, mModuleName, ".", "Beef Compiler 0.42.3", /*moduleOptions.mOptLevel > 0*/false, "", 0, !mHasFullDebugInfo);
  870. }
  871. mAwaitingInitFinish = false;
  872. }
  873. void BfModule::ReifyModule()
  874. {
  875. BF_ASSERT((mCompiler->mCompileState != BfCompiler::CompileState_Unreified) && (mCompiler->mCompileState != BfCompiler::CompileState_VData));
  876. BfLogSysM("ReifyModule %@ %s\n", this, mModuleName.c_str());
  877. BF_ASSERT((this != mContext->mScratchModule) && (this != mContext->mUnreifiedModule));
  878. mIsReified = true;
  879. mReifyQueued = false;
  880. StartNewRevision(RebuildKind_SkipOnDemandTypes, true);
  881. mCompiler->mStats.mModulesReified++;
  882. }
  883. void BfModule::UnreifyModule()
  884. {
  885. BfLogSysM("UnreifyModule %p %s\n", this, mModuleName.c_str());
  886. BF_ASSERT((this != mContext->mScratchModule) && (this != mContext->mUnreifiedModule));
  887. mIsReified = false;
  888. mReifyQueued = false;
  889. StartNewRevision(RebuildKind_None, true);
  890. mCompiler->mStats.mModulesUnreified++;
  891. }
  892. void BfModule::CleanupFileInstances()
  893. {
  894. for (auto& itr : mNamedFileInstanceMap)
  895. {
  896. BfLogSysM("FileInstance deleted: %p\n", itr.mValue);
  897. delete itr.mValue;
  898. }
  899. mCurFilePosition.mFileInstance = NULL;//
  900. mFileInstanceMap.Clear();
  901. mNamedFileInstanceMap.Clear();
  902. }
  903. void BfModule::Cleanup()
  904. {
  905. CleanupFileInstances();
  906. }
  907. void BfModule::PrepareForIRWriting(BfTypeInstance* typeInst)
  908. {
  909. if (HasCompiledOutput())
  910. {
  911. // It's possible that the target's code hasn't changed but we're requesting a new generic method specialization
  912. if ((!mIsModuleMutable) && (!typeInst->IsUnspecializedType()) && (!typeInst->mResolvingVarField))
  913. {
  914. StartExtension();
  915. }
  916. }
  917. else
  918. {
  919. EnsureIRBuilder();
  920. }
  921. }
  922. void BfModule::EnsureIRBuilder(bool dbgVerifyCodeGen)
  923. {
  924. BF_ASSERT(!mIsDeleting);
  925. if (mBfIRBuilder == NULL)
  926. {
  927. if ((!mIsScratchModule) && (!mAddedToCount))
  928. {
  929. mCompiler->mStats.mModulesStarted++;
  930. mAddedToCount = true;
  931. }
  932. BF_ASSERT(mStaticFieldRefs.GetCount() == 0);
  933. /*if (mCompiler->mIsResolveOnly)
  934. BF_ASSERT(mIsResolveOnly);*/
  935. mBfIRBuilder = new BfIRBuilder(this);
  936. BfLogSysM("Created mBfIRBuilder %p in %p %s Reified: %d\n", mBfIRBuilder, this, mModuleName.c_str(), mIsReified);
  937. if (mIsScratchModule)
  938. {
  939. mBfIRBuilder->mIgnoreWrites = true;
  940. BF_ASSERT(!dbgVerifyCodeGen);
  941. }
  942. #ifdef _DEBUG
  943. if (mCompiler->mIsResolveOnly)
  944. {
  945. // For "deep" verification testing
  946. /*if (!mIsSpecialModule)
  947. dbgVerifyCodeGen = true;*/
  948. // We only want to turn this off on smaller builds for testing
  949. mBfIRBuilder->mIgnoreWrites = true;
  950. if (dbgVerifyCodeGen)
  951. mBfIRBuilder->mIgnoreWrites = false;
  952. if (!mBfIRBuilder->mIgnoreWrites)
  953. {
  954. // The only purpose of not ignoring writes is so we can verify the codegen one instruction at a time
  955. mBfIRBuilder->mDbgVerifyCodeGen = true;
  956. }
  957. }
  958. else if (!mIsReified)
  959. {
  960. mBfIRBuilder->mIgnoreWrites = true;
  961. }
  962. else
  963. {
  964. // We almost always want this to be 'false' unless we need need to be able to inspect the generated LLVM
  965. // code as we walk the AST
  966. //mBfIRBuilder->mDbgVerifyCodeGen = true;
  967. if (
  968. (mModuleName == "-")
  969. //|| (mModuleName == "BeefTest2_ClearColorValue")
  970. //|| (mModuleName == "Tests_FuncRefs")
  971. )
  972. mBfIRBuilder->mDbgVerifyCodeGen = true;
  973. // Just for testing!
  974. //mBfIRBuilder->mIgnoreWrites = true;
  975. }
  976. #else
  977. if (mCompiler->mIsResolveOnly)
  978. {
  979. // Always ignore writes in resolveOnly for release builds
  980. mBfIRBuilder->mIgnoreWrites = true;
  981. }
  982. else
  983. {
  984. // Just for memory testing! This breaks everything.
  985. //mBfIRBuilder->mIgnoreWrites = true;
  986. // For "deep" verification testing
  987. //mBfIRBuilder->mDbgVerifyCodeGen = true;
  988. }
  989. #endif
  990. mWantsIRIgnoreWrites = mBfIRBuilder->mIgnoreWrites;
  991. }
  992. }
  993. BfIRValue BfModule::CreateForceLinkMarker(BfModule* module, String* outName)
  994. {
  995. String name = "FORCELINKMOD_" + module->mModuleName;
  996. if (outName != NULL)
  997. *outName = name;
  998. auto markerType = GetPrimitiveType(BfTypeCode_Int8);
  999. return mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(markerType), true, BfIRLinkageType_External, (module == this) ? mBfIRBuilder->CreateConst(BfTypeCode_Int8, 0) : BfIRValue(), name);
  1000. }
  1001. void BfModule::StartNewRevision(RebuildKind rebuildKind, bool force)
  1002. {
  1003. BP_ZONE("BfModule::StartNewRevision");
  1004. // The project MAY be deleted because disabling a project can cause types to be deleted which
  1005. // causes other types rebuild BEFORE they get deleted, which is okay (though wasteful)
  1006. //BF_ASSERT((mProject == NULL) || (!mProject->mDisabled));
  1007. // Already on new revision?
  1008. if ((mRevision == mCompiler->mRevision) && (!force))
  1009. return;
  1010. mHadBuildError = false;
  1011. mHadBuildWarning = false;
  1012. mExtensionCount = 0;
  1013. mRevision = mCompiler->mRevision;
  1014. mRebuildIdx++;
  1015. ClearModuleData();
  1016. // Clear this here, not in ClearModuleData, so we preserve those references even after writing out module
  1017. if (rebuildKind != BfModule::RebuildKind_None) // Leave string pool refs for when we need to use things like [LinkName("")] methods bofore re-reification
  1018. mStringPoolRefs.Clear();
  1019. mDllImportEntries.Clear();
  1020. mImportFileNames.Clear();
  1021. for (auto& pairVal : mDeferredMethodCallData)
  1022. delete pairVal.mValue;
  1023. mDeferredMethodCallData.Clear();
  1024. mDeferredMethodIds.Clear();
  1025. mModuleRefs.Clear();
  1026. mOutFileNames.Clear();
  1027. mTypeDataRefs.Clear();
  1028. mInterfaceSlotRefs.Clear();
  1029. if (rebuildKind == BfModule::RebuildKind_None)
  1030. {
  1031. for (auto& specPair : mSpecializedMethodModules)
  1032. {
  1033. auto specModule = specPair.mValue;
  1034. if (specModule->mIsReified != mIsReified)
  1035. {
  1036. if (mIsReified)
  1037. specModule->ReifyModule();
  1038. else
  1039. specModule->UnreifyModule();
  1040. }
  1041. }
  1042. }
  1043. else
  1044. {
  1045. for (auto& specPair : mSpecializedMethodModules)
  1046. {
  1047. auto specModule = specPair.mValue;
  1048. delete specModule;
  1049. }
  1050. }
  1051. mSpecializedMethodModules.Clear();
  1052. delete mNextAltModule;
  1053. mNextAltModule = NULL;
  1054. BF_ASSERT(mModuleOptions == NULL);
  1055. BfLogSysM("Mod:%p StartNewRevision: %s Revision: %d\n", this, mModuleName.c_str(), mRevision);
  1056. bool needsTypePopulated = false;
  1057. int oldOnDemandCount = 0;
  1058. // We don't have to rebuild types in the unspecialized module because there is no
  1059. // data that's needed -- their method instances are all NULL and the module
  1060. // doesn't get included in the build
  1061. if (this != mContext->mScratchModule)
  1062. {
  1063. for (int typeIdx = 0; typeIdx < (int)mOwnedTypeInstances.size(); typeIdx++)
  1064. {
  1065. auto typeInst = mOwnedTypeInstances[typeIdx];
  1066. if (!typeInst->IsDeleting())
  1067. {
  1068. typeInst->mIsReified = mIsReified;
  1069. if (rebuildKind != BfModule::RebuildKind_None)
  1070. {
  1071. if (typeInst->IsOnDemand())
  1072. {
  1073. // Changing config should require on demand types to be recreated, but reifying a module shouldn't cause the type to be deleted
  1074. if (rebuildKind == BfModule::RebuildKind_All)
  1075. mContext->DeleteType(typeInst);
  1076. else
  1077. {
  1078. RebuildMethods(typeInst);
  1079. }
  1080. }
  1081. else
  1082. //TODO: Why weren't we placing specialzied in purgatory here originally? This caused failed types to stick around too long
  1083. mContext->RebuildType(typeInst, false, false, true);
  1084. //mContext->RebuildType(typeInst, false, false, false);
  1085. }
  1086. else
  1087. {
  1088. auto _HandleMethod = [&](BfMethodInstance* methodInstance)
  1089. {
  1090. if ((methodInstance != NULL) && (methodInstance->mDeclModule != NULL))
  1091. methodInstance->mDeclModule = this;
  1092. };
  1093. for (auto& methodGroup : typeInst->mMethodInstanceGroups)
  1094. {
  1095. if ((methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) ||
  1096. (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference))
  1097. {
  1098. oldOnDemandCount++;
  1099. }
  1100. _HandleMethod(methodGroup.mDefault);
  1101. if (methodGroup.mMethodSpecializationMap != NULL)
  1102. for (auto& kv : *methodGroup.mMethodSpecializationMap)
  1103. _HandleMethod(kv.mValue);
  1104. }
  1105. }
  1106. if (typeInst->IsDeleting())
  1107. typeIdx--;
  1108. }
  1109. }
  1110. }
  1111. if (!mIsDeleting)
  1112. Init();
  1113. mOnDemandMethodCount += oldOnDemandCount;
  1114. }
  1115. void BfModule::StartExtension()
  1116. {
  1117. BF_ASSERT(!mIsModuleMutable);
  1118. BfLogSysM("Extension started of module %p\n", this);
  1119. mExtensionCount++;
  1120. if (mBfIRBuilder != NULL)
  1121. mPrevIRBuilders.push_back(mBfIRBuilder);
  1122. mBfIRBuilder = NULL;
  1123. mWantsIRIgnoreWrites = false;
  1124. mFuncReferences.Clear();
  1125. mClassVDataRefs.Clear();
  1126. mClassVDataExtRefs.Clear();
  1127. for (auto& kv : mTypeDataRefs)
  1128. kv.mValue = BfIRValue();
  1129. mDbgRawAllocDataRefs.Clear();
  1130. mStringCharPtrPool.Clear();
  1131. mStringObjectPool.Clear();
  1132. mStaticFieldRefs.Clear();
  1133. for (auto& kv : mInterfaceSlotRefs)
  1134. kv.mValue = BfIRValue();
  1135. mDeferredMethodCallData.Clear();
  1136. mDeferredMethodIds.Clear();
  1137. DisownMethods();
  1138. BfLogSysM("Mod:%p StartExtension: %s\n", this, mModuleName.c_str());
  1139. bool wasAwaitingInitFinish = mAwaitingInitFinish;
  1140. int prevOnDemandMethodCount = mOnDemandMethodCount;
  1141. Init(false);
  1142. if (!wasAwaitingInitFinish)
  1143. FinishInit();
  1144. mOnDemandMethodCount = prevOnDemandMethodCount;
  1145. }
  1146. void BfModule::GetConstClassValueParam(BfIRValue classVData, SizedArrayImpl<BfIRValue>& typeValueParams)
  1147. {
  1148. BfIRValue vDataValue;
  1149. if (mCompiler->mOptions.mObjectHasDebugFlags)
  1150. vDataValue = mBfIRBuilder->CreatePtrToInt(classVData, BfTypeCode_IntPtr);
  1151. else
  1152. vDataValue = mBfIRBuilder->CreateBitCast(classVData, mBfIRBuilder->MapType(mContext->mBfClassVDataPtrType));
  1153. typeValueParams.push_back(vDataValue);
  1154. if (mCompiler->mOptions.mObjectHasDebugFlags)
  1155. {
  1156. auto primType = GetPrimitiveType(BfTypeCode_IntPtr);
  1157. typeValueParams.push_back(GetDefaultValue(primType));
  1158. }
  1159. }
  1160. BfIRValue BfModule::GetConstValue(int64 val)
  1161. {
  1162. return mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)val);
  1163. }
  1164. BfIRValue BfModule::GetConstValue(int64 val, BfType* type)
  1165. {
  1166. BfType* checkType = type;
  1167. if (type->IsTypedPrimitive())
  1168. {
  1169. checkType = type->GetUnderlyingType();
  1170. }
  1171. if (checkType->IsPrimitiveType())
  1172. {
  1173. auto primType = (BfPrimitiveType*)checkType;
  1174. if (checkType->IsFloat())
  1175. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (double)val);
  1176. else
  1177. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (uint64)val);
  1178. }
  1179. return BfIRValue();
  1180. }
  1181. BfIRValue BfModule::GetConstValue8(int val)
  1182. {
  1183. return mBfIRBuilder->CreateConst(BfTypeCode_Int8, (uint64)val);
  1184. }
  1185. BfIRValue BfModule::GetConstValue32(int32 val)
  1186. {
  1187. return mBfIRBuilder->CreateConst(BfTypeCode_Int32, (uint64)val);
  1188. }
  1189. BfIRValue BfModule::GetConstValue64(int64 val)
  1190. {
  1191. return mBfIRBuilder->CreateConst(BfTypeCode_Int64, (uint64)val);
  1192. }
  1193. BfIRValue BfModule::GetDefaultValue(BfType* type)
  1194. {
  1195. PopulateType(type, BfPopulateType_Data);
  1196. mBfIRBuilder->PopulateType(type, BfIRPopulateType_Declaration);
  1197. if (type->IsTypedPrimitive())
  1198. {
  1199. auto underlyingType = type->GetUnderlyingType();
  1200. if (underlyingType == NULL)
  1201. return mBfIRBuilder->CreateConst(BfTypeCode_Int64, 0);
  1202. return GetDefaultValue(type->GetUnderlyingType());
  1203. }
  1204. if (type->IsPointer() || type->IsObjectOrInterface() || type->IsGenericParam() || type->IsVar() || type->IsRef() || type->IsNull() ||
  1205. type->IsModifiedTypeType() || type->IsConcreteInterfaceType())
  1206. return mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(type));
  1207. if ((type->IsIntegral()) || (type->IsBoolean()))
  1208. {
  1209. auto primType = (BfPrimitiveType*)type;
  1210. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (uint64)0);
  1211. }
  1212. if (type->IsFloat())
  1213. {
  1214. auto primType = (BfPrimitiveType*)type;
  1215. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, 0.0);
  1216. }
  1217. if (type->IsVoid())
  1218. return mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(type));
  1219. return mBfIRBuilder->CreateConstStructZero(mBfIRBuilder->MapType(type));
  1220. }
  1221. BfTypedValue BfModule::GetFakeTypedValue(BfType* type)
  1222. {
  1223. // This is a conservative "IsValueless", since it's not an error to use a fakeVal even if we don't need one
  1224. if (type->mSize == 0)
  1225. return BfTypedValue(BfIRValue::sValueless, type);
  1226. else
  1227. return BfTypedValue(mBfIRBuilder->GetFakeVal(), type);
  1228. }
  1229. BfTypedValue BfModule::GetDefaultTypedValue(BfType* type, bool allowRef, BfDefaultValueKind defaultValueKind)
  1230. {
  1231. if (type->IsVar())
  1232. return BfTypedValue(mBfIRBuilder->GetFakeVal(), type);
  1233. PopulateType(type, BfPopulateType_Data);
  1234. mBfIRBuilder->PopulateType(type, type->IsValueType() ? BfIRPopulateType_Full : BfIRPopulateType_Declaration);
  1235. if (defaultValueKind == BfDefaultValueKind_Undef)
  1236. {
  1237. auto primType = type->ToPrimitiveType();
  1238. if (primType != NULL)
  1239. {
  1240. return BfTypedValue(mBfIRBuilder->GetUndefConstValue(primType->mTypeDef->mTypeCode), type);
  1241. }
  1242. return BfTypedValue(mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(type)), type);
  1243. }
  1244. BfTypedValue typedValue;
  1245. if ((defaultValueKind != BfDefaultValueKind_Const) && (!type->IsValuelessType()))
  1246. {
  1247. if (type->IsRef())
  1248. {
  1249. BfRefType* refType = (BfRefType*)type;
  1250. BfType* underlyingType = refType->GetUnderlyingType();
  1251. typedValue = BfTypedValue(CreateAlloca(underlyingType), underlyingType, BfTypedValueKind_Addr);
  1252. }
  1253. else
  1254. {
  1255. typedValue = BfTypedValue(CreateAlloca(type), type, BfTypedValueKind_Addr);
  1256. }
  1257. if (!mBfIRBuilder->mIgnoreWrites)
  1258. {
  1259. mBfIRBuilder->CreateMemSet(typedValue.mValue, GetConstValue(0, GetPrimitiveType(BfTypeCode_Int8)),
  1260. GetConstValue(type->mSize), type->mAlign);
  1261. }
  1262. if ((defaultValueKind == BfDefaultValueKind_Value) && (!type->IsRef()))
  1263. typedValue = LoadValue(typedValue);
  1264. return typedValue;
  1265. }
  1266. if ((type->IsRef()) && (!allowRef))
  1267. {
  1268. BfRefType* refType = (BfRefType*)type;
  1269. BfType* underlyingType = refType->GetUnderlyingType();
  1270. if (underlyingType->IsValuelessType())
  1271. typedValue = BfTypedValue(mBfIRBuilder->GetFakeVal(), underlyingType, true);
  1272. else
  1273. typedValue = BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(type)), underlyingType, true);
  1274. }
  1275. else
  1276. {
  1277. typedValue = BfTypedValue(GetDefaultValue(type), type, (defaultValueKind == BfDefaultValueKind_Addr) ? BfTypedValueKind_Addr : BfTypedValueKind_Value);
  1278. }
  1279. return typedValue;
  1280. }
  1281. BfIRValue BfModule::CreateStringCharPtr(const StringImpl& str, int stringId, bool define)
  1282. {
  1283. String stringDataName = StrFormat("__bfStrData%d", stringId);
  1284. auto charType = GetPrimitiveType(BfTypeCode_Char8);
  1285. BfIRType irStrCharType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(charType), (int)str.length() + 1);
  1286. BfIRValue strConstant;
  1287. if (define)
  1288. {
  1289. strConstant = mBfIRBuilder->CreateConstString(str);
  1290. }
  1291. BfIRValue gv = mBfIRBuilder->CreateGlobalVariable(irStrCharType,
  1292. true, BfIRLinkageType_External,
  1293. strConstant, stringDataName);
  1294. if (define)
  1295. mBfIRBuilder->GlobalVar_SetUnnamedAddr(gv, true);
  1296. return mBfIRBuilder->CreateInBoundsGEP(gv, 0, 0);
  1297. }
  1298. BfIRValue BfModule::CreateStringObjectValue(const StringImpl& str, int stringId, bool define)
  1299. {
  1300. auto stringTypeInst = ResolveTypeDef(mCompiler->mStringTypeDef, define ? BfPopulateType_Data : BfPopulateType_Declaration)->ToTypeInstance();
  1301. mBfIRBuilder->PopulateType(stringTypeInst);
  1302. auto classVDataGlobal = CreateClassVDataGlobal(stringTypeInst);
  1303. String stringObjName = StrFormat("__bfStrObj%d", stringId);
  1304. BfIRValue stringValData;
  1305. if (define)
  1306. {
  1307. BfIRValue stringCharsVal = CreateStringCharPtr(str, stringId, define);
  1308. mStringCharPtrPool[stringId] = stringCharsVal;
  1309. SizedArray<BfIRValue, 8> typeValueParams;
  1310. GetConstClassValueParam(classVDataGlobal, typeValueParams);
  1311. auto objData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(stringTypeInst->mBaseType, BfIRPopulateType_Full), typeValueParams);
  1312. auto lenByteCount = stringTypeInst->mFieldInstances[0].mResolvedType->mSize;
  1313. typeValueParams.clear();
  1314. typeValueParams.push_back(objData);
  1315. if (lenByteCount == 4)
  1316. {
  1317. typeValueParams.push_back(GetConstValue32((int)str.length())); // mLength
  1318. typeValueParams.push_back(GetConstValue32((int32)(0x40000000 + str.length() + 1))); // mAllocSizeAndFlags
  1319. }
  1320. else
  1321. {
  1322. typeValueParams.push_back(GetConstValue64(str.length())); // mLength
  1323. typeValueParams.push_back(GetConstValue64(0x4000000000000000LL + str.length() + 1)); // mAllocSizeAndFlags
  1324. }
  1325. typeValueParams.push_back(stringCharsVal); // mPtr
  1326. for (int fieldIdx = 0; fieldIdx < (int)stringTypeInst->mFieldInstances.size(); fieldIdx++)
  1327. {
  1328. auto fieldInstance = &stringTypeInst->mFieldInstances[fieldIdx];
  1329. if (fieldInstance->mDataIdx < 4)
  1330. continue;
  1331. while (fieldInstance->mDataIdx >= typeValueParams.size())
  1332. typeValueParams.Add(BfIRValue());
  1333. typeValueParams[fieldInstance->mDataIdx] = GetDefaultValue(fieldInstance->mResolvedType);
  1334. }
  1335. stringValData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(stringTypeInst, BfIRPopulateType_Full), typeValueParams);
  1336. }
  1337. mBfIRBuilder->PopulateType(stringTypeInst);
  1338. auto stringValLiteral = mBfIRBuilder->CreateGlobalVariable(
  1339. mBfIRBuilder->MapTypeInst(stringTypeInst),
  1340. true,
  1341. BfIRLinkageType_External,
  1342. define ? stringValData : BfIRValue(),
  1343. stringObjName);
  1344. auto stringVal = mBfIRBuilder->CreateBitCast(stringValLiteral, mBfIRBuilder->MapType(stringTypeInst, BfIRPopulateType_Full));
  1345. return stringVal;
  1346. }
  1347. int BfModule::GetStringPoolIdx(BfIRValue constantStr, BfIRConstHolder* constHolder)
  1348. {
  1349. BF_ASSERT(constantStr.IsConst());
  1350. if (constHolder == NULL)
  1351. constHolder = mBfIRBuilder;
  1352. auto constant = constHolder->GetConstant(constantStr);
  1353. if (constant->mTypeCode == BfTypeCode_StringId)
  1354. {
  1355. return constant->mInt32;
  1356. }
  1357. while (constant->mConstType == BfConstType_BitCast)
  1358. {
  1359. auto constBitCast = (BfConstantBitCast*)constant;
  1360. constant = constHolder->GetConstantById(constBitCast->mTarget);
  1361. }
  1362. if (constant->mConstType == BfConstType_GEP32_2)
  1363. {
  1364. auto constGEP = (BfConstantGEP32_2*)constant;
  1365. constant = constHolder->GetConstantById(constGEP->mTarget);
  1366. }
  1367. if (constant->mConstType == BfConstType_GlobalVar)
  1368. {
  1369. auto constGV = (BfGlobalVar*)constant;
  1370. const char* strDataPrefix = "__bfStrData";
  1371. if (strncmp(constGV->mName, strDataPrefix, strlen(strDataPrefix)) == 0)
  1372. return atoi(constGV->mName + strlen(strDataPrefix));
  1373. const char* strObjPrefix = "__bfStrObj";
  1374. if (strncmp(constGV->mName, strObjPrefix, strlen(strObjPrefix)) == 0)
  1375. return atoi(constGV->mName + strlen(strObjPrefix));
  1376. }
  1377. return -1;
  1378. }
  1379. String* BfModule::GetStringPoolString(BfIRValue constantStr, BfIRConstHolder * constHolder)
  1380. {
  1381. int strId = GetStringPoolIdx(constantStr, constHolder);
  1382. if (strId != -1)
  1383. {
  1384. auto& entry = mContext->mStringObjectIdMap[strId];
  1385. return &entry.mString;
  1386. }
  1387. return NULL;
  1388. }
  1389. BfIRValue BfModule::GetStringCharPtr(int stringId)
  1390. {
  1391. BfIRValue* irValue = NULL;
  1392. if (!mStringCharPtrPool.TryAdd(stringId, NULL, &irValue))
  1393. return *irValue;
  1394. // If this wasn't in neither dictionary yet, add to mStringPoolRefs
  1395. if (!mStringObjectPool.ContainsKey(stringId))
  1396. mStringPoolRefs.Add(stringId);
  1397. const StringImpl& str = mContext->mStringObjectIdMap[stringId].mString;
  1398. BfIRValue strCharPtrConst = CreateStringCharPtr(str, stringId, false);
  1399. *irValue = strCharPtrConst;
  1400. return strCharPtrConst;
  1401. }
  1402. BfIRValue BfModule::GetStringCharPtr(BfIRValue strValue)
  1403. {
  1404. if (strValue.IsConst())
  1405. {
  1406. int stringId = GetStringPoolIdx(strValue);
  1407. BF_ASSERT(stringId != -1);
  1408. return GetStringCharPtr(stringId);
  1409. }
  1410. BfIRValue charPtrPtr = mBfIRBuilder->CreateInBoundsGEP(strValue, 0, 1);
  1411. BfIRValue charPtr = mBfIRBuilder->CreateLoad(charPtrPtr);
  1412. return charPtr;
  1413. }
  1414. BfIRValue BfModule::GetStringCharPtr(const StringImpl& str)
  1415. {
  1416. return GetStringCharPtr(GetStringObjectValue(str));
  1417. }
  1418. BfIRValue BfModule::GetStringObjectValue(int strId)
  1419. {
  1420. BfIRValue* objValue;
  1421. if (mStringObjectPool.TryGetValue(strId, &objValue))
  1422. return *objValue;
  1423. auto stringPoolEntry = mContext->mStringObjectIdMap[strId];
  1424. return GetStringObjectValue(stringPoolEntry.mString, true);
  1425. }
  1426. BfIRValue BfModule::GetStringObjectValue(const StringImpl& str, bool define)
  1427. {
  1428. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef, define ? BfPopulateType_Data : BfPopulateType_Declaration);
  1429. mBfIRBuilder->PopulateType(stringType);
  1430. int strId = mContext->GetStringLiteralId(str);
  1431. BfIRValue* irValuePtr = NULL;
  1432. if (!mStringObjectPool.TryAdd(strId, NULL, &irValuePtr))
  1433. return *irValuePtr;
  1434. // If this wasn't in neither dictionary yet, add to mStringPoolRefs
  1435. if (!mStringCharPtrPool.ContainsKey(strId))
  1436. mStringPoolRefs.Add(strId);
  1437. BfIRValue strObject = CreateStringObjectValue(str, strId, define);
  1438. *irValuePtr = strObject;
  1439. mStringPoolRefs.Add(strId);
  1440. return strObject;
  1441. }
  1442. BfIRValue BfModule::CreateGlobalConstValue(const StringImpl& name, BfIRValue constant, BfIRType type, bool external)
  1443. {
  1444. auto newConst = mBfIRBuilder->CreateGlobalVariable(
  1445. type,
  1446. true,
  1447. external ? BfIRLinkageType_External : BfIRLinkageType_Internal,
  1448. constant,
  1449. name.c_str());
  1450. return newConst;
  1451. }
  1452. void BfModule::NewScopeState(bool createLexicalBlock, bool flushValueScope)
  1453. {
  1454. auto curScope = mCurMethodState->mCurScope;
  1455. if (curScope->mLabelNode != NULL)
  1456. {
  1457. curScope->mLabelNode->ToString(curScope->mLabel);
  1458. auto rootMethodState = mCurMethodState->GetRootMethodState();
  1459. curScope->mScopeLocalId = rootMethodState->mCurLocalVarId++;
  1460. auto autoComplete = mCompiler->GetAutoComplete();
  1461. if (autoComplete != NULL)
  1462. autoComplete->CheckLabel(curScope->mLabelNode, NULL, curScope);
  1463. }
  1464. if (!mCurMethodState->mCurScope->mLabel.IsEmpty())
  1465. {
  1466. auto checkScope = mCurMethodState->mCurScope->mPrevScope;
  1467. while (checkScope != NULL)
  1468. {
  1469. if (checkScope->mLabel == mCurMethodState->mCurScope->mLabel)
  1470. {
  1471. auto errorNode = Fail("Duplicate scope label", curScope->mLabelNode);
  1472. if (errorNode != NULL)
  1473. mCompiler->mPassInstance->MoreInfo("See previous scope label", checkScope->mLabelNode);
  1474. break;
  1475. }
  1476. checkScope = checkScope->mPrevScope;
  1477. }
  1478. }
  1479. auto prevScope = mCurMethodState->mCurScope->mPrevScope;
  1480. if ((flushValueScope) && (prevScope != NULL) && (prevScope->mValueScopeStart))
  1481. {
  1482. if (prevScope->mHadScopeValueRetain)
  1483. mBfIRBuilder->CreateValueScopeSoftEnd(prevScope->mValueScopeStart);
  1484. else
  1485. mBfIRBuilder->CreateValueScopeHardEnd(prevScope->mValueScopeStart);
  1486. }
  1487. mCurMethodState->mBlockNestLevel++;
  1488. if ((createLexicalBlock) && (mBfIRBuilder->DbgHasInfo()) && (mHasFullDebugInfo))
  1489. {
  1490. // DIScope could be NULL if we're in an unspecialized method (for example)
  1491. if (mCurMethodState->mCurScope->mDIScope)
  1492. mCurMethodState->mCurScope->mDIScope = mBfIRBuilder->DbgCreateLexicalBlock(mCurMethodState->mCurScope->mDIScope, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mCurFilePosition.mCurColumn);
  1493. }
  1494. mCurMethodState->mCurScope->mLocalVarStart = (int)mCurMethodState->mLocals.size();
  1495. mCurMethodState->mCurScope->mBlock = mBfIRBuilder->MaybeChainNewBlock((!mCurMethodState->mCurScope->mLabel.empty()) ? mCurMethodState->mCurScope->mLabel : "newScope");
  1496. }
  1497. void BfModule::RestoreScoreState_LocalVariables()
  1498. {
  1499. while (mCurMethodState->mCurScope->mLocalVarStart < (int)mCurMethodState->mLocals.size())
  1500. {
  1501. auto localVar = mCurMethodState->mLocals.back();
  1502. LocalVariableDone(localVar, false);
  1503. mCurMethodState->mLocals.pop_back();
  1504. if (localVar->mShadowedLocal != NULL)
  1505. {
  1506. BfLocalVarEntry* localVarEntryPtr;
  1507. if (mCurMethodState->mLocalVarSet.TryGet(BfLocalVarEntry(localVar), &localVarEntryPtr))
  1508. {
  1509. localVarEntryPtr->mLocalVar = localVar->mShadowedLocal;
  1510. }
  1511. }
  1512. else
  1513. {
  1514. mCurMethodState->mLocalVarSet.Remove(BfLocalVarEntry(localVar));
  1515. }
  1516. delete localVar;
  1517. }
  1518. }
  1519. void BfModule::RestoreScopeState()
  1520. {
  1521. BfScopeData* prevScopeData = mCurMethodState->mCurScope->mPrevScope;
  1522. mCurMethodState->mBlockNestLevel--;
  1523. if (!mCurMethodState->mCurScope->mAtEndBlocks.empty())
  1524. {
  1525. BfIRBlock afterEndBlock;
  1526. if (!mCurMethodState->mLeftBlockUncond)
  1527. {
  1528. afterEndBlock = mBfIRBuilder->CreateBlock("scopeAfterEnd");
  1529. mBfIRBuilder->CreateBr(afterEndBlock);
  1530. mBfIRBuilder->ClearDebugLocation_Last();
  1531. }
  1532. for (auto preExitBlock : mCurMethodState->mCurScope->mAtEndBlocks)
  1533. mBfIRBuilder->MoveBlockToEnd(preExitBlock);
  1534. if (afterEndBlock)
  1535. {
  1536. mBfIRBuilder->AddBlock(afterEndBlock);
  1537. mBfIRBuilder->SetInsertPoint(afterEndBlock);
  1538. }
  1539. }
  1540. if (!mCurMethodState->mLeftBlockUncond)
  1541. EmitDeferredScopeCalls(true, mCurMethodState->mCurScope);
  1542. RestoreScoreState_LocalVariables();
  1543. if (mCurMethodState->mCurScope->mValueScopeStart)
  1544. mBfIRBuilder->CreateValueScopeHardEnd(mCurMethodState->mCurScope->mValueScopeStart);
  1545. mCurMethodState->mCurScope = prevScopeData;
  1546. mCurMethodState->mTailScope = mCurMethodState->mCurScope;
  1547. }
  1548. BfIRValue BfModule::CreateAlloca(BfType* type, bool addLifetime, const char* name, BfIRValue arraySize)
  1549. {
  1550. if (mBfIRBuilder->mIgnoreWrites)
  1551. return mBfIRBuilder->GetFakeVal();
  1552. BF_ASSERT((*(int8*)&addLifetime == 1) || (*(int8*)&addLifetime == 0));
  1553. mBfIRBuilder->PopulateType(type);
  1554. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  1555. if (!mBfIRBuilder->mIgnoreWrites)
  1556. BF_ASSERT(!prevInsertBlock.IsFake());
  1557. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  1558. BfIRValue allocaInst;
  1559. if (arraySize)
  1560. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type), arraySize);
  1561. else
  1562. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type));
  1563. mBfIRBuilder->SetAllocaAlignment(allocaInst, type->mAlign);
  1564. mBfIRBuilder->ClearDebugLocation(allocaInst);
  1565. if (name != NULL)
  1566. mBfIRBuilder->SetName(allocaInst, name);
  1567. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  1568. if ((addLifetime) && (WantsLifetimes()))
  1569. {
  1570. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  1571. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  1572. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  1573. }
  1574. return allocaInst;
  1575. }
  1576. BfIRValue BfModule::CreateAllocaInst(BfTypeInstance* typeInst, bool addLifetime, const char* name)
  1577. {
  1578. if (mBfIRBuilder->mIgnoreWrites)
  1579. return mBfIRBuilder->GetFakeVal();
  1580. BF_ASSERT((*(int8*)&addLifetime == 1) || (*(int8*)&addLifetime == 0));
  1581. mBfIRBuilder->PopulateType(typeInst);
  1582. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  1583. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  1584. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapTypeInst(typeInst));
  1585. mBfIRBuilder->SetAllocaAlignment(allocaInst, typeInst->mInstAlign);
  1586. mBfIRBuilder->ClearDebugLocation(allocaInst);
  1587. if (name != NULL)
  1588. mBfIRBuilder->SetName(allocaInst, name);
  1589. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  1590. if ((addLifetime) && (WantsLifetimes()))
  1591. {
  1592. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  1593. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  1594. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  1595. }
  1596. return allocaInst;
  1597. }
  1598. void BfModule::AddStackAlloc(BfTypedValue val, BfIRValue arraySize, BfAstNode* refNode, BfScopeData* scopeData, bool condAlloca, bool mayEscape)
  1599. {
  1600. //This was removed because we want the alloc to be added to the __deferred list if it's actually a "stack"
  1601. // 'stack' in a head scopeData is really the same as 'scopeData', so use the simpler scopeData handling
  1602. /*if (mCurMethodState->mInHeadScope)
  1603. isScopeAlloc = true;*/
  1604. if (scopeData == NULL)
  1605. return;
  1606. auto checkBaseType = val.mType->ToTypeInstance();
  1607. if ((checkBaseType != NULL) && (checkBaseType->IsObject()))
  1608. {
  1609. bool hadDtorCall = false;
  1610. while (checkBaseType != NULL)
  1611. {
  1612. if ((checkBaseType->mTypeDef->mDtorDef != NULL) /*&& (checkBaseType != mContext->mBfObjectType)*/)
  1613. {
  1614. auto dtorMethodInstance = GetMethodInstance(checkBaseType, checkBaseType->mTypeDef->mDtorDef, BfTypeVector());
  1615. if (dtorMethodInstance)
  1616. {
  1617. bool isDynAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsDyn(scopeData));
  1618. BfIRValue useVal = val.mValue;
  1619. useVal = mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapTypeInstPtr(checkBaseType));
  1620. if (isDynAlloc)
  1621. {
  1622. //
  1623. }
  1624. else if (condAlloca)
  1625. {
  1626. BF_ASSERT(!IsTargetingBeefBackend());
  1627. BF_ASSERT(!isDynAlloc);
  1628. auto valPtr = CreateAlloca(checkBaseType);
  1629. mBfIRBuilder->CreateStore(useVal, valPtr);
  1630. useVal = valPtr;
  1631. }
  1632. SizedArray<BfIRValue, 1> llvmArgs;
  1633. llvmArgs.push_back(useVal);
  1634. auto deferredCall = AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1635. if (deferredCall != NULL)
  1636. {
  1637. deferredCall->mCastThis = (val.mType != checkBaseType) && (!isDynAlloc);
  1638. if (condAlloca)
  1639. deferredCall->mArgsNeedLoad = true;
  1640. }
  1641. hadDtorCall = true;
  1642. break;
  1643. }
  1644. }
  1645. checkBaseType = checkBaseType->mBaseType;
  1646. }
  1647. return;
  1648. }
  1649. //TODO: In the future we could be smarter about statically determining that our value hasn't escaped and eliding this
  1650. if (mayEscape)
  1651. {
  1652. if ((!IsOptimized()) && (!val.mType->IsValuelessType()) && (!mBfIRBuilder->mIgnoreWrites) && (!mCompiler->mIsResolveOnly))
  1653. {
  1654. auto nullPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  1655. bool isDyn = mCurMethodState->mCurScope->IsDyn(scopeData);
  1656. if (!isDyn)
  1657. {
  1658. const char* methodName = arraySize ? "SetDeletedArray" : "SetDeleted";
  1659. BfModuleMethodInstance dtorMethodInstance = GetInternalMethod(methodName);
  1660. BF_ASSERT(dtorMethodInstance.mMethodInstance != NULL);
  1661. if (!dtorMethodInstance.mMethodInstance)
  1662. {
  1663. Fail(StrFormat("Unable to find %s", methodName));
  1664. }
  1665. else
  1666. {
  1667. SizedArray<BfIRValue, 1> llvmArgs;
  1668. llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(nullPtrType)));
  1669. llvmArgs.push_back(GetConstValue(val.mType->mSize));
  1670. llvmArgs.push_back(GetConstValue32(val.mType->mAlign));
  1671. if (arraySize)
  1672. llvmArgs.push_back(arraySize);
  1673. AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1674. }
  1675. }
  1676. else
  1677. {
  1678. if ((arraySize) && (!arraySize.IsConst()) && (val.mType->mSize < mSystem->mPtrSize))
  1679. {
  1680. BfIRValue clearSize = arraySize;
  1681. if (val.mType->GetStride() > 1)
  1682. clearSize = mBfIRBuilder->CreateMul(clearSize, GetConstValue(val.mType->GetStride()));
  1683. const char* methodName = "SetDeletedX";
  1684. BfModuleMethodInstance dtorMethodInstance = GetInternalMethod(methodName);
  1685. BF_ASSERT(dtorMethodInstance);
  1686. if (!dtorMethodInstance)
  1687. {
  1688. Fail(StrFormat("Unable to find %s", methodName));
  1689. }
  1690. else
  1691. {
  1692. SizedArray<BfIRValue, 1> llvmArgs;
  1693. llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(nullPtrType)));
  1694. llvmArgs.push_back(clearSize);
  1695. AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1696. }
  1697. }
  1698. else
  1699. {
  1700. intptr clearSize = val.mType->mSize;
  1701. auto constant = mBfIRBuilder->GetConstant(arraySize);
  1702. if (constant != NULL)
  1703. clearSize = (intptr)(clearSize * constant->mInt64);
  1704. const char* funcName = "SetDeleted1";
  1705. if (clearSize >= 16)
  1706. funcName = "SetDeleted16";
  1707. else if (clearSize >= 8)
  1708. funcName = "SetDeleted8";
  1709. else if (clearSize >= 4)
  1710. funcName = "SetDeleted4";
  1711. BfModuleMethodInstance dtorMethodInstance = GetInternalMethod(funcName);
  1712. BF_ASSERT(dtorMethodInstance.mMethodInstance != NULL);
  1713. if (!dtorMethodInstance)
  1714. {
  1715. Fail(StrFormat("Unable to find %s", funcName));
  1716. }
  1717. else
  1718. {
  1719. SizedArray<BfIRValue, 1> llvmArgs;
  1720. llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(nullPtrType)));
  1721. AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1722. }
  1723. }
  1724. }
  1725. }
  1726. }
  1727. }
  1728. bool BfModule::TryLocalVariableInit(BfLocalVariable* localVar)
  1729. {
  1730. auto startTypeInstance = localVar->mResolvedType->ToTypeInstance();
  1731. if ((startTypeInstance == NULL) || (!startTypeInstance->IsStruct()))
  1732. return false;
  1733. auto checkTypeInstance = startTypeInstance;
  1734. while (checkTypeInstance != NULL)
  1735. {
  1736. for (auto& fieldInstance : checkTypeInstance->mFieldInstances)
  1737. {
  1738. if (fieldInstance.mMergedDataIdx != -1)
  1739. {
  1740. int64 checkMask = (int64)1 << fieldInstance.mMergedDataIdx;
  1741. if ((localVar->mUnassignedFieldFlags & checkMask) != 0)
  1742. {
  1743. // For fields added in extensions, we automatically initialize those if necessary
  1744. auto fieldDef = fieldInstance.GetFieldDef();
  1745. if (!fieldDef->mDeclaringType->IsExtension())
  1746. return false;
  1747. if ((fieldInstance.mDataIdx != -1) && (!mBfIRBuilder->mIgnoreWrites) && (!mCompiler->mIsResolveOnly))
  1748. {
  1749. auto curInsertBlock = mBfIRBuilder->GetInsertBlock();
  1750. mBfIRBuilder->SaveDebugLocation();
  1751. if (localVar->IsParam())
  1752. mBfIRBuilder->SetInsertPointAtStart(mCurMethodState->mIRInitBlock);
  1753. else
  1754. {
  1755. BF_ASSERT(localVar->mDeclBlock);
  1756. mBfIRBuilder->SetInsertPointAtStart(localVar->mDeclBlock);
  1757. }
  1758. mBfIRBuilder->ClearDebugLocation();
  1759. BfIRValue curVal;
  1760. if (localVar->mIsThis)
  1761. curVal = mBfIRBuilder->GetArgument(0);
  1762. else
  1763. curVal = localVar->mAddr;
  1764. auto subTypeInstance = startTypeInstance;
  1765. while (subTypeInstance != checkTypeInstance)
  1766. {
  1767. curVal = mBfIRBuilder->CreateInBoundsGEP(curVal, 0, 0);
  1768. subTypeInstance = subTypeInstance->mBaseType;
  1769. }
  1770. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(curVal, 0, fieldInstance.mDataIdx);
  1771. auto defVal = GetDefaultValue(fieldInstance.mResolvedType);
  1772. auto storeInst = mBfIRBuilder->CreateStore(defVal, fieldPtr);
  1773. mBfIRBuilder->SetInsertPoint(curInsertBlock);
  1774. mBfIRBuilder->RestoreDebugLocation();
  1775. }
  1776. localVar->mUnassignedFieldFlags &= ~checkMask;
  1777. if (localVar->mUnassignedFieldFlags == 0)
  1778. localVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  1779. }
  1780. }
  1781. }
  1782. checkTypeInstance = checkTypeInstance->mBaseType;
  1783. }
  1784. return localVar->mAssignedKind != BfLocalVarAssignKind_None;
  1785. }
  1786. void BfModule::LocalVariableDone(BfLocalVariable* localVar, bool isMethodExit)
  1787. {
  1788. //if (localVar->mAddr == NULL)
  1789. /*if ((localVar->mValue) && (!localVar->mAddr) && (IsTargetingBeefBackend()))
  1790. {
  1791. if ((!localVar->mValue.IsConst()) && (!localVar->mValue.IsArg()) && (!localVar->mValue.IsFake()))
  1792. {
  1793. if (mCurMethodInstance->mMethodDef->mName == "FuncA")
  1794. mBfIRBuilder->CreateLifetimeEnd(localVar->mValue);
  1795. }
  1796. }*/
  1797. BfAstNode* localNameNode = localVar->mNameNode;
  1798. if (localVar->mIsThis)
  1799. {
  1800. localNameNode = mCurMethodInstance->mMethodDef->GetRefNode();
  1801. }
  1802. if (localNameNode != NULL)
  1803. {
  1804. bool isOut = false;
  1805. if (localVar->mResolvedType->IsRef())
  1806. {
  1807. auto refType = (BfRefType*)localVar->mResolvedType;
  1808. isOut = refType->mRefKind == BfRefType::RefKind_Out;
  1809. }
  1810. if ((localVar->mReadFromId == -1) || (isOut) || ((localVar->mIsThis) && (mCurTypeInstance->IsStruct())))
  1811. {
  1812. if ((localVar->mAssignedKind != BfLocalVarAssignKind_Unconditional) & (localVar->IsParam()))
  1813. TryLocalVariableInit(localVar);
  1814. // We may skip processing of local methods, so we won't know if it bind to any of our local variables or not
  1815. bool deferFullAnalysis = mCurMethodState->GetRootMethodState()->mLocalMethodCache.size() != 0;
  1816. //bool deferFullAnalysis = true;
  1817. bool deferUsageWarning = deferFullAnalysis && mCompiler->IsAutocomplete();
  1818. if (((localVar->mAssignedKind != BfLocalVarAssignKind_Unconditional) || (localVar->mHadExitBeforeAssign)) &&
  1819. (!localVar->mIsImplicitParam))
  1820. {
  1821. if (deferUsageWarning)
  1822. {
  1823. // Ignore
  1824. }
  1825. else if (localVar->mIsThis)
  1826. {
  1827. bool foundFields = false;
  1828. auto checkTypeInstance = mCurTypeInstance;
  1829. while (checkTypeInstance != NULL)
  1830. {
  1831. for (auto& fieldInstance : checkTypeInstance->mFieldInstances)
  1832. {
  1833. if (fieldInstance.mMergedDataIdx != -1)
  1834. {
  1835. int checkMask = 1 << fieldInstance.mMergedDataIdx;
  1836. if ((localVar->mUnassignedFieldFlags & checkMask) != 0)
  1837. {
  1838. auto fieldDef = fieldInstance.GetFieldDef();
  1839. if (auto propertyDeclaration = BfNodeDynCast<BfPropertyDeclaration>(fieldDef->mFieldDeclaration))
  1840. {
  1841. String propName;
  1842. if (propertyDeclaration->mNameNode != NULL)
  1843. propertyDeclaration->mNameNode->ToString(propName);
  1844. if (checkTypeInstance == mCurTypeInstance)
  1845. {
  1846. Fail(StrFormat("Auto-implemented property '%s' must be fully assigned before control is returned to the caller",
  1847. propName.c_str()), localNameNode, deferFullAnalysis); // 0171
  1848. }
  1849. else
  1850. {
  1851. Fail(StrFormat("Auto-implemented property '%s.%s' must be fully assigned before control is returned to the caller",
  1852. TypeToString(checkTypeInstance).c_str(),
  1853. propName.c_str()), localNameNode, deferFullAnalysis); // 0171
  1854. }
  1855. }
  1856. else
  1857. {
  1858. if (checkTypeInstance == mCurTypeInstance)
  1859. {
  1860. Fail(StrFormat("Field '%s' must be fully assigned before control is returned to the caller",
  1861. fieldDef->mName.c_str()), localNameNode, deferFullAnalysis); // 0171
  1862. }
  1863. else
  1864. {
  1865. Fail(StrFormat("Field '%s.%s' must be fully assigned before control is returned to the caller",
  1866. TypeToString(checkTypeInstance).c_str(),
  1867. fieldDef->mName.c_str()), localNameNode, deferFullAnalysis); // 0171
  1868. }
  1869. }
  1870. foundFields = true;
  1871. }
  1872. }
  1873. }
  1874. checkTypeInstance = checkTypeInstance->mBaseType;
  1875. }
  1876. if (!foundFields)
  1877. {
  1878. if (mCurTypeInstance->mInstSize > 0)
  1879. Fail(StrFormat("The variable '%s' must be fully assigned to before control leaves the current method", localVar->mName.c_str()), localNameNode); // 0177
  1880. }
  1881. }
  1882. else if (localVar->IsParam())
  1883. Fail(StrFormat("The out parameter '%s' must be assigned to before control leaves the current method", localVar->mName.c_str()), localNameNode, deferFullAnalysis); // 0177
  1884. else if (!deferUsageWarning)
  1885. Warn(BfWarning_CS0168_VariableDeclaredButNeverUsed, StrFormat("The variable '%s' is declared but never used", localVar->mName.c_str()), localNameNode, deferFullAnalysis);
  1886. }
  1887. else if ((localVar->mReadFromId == -1) && (!localVar->IsParam()) && (!deferUsageWarning))
  1888. Warn(BfWarning_CS0168_VariableDeclaredButNeverUsed, StrFormat("The variable '%s' is assigned but its value is never used", localVar->mName.c_str()), localNameNode, deferFullAnalysis);
  1889. }
  1890. }
  1891. }
  1892. void BfModule::MarkDynStack(BfScopeData* scopeData)
  1893. {
  1894. auto checkScope = mCurMethodState->mCurScope;
  1895. while (true)
  1896. {
  1897. if (checkScope == scopeData)
  1898. break;
  1899. checkScope->mHadOuterDynStack = true;
  1900. checkScope = checkScope->mPrevScope;
  1901. }
  1902. }
  1903. void BfModule::SaveStackState(BfScopeData* scopeData)
  1904. {
  1905. // If we push a value on the stack that needs to survive until the end of scopeData, we need to make sure that no
  1906. // scopes within scopeData restore the stack
  1907. auto checkScope = mCurMethodState->mCurScope;
  1908. while (true)
  1909. {
  1910. if (checkScope == scopeData)
  1911. {
  1912. if ((!checkScope->mSavedStack) && (checkScope->mBlock) && (!checkScope->mIsScopeHead) && (!checkScope->mHadOuterDynStack))
  1913. {
  1914. if (mBfIRBuilder->mHasDebugInfo)
  1915. mBfIRBuilder->SaveDebugLocation();
  1916. auto prevPos = mBfIRBuilder->GetInsertBlock();
  1917. mBfIRBuilder->SetInsertPointAtStart(checkScope->mBlock);
  1918. checkScope->mSavedStack = mBfIRBuilder->CreateStackSave();
  1919. mBfIRBuilder->ClearDebugLocation(checkScope->mSavedStack);
  1920. mBfIRBuilder->SetInsertPoint(prevPos);
  1921. if (mBfIRBuilder->mHasDebugInfo)
  1922. mBfIRBuilder->RestoreDebugLocation();
  1923. }
  1924. break;
  1925. }
  1926. if (checkScope->mSavedStack)
  1927. {
  1928. for (auto usage : checkScope->mSavedStackUses)
  1929. mBfIRBuilder->EraseInstFromParent(usage);
  1930. checkScope->mSavedStackUses.Clear();
  1931. mBfIRBuilder->EraseInstFromParent(checkScope->mSavedStack);
  1932. checkScope->mSavedStack = BfIRValue();
  1933. }
  1934. checkScope = checkScope->mPrevScope;
  1935. }
  1936. }
  1937. BfIRValue BfModule::ValueScopeStart()
  1938. {
  1939. if (IsTargetingBeefBackend())
  1940. return mBfIRBuilder->CreateValueScopeStart();
  1941. return BfIRValue();
  1942. }
  1943. void BfModule::ValueScopeEnd(BfIRValue valueScopeStart)
  1944. {
  1945. if (valueScopeStart)
  1946. mBfIRBuilder->CreateValueScopeHardEnd(valueScopeStart);
  1947. }
  1948. BfProjectSet* BfModule::GetVisibleProjectSet()
  1949. {
  1950. if (mCurMethodState == NULL)
  1951. return NULL;
  1952. if (mCurMethodState->mVisibleProjectSet.IsEmpty())
  1953. {
  1954. HashSet<BfType*> seenTypes;
  1955. std::function<void(BfProject* project)> _AddProject = [&](BfProject* project)
  1956. {
  1957. if (mCurMethodState->mVisibleProjectSet.Add(project))
  1958. {
  1959. for (auto dep : project->mDependencies)
  1960. _AddProject(dep);
  1961. }
  1962. };
  1963. std::function<void(BfType* type)> _AddType = [&](BfType* type)
  1964. {
  1965. auto typeInstance = type->ToTypeInstance();
  1966. if (typeInstance == NULL)
  1967. {
  1968. if (type->IsSizedArray())
  1969. _AddType(type->GetUnderlyingType());
  1970. return;
  1971. }
  1972. if (typeInstance->IsTuple())
  1973. {
  1974. for (auto& fieldInst : typeInstance->mFieldInstances)
  1975. {
  1976. if (fieldInst.mDataIdx != -1)
  1977. _AddType(fieldInst.mResolvedType);
  1978. }
  1979. }
  1980. _AddProject(typeInstance->mTypeDef->mProject);
  1981. if (typeInstance->mGenericTypeInfo == NULL)
  1982. return;
  1983. for (auto type : typeInstance->mGenericTypeInfo->mTypeGenericArguments)
  1984. {
  1985. if (seenTypes.Add(type))
  1986. _AddType(type);
  1987. }
  1988. };
  1989. if (mCurTypeInstance != NULL)
  1990. _AddType(mCurTypeInstance);
  1991. auto methodState = mCurMethodState;
  1992. while (methodState != NULL)
  1993. {
  1994. if (methodState->mMethodInstance != NULL)
  1995. {
  1996. _AddProject(methodState->mMethodInstance->mMethodDef->mDeclaringType->mProject);
  1997. if (methodState->mMethodInstance->mMethodInfoEx != NULL)
  1998. {
  1999. for (auto type : methodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  2000. _AddType(type);
  2001. }
  2002. }
  2003. methodState = methodState->mPrevMethodState;
  2004. }
  2005. }
  2006. return &mCurMethodState->mVisibleProjectSet;
  2007. }
  2008. BfFileInstance* BfModule::GetFileFromNode(BfAstNode* astNode)
  2009. {
  2010. auto bfParser = astNode->GetSourceData()->ToParserData();
  2011. if (bfParser == NULL)
  2012. return NULL;
  2013. BfFileInstance** fileInstancePtr = NULL;
  2014. if (!mFileInstanceMap.TryAdd(bfParser, NULL, &fileInstancePtr))
  2015. {
  2016. return *fileInstancePtr;
  2017. }
  2018. else
  2019. {
  2020. // It's possible two parsers have the same file name (ie: mNextRevision)
  2021. BfFileInstance** namedFileInstancePtr = NULL;
  2022. if (!mNamedFileInstanceMap.TryAdd(bfParser->mFileName, NULL, &namedFileInstancePtr))
  2023. {
  2024. auto bfFileInstance = *namedFileInstancePtr;
  2025. *fileInstancePtr = bfFileInstance;
  2026. return bfFileInstance;
  2027. }
  2028. int slashPos = (int)bfParser->mFileName.LastIndexOf(DIR_SEP_CHAR);
  2029. auto bfFileInstance = new BfFileInstance();
  2030. *fileInstancePtr = bfFileInstance;
  2031. *namedFileInstancePtr = bfFileInstance;
  2032. bfFileInstance->mPrevPosition.mFileInstance = bfFileInstance;
  2033. bfFileInstance->mParser = bfParser;
  2034. BfLogSysM("GetFileFromNode new file. Mod: %p FileInstance: %p Parser: %p\n", this, bfFileInstance, bfParser);
  2035. if ((mBfIRBuilder != NULL) && (mBfIRBuilder->DbgHasInfo()))
  2036. {
  2037. String fileName = bfParser->mFileName;
  2038. for (int i = 0; i < (int)fileName.length(); i++)
  2039. {
  2040. if (fileName[i] == DIR_SEP_CHAR_ALT)
  2041. fileName[i] = DIR_SEP_CHAR;
  2042. }
  2043. bfFileInstance->mDIFile = mBfIRBuilder->DbgCreateFile(fileName.Substring(slashPos + 1), fileName.Substring(0, slashPos), bfParser->mMD5Hash);
  2044. }
  2045. return bfFileInstance;
  2046. }
  2047. }
  2048. void BfModule::UpdateSrcPos(BfAstNode* astNode, BfSrcPosFlags flags, int debugLocOffset)
  2049. {
  2050. // We set force to true when we MUST get the line position set (for navigation purposes, for example)
  2051. if (((mBfIRBuilder->mIgnoreWrites)) && ((flags & BfSrcPosFlag_Force) == 0))
  2052. return;
  2053. BF_ASSERT((!mAwaitingInitFinish) || (mBfIRBuilder->mIgnoreWrites));
  2054. if (astNode == NULL)
  2055. return;
  2056. auto bfParser = astNode->GetSourceData()->ToParserData();
  2057. if (bfParser == NULL)
  2058. return;
  2059. if ((mCurFilePosition.mFileInstance == NULL) || (mCurFilePosition.mFileInstance->mParser != bfParser))
  2060. {
  2061. if (mCurFilePosition.mFileInstance != NULL)
  2062. {
  2063. BF_ASSERT(mFileInstanceMap.GetCount() != 0);
  2064. mCurFilePosition.mFileInstance->mPrevPosition = mCurFilePosition;
  2065. }
  2066. auto bfFileInstance = GetFileFromNode(astNode);
  2067. if (bfFileInstance->mPrevPosition.mFileInstance != NULL)
  2068. {
  2069. mCurFilePosition = bfFileInstance->mPrevPosition;
  2070. }
  2071. else
  2072. {
  2073. mCurFilePosition.mFileInstance = bfFileInstance;
  2074. mCurFilePosition.mCurLine = 0;
  2075. mCurFilePosition.mCurSrcPos = 0;
  2076. }
  2077. }
  2078. int srcPos = astNode->GetSrcStart() + debugLocOffset;
  2079. BF_ASSERT(srcPos < bfParser->mSrcLength);
  2080. auto* jumpEntry = bfParser->mJumpTable + (srcPos / PARSER_JUMPTABLE_DIVIDE);
  2081. if (jumpEntry->mCharIdx > srcPos)
  2082. jumpEntry--;
  2083. mCurFilePosition.mCurLine = jumpEntry->mLineNum;
  2084. mCurFilePosition.mCurSrcPos = jumpEntry->mCharIdx;
  2085. mCurFilePosition.mCurColumn = 0;
  2086. while (mCurFilePosition.mCurSrcPos < srcPos)
  2087. {
  2088. if (bfParser->mSrc[mCurFilePosition.mCurSrcPos] == '\n')
  2089. {
  2090. mCurFilePosition.mCurLine++;
  2091. mCurFilePosition.mCurColumn = 0;
  2092. }
  2093. else
  2094. {
  2095. mCurFilePosition.mCurColumn++;
  2096. }
  2097. mCurFilePosition.mCurSrcPos++;
  2098. }
  2099. //TODO: if we bail on the "mCurMethodState == NULL" case then we don't get it set during type declarations
  2100. if (((flags & BfSrcPosFlag_NoSetDebugLoc) == 0) && (mBfIRBuilder->DbgHasInfo()) && (mCurMethodState != NULL))
  2101. {
  2102. int column = mCurFilePosition.mCurColumn + 1;
  2103. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend))
  2104. {
  2105. // Set to illegal position
  2106. column = 0;
  2107. }
  2108. if (mSetIllegalSrcPosition)
  2109. column = 0;
  2110. BfIRMDNode useDIScope = mCurMethodState->mCurScope->mDIScope;
  2111. auto wantDIFile = mCurFilePosition.mFileInstance->mDIFile;
  2112. if ((wantDIFile != mCurMethodState->mDIFile) && (mCurMethodState->mDIFile))
  2113. {
  2114. // This is from a different scope...
  2115. if (wantDIFile != mCurMethodState->mCurScope->mAltDIFile)
  2116. {
  2117. mCurMethodState->mCurScope->mAltDIFile = wantDIFile;
  2118. mCurMethodState->mCurScope->mAltDIScope = mBfIRBuilder->DbgCreateLexicalBlock(mCurMethodState->mCurScope->mDIScope, wantDIFile, mCurFilePosition.mCurLine + 1, column);
  2119. }
  2120. if (mCurMethodState->mCurScope->mAltDIScope) // This may not be set if mAltDIFile is set by a mixin
  2121. useDIScope = mCurMethodState->mCurScope->mAltDIScope;
  2122. }
  2123. else
  2124. {
  2125. if (mCurMethodState->mCurScope->mAltDIFile)
  2126. {
  2127. mCurMethodState->mCurScope->mAltDIFile = BfIRMDNode();
  2128. mCurMethodState->mCurScope->mAltDIScope = BfIRMDNode();
  2129. }
  2130. }
  2131. auto inlineAt = mCurMethodState->mCurScope->mDIInlinedAt;
  2132. if (mCurMethodState->mCrossingMixin)
  2133. inlineAt = BfIRMDNode();
  2134. mBfIRBuilder->SetCurrentDebugLocation(mCurFilePosition.mCurLine + 1, column, useDIScope, inlineAt);
  2135. if ((flags & BfSrcPosFlag_Expression) == 0)
  2136. mBfIRBuilder->CreateStatementStart();
  2137. }
  2138. }
  2139. void BfModule::UpdateExprSrcPos(BfAstNode* astNode, BfSrcPosFlags flags)
  2140. {
  2141. // We've turned off expr src pos (for now?)
  2142. //UpdateSrcPos(astNode, (BfSrcPosFlags)(flags | BfSrcPosFlag_Expression));
  2143. }
  2144. void BfModule::UseDefaultSrcPos(BfSrcPosFlags flags, int debugLocOffset)
  2145. {
  2146. UpdateSrcPos(mCompiler->mBfObjectTypeDef->mTypeDeclaration, flags, debugLocOffset);
  2147. SetIllegalSrcPos();
  2148. }
  2149. void BfModule::SetIllegalSrcPos(BfSrcPosFlags flags)
  2150. {
  2151. if ((mBfIRBuilder->DbgHasInfo()) && (mCurMethodState != NULL))
  2152. {
  2153. if ((mCurMethodState->mCurScope->mDIInlinedAt) && (mCompiler->mOptions.IsCodeView()))
  2154. {
  2155. // Currently, CodeView does not record column positions so we can't use an illegal column position as an "invalid" marker
  2156. mBfIRBuilder->SetCurrentDebugLocation(0, 0, mCurMethodState->mCurScope->mDIScope, mCurMethodState->mCurScope->mDIInlinedAt);
  2157. }
  2158. else
  2159. {
  2160. // Set to whatever it previously was but at column zero, which we will know to be illegal
  2161. mBfIRBuilder->SetCurrentDebugLocation(mCurFilePosition.mCurLine + 1, 0, mCurMethodState->mCurScope->mDIScope, mCurMethodState->mCurScope->mDIInlinedAt);
  2162. }
  2163. if ((flags & BfSrcPosFlag_Expression) == 0)
  2164. mBfIRBuilder->CreateStatementStart();
  2165. }
  2166. }
  2167. void BfModule::SetIllegalExprSrcPos(BfSrcPosFlags flags)
  2168. {
  2169. // We've turned off expr src pos (for now?)
  2170. //SetIllegalSrcPos((BfSrcPosFlags)(flags | BfSrcPosFlag_Expression));
  2171. }
  2172. bool BfModule::CheckProtection(BfProtection protection, BfTypeDef* checkType, bool allowProtected, bool allowPrivate)
  2173. {
  2174. if ((protection == BfProtection_Public) ||
  2175. ((protection == BfProtection_Protected) && (allowProtected)) ||
  2176. ((protection == BfProtection_Private) && (allowPrivate)))
  2177. return true;
  2178. if ((mAttributeState != NULL) && (mAttributeState->mCustomAttributes != NULL) && (mAttributeState->mCustomAttributes->Contains(mCompiler->mFriendAttributeTypeDef)))
  2179. {
  2180. mAttributeState->mUsed = true;
  2181. return true;
  2182. }
  2183. if ((protection == BfProtection_Internal) && (checkType != NULL))
  2184. {
  2185. if (CheckInternalProtection(checkType))
  2186. return true;
  2187. }
  2188. return false;
  2189. }
  2190. void BfModule::GetAccessAllowed(BfTypeInstance* checkType, bool &allowProtected, bool &allowPrivate)
  2191. {
  2192. allowPrivate = (checkType == mCurTypeInstance) || (IsInnerType(mCurTypeInstance, checkType));
  2193. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2194. {
  2195. auto mixinOwner = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  2196. allowPrivate |= (checkType == mixinOwner) || (IsInnerType(mixinOwner, checkType));
  2197. }
  2198. allowProtected = allowPrivate;
  2199. }
  2200. bool BfModule::CheckProtection(BfProtectionCheckFlags& flags, BfTypeInstance* memberOwner, BfProject* memberProject, BfProtection memberProtection, BfTypeInstance* lookupStartType)
  2201. {
  2202. if (memberProtection == BfProtection_Hidden)
  2203. return false;
  2204. if (memberProtection == BfProtection_Public)
  2205. return true;
  2206. if ((flags & BfProtectionCheckFlag_CheckedPrivate) == 0)
  2207. {
  2208. BfTypeInstance* curCheckType = mCurTypeInstance;
  2209. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2210. {
  2211. auto mixinOwner = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  2212. curCheckType = mixinOwner;
  2213. }
  2214. bool allowPrivate = (curCheckType != NULL) && (memberOwner->mTypeDef == curCheckType->mTypeDef);
  2215. if (curCheckType != NULL)
  2216. allowPrivate |= IsInnerType(curCheckType->mTypeDef, memberOwner->mTypeDef);
  2217. if (allowPrivate)
  2218. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_AllowPrivate | BfProtectionCheckFlag_CheckedPrivate);
  2219. else
  2220. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedPrivate);
  2221. }
  2222. if ((flags & BfProtectionCheckFlag_AllowPrivate) != 0)
  2223. return true;
  2224. if (memberProtection == BfProtection_Protected)
  2225. {
  2226. if ((flags & BfProtectionCheckFlag_CheckedProtected) == 0)
  2227. {
  2228. bool allowProtected = false;
  2229. auto memberOwnerTypeDef = memberOwner->mTypeDef;
  2230. auto curCheckType = mCurTypeInstance;
  2231. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2232. {
  2233. auto mixinOwner = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  2234. curCheckType = mixinOwner;
  2235. }
  2236. auto lookupCheckType = lookupStartType;
  2237. while (lookupCheckType->mInheritDepth >= curCheckType->mInheritDepth)
  2238. {
  2239. if (lookupCheckType == curCheckType)
  2240. {
  2241. allowProtected = true;
  2242. break;
  2243. }
  2244. if (lookupCheckType == memberOwner)
  2245. break;
  2246. lookupCheckType = lookupCheckType->mBaseType;
  2247. if (lookupCheckType == NULL)
  2248. break;
  2249. }
  2250. if (!allowProtected)
  2251. {
  2252. // It's possible our outer type is derived from 'memberOwner'
  2253. while (curCheckType->mTypeDef->mNestDepth > 0)
  2254. {
  2255. curCheckType = GetOuterType(curCheckType);
  2256. if (curCheckType == NULL)
  2257. break;
  2258. auto lookupCheckType = lookupStartType;
  2259. while (lookupCheckType->mInheritDepth >= curCheckType->mInheritDepth)
  2260. {
  2261. if (lookupCheckType == curCheckType)
  2262. {
  2263. allowProtected = true;
  2264. break;
  2265. }
  2266. if (lookupCheckType == memberOwner)
  2267. break;
  2268. lookupCheckType = lookupCheckType->mBaseType;
  2269. if (lookupCheckType == NULL)
  2270. break;
  2271. }
  2272. }
  2273. }
  2274. if (allowProtected)
  2275. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedProtected | BfProtectionCheckFlag_AllowProtected);
  2276. else
  2277. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedProtected);
  2278. }
  2279. if ((flags & BfProtectionCheckFlag_AllowProtected) != 0)
  2280. return true;
  2281. }
  2282. if ((mAttributeState != NULL) && (mAttributeState->mCustomAttributes != NULL) && (mAttributeState->mCustomAttributes->Contains(mCompiler->mFriendAttributeTypeDef)))
  2283. {
  2284. mAttributeState->mUsed = true;
  2285. return true;
  2286. }
  2287. if ((memberProtection == BfProtection_Internal) && (memberOwner != NULL))
  2288. {
  2289. if (CheckInternalProtection(memberOwner->mTypeDef))
  2290. return true;
  2291. }
  2292. return false;
  2293. }
  2294. void BfModule::SetElementType(BfAstNode* astNode, BfSourceElementType elementType)
  2295. {
  2296. if ((mCompiler->mResolvePassData != NULL) &&
  2297. (mCompiler->mResolvePassData->mSourceClassifier != NULL) &&
  2298. (astNode->IsFromParser( mCompiler->mResolvePassData->mParser)))
  2299. {
  2300. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(astNode, elementType);
  2301. }
  2302. }
  2303. void BfModule::SetFail()
  2304. {
  2305. if (mIgnoreErrors)
  2306. {
  2307. if (mAttributeState != NULL)
  2308. mAttributeState->mFlags = (BfAttributeState::Flags)(mAttributeState->mFlags | BfAttributeState::Flag_HadError);
  2309. }
  2310. }
  2311. BfError* BfModule::Fail(const StringImpl& error, BfAstNode* refNode, bool isPersistent)
  2312. {
  2313. BP_ZONE("BfModule::Fail");
  2314. if (mIgnoreErrors)
  2315. {
  2316. if (mAttributeState != NULL)
  2317. mAttributeState->mFlags = (BfAttributeState::Flags)(mAttributeState->mFlags | BfAttributeState::Flag_HadError);
  2318. return NULL;
  2319. }
  2320. if (!mReportErrors)
  2321. {
  2322. mCompiler->mPassInstance->SilentFail();
  2323. return NULL;
  2324. }
  2325. if (refNode != NULL)
  2326. refNode = BfNodeToNonTemporary(refNode);
  2327. //BF_ASSERT(refNode != NULL);
  2328. if (mCurMethodInstance != NULL)
  2329. mCurMethodInstance->mHasFailed = true;
  2330. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsUnspecializedTypeVariation()))
  2331. return NULL;
  2332. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->IsOrInUnspecializedVariation()))
  2333. return NULL; // Ignore errors on unspecialized variations, they are always dups
  2334. if (!mHadBuildError)
  2335. mHadBuildError = true;
  2336. if (mParentModule != NULL)
  2337. mParentModule->mHadBuildError = true;
  2338. if (mCurTypeInstance != NULL)
  2339. AddFailType(mCurTypeInstance);
  2340. BfLogSysM("BfModule::Fail module %p type %p %s\n", this, mCurTypeInstance, error.c_str());
  2341. String errorString = error;
  2342. bool isWhileSpecializing = false;
  2343. bool isWhileSpecializingMethod = false;
  2344. if ((mIsSpecialModule) && (mModuleName == "vdata"))
  2345. errorString += StrFormat("\n while generating vdata for project '%s'", mProject->mName.c_str());
  2346. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend))
  2347. errorString += StrFormat("\n while generating append size calculating method");
  2348. else if (refNode == NULL)
  2349. {
  2350. if (mCurTypeInstance != NULL)
  2351. errorString += StrFormat("\n while compiling '%s'", TypeToString(mCurTypeInstance, BfTypeNameFlags_None).c_str());
  2352. else if (mProject != NULL)
  2353. errorString += StrFormat("\n while compiling project '%s'", mProject->mName.c_str());
  2354. }
  2355. if (mCurTypeInstance != NULL)
  2356. {
  2357. auto _CheckMethodInstance = [&](BfMethodInstance* methodInstance)
  2358. {
  2359. // Propogatea the fail all the way to the main method (assuming we're in a local method or lambda)
  2360. methodInstance->mHasFailed = true;
  2361. bool isSpecializedMethod = ((methodInstance != NULL) && (!methodInstance->mIsUnspecialized) && (methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mMethodGenericArguments.size() != 0));
  2362. if (isSpecializedMethod)
  2363. {
  2364. //auto unspecializedMethod = &mCurMethodInstance->mMethodInstanceGroup->mMethodSpecializationMap.begin()->second;
  2365. auto unspecializedMethod = methodInstance->mMethodInstanceGroup->mDefault;
  2366. if (unspecializedMethod->mHasFailed)
  2367. return false; // At least SOME error has already been reported
  2368. }
  2369. if (isSpecializedMethod)
  2370. {
  2371. errorString += StrFormat("\n while specializing method '%s'", MethodToString(methodInstance).c_str());
  2372. isWhileSpecializing = true;
  2373. isWhileSpecializingMethod = true;
  2374. }
  2375. else if ((methodInstance != NULL) && (methodInstance->mIsForeignMethodDef))
  2376. {
  2377. errorString += StrFormat("\n while implementing default interface method '%s'", MethodToString(methodInstance).c_str());
  2378. isWhileSpecializing = true;
  2379. isWhileSpecializingMethod = true;
  2380. }
  2381. else if ((mCurTypeInstance->IsGenericTypeInstance()) && (!mCurTypeInstance->IsUnspecializedType()))
  2382. {
  2383. errorString += StrFormat("\n while specializing type '%s'", TypeToString(mCurTypeInstance).c_str());
  2384. isWhileSpecializing = true;
  2385. }
  2386. return true;
  2387. };
  2388. if (mCurMethodState != NULL)
  2389. {
  2390. auto checkMethodState = mCurMethodState;
  2391. while (checkMethodState != NULL)
  2392. {
  2393. auto methodInstance = checkMethodState->mMethodInstance;
  2394. if (methodInstance == NULL)
  2395. {
  2396. checkMethodState = checkMethodState->mPrevMethodState;
  2397. continue;
  2398. }
  2399. if (!_CheckMethodInstance(methodInstance))
  2400. return NULL;
  2401. checkMethodState = checkMethodState->mPrevMethodState;
  2402. }
  2403. }
  2404. else if (mCurMethodInstance != NULL)
  2405. {
  2406. if (!_CheckMethodInstance(mCurMethodInstance))
  2407. return NULL;
  2408. }
  2409. // Keep in mind that all method specializations with generic type instances as its method generic params
  2410. // need to be deferred because the specified generic type instance might get deleted at the end of the
  2411. // compilation due to no longer having indirect references removed, and we have to ignore errors from
  2412. // those method specializations if that occurs
  2413. if (isWhileSpecializing)
  2414. {
  2415. BfError* bfError = mCompiler->mPassInstance->DeferFail(errorString, refNode);
  2416. if (bfError != NULL)
  2417. bfError->mIsWhileSpecializing = isWhileSpecializing;
  2418. return bfError;
  2419. }
  2420. }
  2421. if ((!isWhileSpecializing) && (mCurTypeInstance != NULL) && ((mCurTypeInstance->IsGenericTypeInstance()) && (!mCurTypeInstance->IsUnspecializedType())))
  2422. {
  2423. errorString += StrFormat("\n while specializing type '%s'", TypeToString(mCurTypeInstance).c_str());
  2424. isWhileSpecializing = true;
  2425. }
  2426. if (!mHadBuildError)
  2427. mHadBuildError = true;
  2428. // Check mixins
  2429. {
  2430. auto checkMethodInstance = mCurMethodState;
  2431. while (checkMethodInstance != NULL)
  2432. {
  2433. auto rootMixinState = checkMethodInstance->GetRootMixinState();
  2434. if (rootMixinState != NULL)
  2435. {
  2436. BfError* bfError = mCompiler->mPassInstance->Fail(StrFormat("Failed to inject mixin '%s'", MethodToString(rootMixinState->mMixinMethodInstance).c_str()), rootMixinState->mSource);
  2437. mCompiler->mPassInstance->MoreInfo(errorString, refNode);
  2438. auto mixinState = checkMethodInstance->mMixinState;
  2439. while ((mixinState != NULL) && (mixinState->mPrevMixinState != NULL))
  2440. {
  2441. mCompiler->mPassInstance->MoreInfo(StrFormat("Injected from mixin '%s'", MethodToString(mixinState->mPrevMixinState->mMixinMethodInstance).c_str()), mixinState->mSource);
  2442. mixinState = mixinState->mPrevMixinState;
  2443. }
  2444. return bfError;
  2445. }
  2446. checkMethodInstance = checkMethodInstance->mPrevMethodState;
  2447. }
  2448. }
  2449. BfError* bfError = NULL;
  2450. if (refNode == NULL)
  2451. bfError = mCompiler->mPassInstance->Fail(errorString);
  2452. else
  2453. {
  2454. bfError = mCompiler->mPassInstance->Fail(errorString, refNode);
  2455. }
  2456. if (bfError != NULL)
  2457. {
  2458. bfError->mProject = mProject;
  2459. bfError->mIsPersistent = isPersistent;
  2460. bfError->mIsWhileSpecializing = isWhileSpecializing;
  2461. if ((mCurMethodState != NULL) && (mCurMethodState->mDeferredCallEmitState != NULL) && (mCurMethodState->mDeferredCallEmitState->mCloseNode != NULL))
  2462. mCompiler->mPassInstance->MoreInfo("Error during deferred statement handling", mCurMethodState->mDeferredCallEmitState->mCloseNode);
  2463. }
  2464. return bfError;
  2465. }
  2466. BfError* BfModule::FailInternal(const StringImpl& error, BfAstNode* refNode)
  2467. {
  2468. if (mHadBuildError)
  2469. return NULL;
  2470. return Fail(error, refNode);
  2471. }
  2472. BfError* BfModule::FailAfter(const StringImpl& error, BfAstNode* refNode)
  2473. {
  2474. if (mIgnoreErrors)
  2475. return NULL;
  2476. if (refNode != NULL)
  2477. refNode = BfNodeToNonTemporary(refNode);
  2478. mHadBuildError = true;
  2479. BfError* bfError = mCompiler->mPassInstance->FailAfter(error, refNode);
  2480. if (bfError != NULL)
  2481. bfError->mProject = mProject;
  2482. return bfError;
  2483. }
  2484. BfError* BfModule::Warn(int warningNum, const StringImpl& warning, BfAstNode* refNode, bool isPersistent)
  2485. {
  2486. if (mIgnoreErrors || mIgnoreWarnings)
  2487. return NULL;
  2488. if (!mReportErrors)
  2489. {
  2490. mCompiler->mPassInstance->SilentFail();
  2491. return NULL;
  2492. }
  2493. BfAstNode* unwarnNode = refNode;
  2494. //
  2495. {
  2496. BfParentNodeEntry* parentNodeEntry = mParentNodeEntry;
  2497. while (parentNodeEntry != NULL)
  2498. {
  2499. if (auto block = BfNodeDynCast<BfBlock>(parentNodeEntry->mNode))
  2500. break;
  2501. unwarnNode = parentNodeEntry->mNode;
  2502. parentNodeEntry = parentNodeEntry->mPrev;
  2503. }
  2504. }
  2505. auto parser = unwarnNode->GetSourceData()->ToParserData();
  2506. if ((parser != NULL) && (parser->IsUnwarnedAt(unwarnNode)))
  2507. {
  2508. return NULL;
  2509. }
  2510. // Right now we're only warning on the unspecialized declarations, we may revisit this
  2511. if (mCurMethodInstance != NULL)
  2512. {
  2513. if (mCurMethodInstance->IsSpecializedGenericMethodOrType())
  2514. return NULL;
  2515. if (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend)
  2516. return NULL; // No ctorCalcAppend warnings
  2517. }
  2518. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsSpecializedType()))
  2519. return NULL;
  2520. if (refNode != NULL)
  2521. refNode = BfNodeToNonTemporary(refNode);
  2522. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2523. {
  2524. // We used to bubble up warnings into the mixin injection site, BUT
  2525. // we are now assuming any relevant warnings will be given at the declaration site
  2526. return NULL;
  2527. }
  2528. BfError* bfError;
  2529. if (refNode != NULL)
  2530. bfError = mCompiler->mPassInstance->WarnAt(warningNum, warning, refNode->GetSourceData(), refNode->GetSrcStart(), refNode->GetSrcLength());
  2531. else
  2532. bfError = mCompiler->mPassInstance->Warn(warningNum, warning);
  2533. if (bfError != NULL)
  2534. {
  2535. bfError->mProject = mProject;
  2536. AddFailType(mCurTypeInstance);
  2537. mHadBuildWarning = true;
  2538. bfError->mIsPersistent = isPersistent;
  2539. if ((mCompiler->IsAutocomplete()) && (mCompiler->mResolvePassData->mAutoComplete->CheckFixit((refNode))))
  2540. {
  2541. BfParserData* parser = refNode->GetSourceData()->ToParserData();
  2542. if (parser != NULL)
  2543. {
  2544. int fileLoc = BfFixitFinder::FindLineStartBefore(refNode);
  2545. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("fixit", StrFormat("#unwarn\tunwarn|%s|%d|#unwarn|", parser->mFileName.c_str(), fileLoc).c_str()));
  2546. if (warningNum != 0)
  2547. {
  2548. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("fixit", StrFormat("#pragma warning disable %d\t.pragma|%s|%d||#pragma warning disable %d",
  2549. warningNum, parser->mFileName.c_str(), 0, warningNum).c_str()));
  2550. }
  2551. }
  2552. }
  2553. }
  2554. return bfError;
  2555. }
  2556. void BfModule::CheckErrorAttributes(BfTypeInstance* typeInstance, BfMethodInstance* methodInstance, BfCustomAttributes* customAttributes, BfAstNode* targetSrc)
  2557. {
  2558. auto _AddDeclarationMoreInfo = [&]()
  2559. {
  2560. if (methodInstance != NULL)
  2561. {
  2562. if (methodInstance->mMethodDef->mMethodDeclaration != NULL)
  2563. mCompiler->mPassInstance->MoreInfo(
  2564. StrFormat("See method declaration '%s'", MethodToString(methodInstance).c_str()),
  2565. methodInstance->mMethodDef->GetRefNode());
  2566. }
  2567. else
  2568. {
  2569. mCompiler->mPassInstance->MoreInfo(
  2570. StrFormat("See type declaration '%s'", TypeToString(typeInstance, BfTypeNameFlag_UseUnspecializedGenericParamNames).c_str()),
  2571. typeInstance->mTypeDef->GetRefNode());
  2572. }
  2573. };
  2574. BfIRConstHolder* constHolder = typeInstance->mConstHolder;
  2575. auto customAttribute = customAttributes->Get(mCompiler->mObsoleteAttributeTypeDef);
  2576. if ((customAttribute != NULL) && (!customAttribute->mCtorArgs.IsEmpty()))
  2577. {
  2578. String err;
  2579. if (methodInstance != NULL)
  2580. err = StrFormat("'%s' is obsolete", MethodToString(methodInstance).c_str());
  2581. else
  2582. err = StrFormat("'%s' is obsolete", TypeToString(typeInstance, BfTypeNameFlag_UseUnspecializedGenericParamNames).c_str());
  2583. bool isError = false;
  2584. auto constant = constHolder->GetConstant(customAttribute->mCtorArgs[0]);
  2585. if (constant->mTypeCode == BfTypeCode_Boolean)
  2586. {
  2587. isError = constant->mBool;
  2588. }
  2589. else if (customAttribute->mCtorArgs.size() >= 2)
  2590. {
  2591. String* str = GetStringPoolString(customAttribute->mCtorArgs[0], constHolder);
  2592. if (str != NULL)
  2593. {
  2594. err += ":\n '";
  2595. err += *str;
  2596. err += "'";
  2597. }
  2598. constant = constHolder->GetConstant(customAttribute->mCtorArgs[1]);
  2599. isError = constant->mBool;
  2600. }
  2601. BfError* error = NULL;
  2602. if (isError)
  2603. error = Fail(err, targetSrc);
  2604. else
  2605. error = Warn(0, err, targetSrc);
  2606. if (error != NULL)
  2607. _AddDeclarationMoreInfo();
  2608. }
  2609. customAttribute = customAttributes->Get(mCompiler->mErrorAttributeTypeDef);
  2610. if ((customAttribute != NULL) && (!customAttribute->mCtorArgs.IsEmpty()))
  2611. {
  2612. String err;
  2613. if (methodInstance != NULL)
  2614. StrFormat("Method error: '", MethodToString(methodInstance).c_str());
  2615. else
  2616. StrFormat("Type error: '", TypeToString(typeInstance, BfTypeNameFlag_UseUnspecializedGenericParamNames).c_str());
  2617. String* str = GetStringPoolString(customAttribute->mCtorArgs[0], constHolder);
  2618. if (str != NULL)
  2619. err += *str;
  2620. err += "'";
  2621. if (Fail(err, targetSrc) != NULL)
  2622. _AddDeclarationMoreInfo();
  2623. }
  2624. customAttribute = customAttributes->Get(mCompiler->mWarnAttributeTypeDef);
  2625. if ((customAttribute != NULL) && (!customAttribute->mCtorArgs.IsEmpty()))
  2626. {
  2627. String err;
  2628. if (methodInstance != NULL)
  2629. StrFormat("Method warning: '", MethodToString(methodInstance).c_str());
  2630. else
  2631. StrFormat("Type warning: '", TypeToString(typeInstance, BfTypeNameFlag_UseUnspecializedGenericParamNames).c_str());
  2632. String* str = GetStringPoolString(customAttribute->mCtorArgs[0], constHolder);
  2633. if (str != NULL)
  2634. err += *str;
  2635. err += "'";
  2636. if (Warn(0, err, targetSrc) != NULL)
  2637. _AddDeclarationMoreInfo();
  2638. }
  2639. }
  2640. void BfModule::CheckRangeError(BfType* type, BfAstNode* refNode)
  2641. {
  2642. if (mBfIRBuilder->mOpFailed)
  2643. Fail(StrFormat("Result out of range for type '%s'", TypeToString(type).c_str()), refNode);
  2644. }
  2645. void BfModule::FatalError(const StringImpl& error, const char* file, int line)
  2646. {
  2647. static bool sHadFatalError = false;
  2648. static bool sHadReentrancy = false;
  2649. if (sHadFatalError)
  2650. {
  2651. return;
  2652. sHadReentrancy = true;
  2653. }
  2654. sHadFatalError = true;
  2655. String fullError = error;
  2656. if (file != NULL)
  2657. fullError += StrFormat(" at %s:%d", file, line);
  2658. fullError += StrFormat("\nModule: %s", mModuleName.c_str());
  2659. if (mCurTypeInstance != NULL)
  2660. fullError += StrFormat("\nType: %s", TypeToString(mCurTypeInstance).c_str());
  2661. if (mCurMethodInstance != NULL)
  2662. fullError += StrFormat("\nMethod: %s", MethodToString(mCurMethodInstance).c_str());
  2663. if ((mCurFilePosition.mFileInstance != NULL) && (mCurFilePosition.mFileInstance->mParser != NULL))
  2664. fullError += StrFormat("\nSource Location: %s:%d", mCurFilePosition.mFileInstance->mParser->mFileName.c_str(), mCurFilePosition.mCurLine + 1);
  2665. if (sHadReentrancy)
  2666. fullError += "\nError had reentrancy";
  2667. BfpSystem_FatalError(fullError.c_str(), "FATAL MODULE ERROR");
  2668. }
  2669. void BfModule::NotImpl(BfAstNode* astNode)
  2670. {
  2671. Fail("INTERNAL ERROR: Not implemented", astNode);
  2672. }
  2673. bool BfModule::CheckAccessMemberProtection(BfProtection protection, BfTypeInstance* memberType)
  2674. {
  2675. bool allowPrivate = (memberType == mCurTypeInstance) || (IsInnerType(mCurTypeInstance, memberType));
  2676. if (!allowPrivate)
  2677. allowPrivate |= memberType->IsInterface();
  2678. bool allowProtected = allowPrivate;
  2679. //TODO: We had this commented out, but this makes accessing protected properties fail
  2680. if (mCurTypeInstance != NULL)
  2681. allowProtected |= TypeIsSubTypeOf(mCurTypeInstance, memberType->ToTypeInstance());
  2682. if (!CheckProtection(protection, memberType->mTypeDef, allowProtected, allowPrivate))
  2683. {
  2684. return false;
  2685. }
  2686. return true;
  2687. }
  2688. bool BfModule::CheckDefineMemberProtection(BfProtection protection, BfType* memberType)
  2689. {
  2690. // Use 'min' - exporting a 'public' from a 'private' class is really just 'private' still
  2691. protection = std::min(protection, mCurTypeInstance->mTypeDef->mProtection);
  2692. auto memberTypeInstance = memberType->ToTypeInstance();
  2693. if (memberTypeInstance == NULL)
  2694. {
  2695. auto underlyingType = memberType->GetUnderlyingType();
  2696. if (underlyingType != NULL)
  2697. return CheckDefineMemberProtection(protection, underlyingType);
  2698. return true;
  2699. }
  2700. if (memberTypeInstance->mTypeDef->mProtection < protection)
  2701. return false;
  2702. if (memberTypeInstance->IsGenericTypeInstance())
  2703. {
  2704. // When we're a generic struct, our data layout can depend on our generic parameters as well
  2705. auto genericTypeInstance = (BfTypeInstance*) memberTypeInstance;
  2706. for (auto typeGenericArg : genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments)
  2707. {
  2708. if (!CheckDefineMemberProtection(protection, typeGenericArg))
  2709. return false;
  2710. }
  2711. }
  2712. return true;
  2713. }
  2714. void BfModule::AddDependency(BfType* usedType, BfType* userType, BfDependencyMap::DependencyFlags flags)
  2715. {
  2716. if (usedType == userType)
  2717. return;
  2718. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsAutocompleteMethod))
  2719. {
  2720. if (userType->IsMethodRef())
  2721. {
  2722. // We cannot short-circuit dependencies because of method group ref counting
  2723. }
  2724. else
  2725. return;
  2726. }
  2727. if (usedType->IsSpecializedByAutoCompleteMethod())
  2728. return;
  2729. // if (usedType->IsBoxed())
  2730. // {
  2731. // NOP;
  2732. // auto underlyingType = usedType->GetUnderlyingType()->ToTypeInstance();
  2733. // if ((underlyingType != NULL) && (underlyingType->IsInstanceOf(mCompiler->mSizedArrayTypeDef)))
  2734. // {
  2735. // BfLogSysM("AddDependency UsedType:%p UserType:%p Method:%p\n", usedType, userType, mCurMethodInstance);
  2736. // }
  2737. // }
  2738. // TODO: It seems this was bogus - it kept the root array from being marked as a dependency (for example)
  2739. // BfType* origUsedType = usedType;
  2740. bool isDataAccess = ((flags & (BfDependencyMap::DependencyFlag_ReadFields | BfDependencyMap::DependencyFlag_LocalUsage | BfDependencyMap::DependencyFlag_Allocates)) != 0);
  2741. // if (isDataAccess)
  2742. // {
  2743. // while (true)
  2744. // {
  2745. // if ((usedType->IsPointer()) || (usedType->IsRef()) || (usedType->IsSizedArray()))
  2746. // usedType = usedType->GetUnderlyingType();
  2747. // else if (usedType->IsArray())
  2748. // {
  2749. // usedType = ((BfTypeInstance*)usedType)->mGenericTypeInfo->mTypeGenericArguments[0];
  2750. // }
  2751. // else
  2752. // break;
  2753. // }
  2754. // }
  2755. if ((mCurMethodState != NULL) && (mCurMethodState->mHotDataReferenceBuilder != NULL) && (usedType != mCurTypeInstance) && (isDataAccess))
  2756. {
  2757. bool addType = true;
  2758. auto checkType = usedType;
  2759. PopulateType(checkType, BfPopulateType_Data);
  2760. if (checkType->IsValuelessType())
  2761. addType = false;
  2762. else if (checkType->IsPrimitiveType())
  2763. addType = false;
  2764. else
  2765. {
  2766. auto checkTypeInst = checkType->ToTypeInstance();
  2767. if (checkTypeInst == NULL)
  2768. {
  2769. addType = false;
  2770. }
  2771. else
  2772. {
  2773. if (TypeIsSubTypeOf(mCurTypeInstance, checkTypeInst))
  2774. addType = false;
  2775. }
  2776. }
  2777. if (addType)
  2778. {
  2779. auto checkTypeInst = checkType->ToTypeInstance();
  2780. auto hotTypeVersion = checkTypeInst->mHotTypeData->GetLatestVersion();
  2781. BF_ASSERT(hotTypeVersion != NULL);
  2782. bool isAllocation = ((flags & BfDependencyMap::DependencyFlag_Allocates) != 0);
  2783. if (((flags & BfDependencyMap::DependencyFlag_LocalUsage) != 0) &&
  2784. (checkType->IsComposite()))
  2785. isAllocation = true;
  2786. if (isAllocation)
  2787. {
  2788. mCurMethodState->mHotDataReferenceBuilder->mAllocatedData.Add(hotTypeVersion);
  2789. }
  2790. else
  2791. mCurMethodState->mHotDataReferenceBuilder->mUsedData.Add(hotTypeVersion);
  2792. }
  2793. }
  2794. if ((!mCompiler->mIsResolveOnly) && (mIsReified))
  2795. {
  2796. auto usingModule = userType->GetModule();
  2797. BfModule* usedModule;
  2798. if (usedType->IsFunction())
  2799. {
  2800. auto typeInst = usedType->ToTypeInstance();
  2801. if (typeInst->mBaseType == NULL)
  2802. PopulateType(typeInst);
  2803. usedModule = typeInst->mBaseType->GetModule();
  2804. }
  2805. else
  2806. usedModule = usedType->GetModule();
  2807. if ((usingModule != NULL) && (!usingModule->mIsSpecialModule) &&
  2808. (usedModule != NULL) && (!usedModule->mIsSpecialModule))
  2809. {
  2810. usingModule->mModuleRefs.Add(usedModule);
  2811. }
  2812. }
  2813. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodInfoEx != NULL) && (flags != BfDependencyMap::DependencyFlag_MethodGenericArg))
  2814. {
  2815. // When we are specializing a method, usage of that specialized type is already handled with DependencyFlag_MethodGenericArg
  2816. for (auto genericArg : mCurMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  2817. if (genericArg == usedType)
  2818. return;
  2819. }
  2820. auto depFlag = flags;
  2821. if ((flags & (BfDependencyMap::DependencyFlag_MethodGenericArg | BfDependencyMap::DependencyFlag_TypeGenericArg)) != 0)
  2822. depFlag = BfDependencyMap::DependencyFlag_GenericArgRef; // Will cause a rebuild but not an outright deletion of the type
  2823. auto underlyingType = usedType->GetUnderlyingType();
  2824. if (underlyingType != NULL)
  2825. AddDependency(underlyingType, userType, depFlag);
  2826. BfDependedType* checkDType = usedType->ToDependedType();
  2827. if (checkDType == NULL)
  2828. return;
  2829. if ((usedType->mRebuildFlags & BfTypeRebuildFlag_AwaitingReference) != 0)
  2830. mContext->MarkAsReferenced(checkDType);
  2831. if (!checkDType->mDependencyMap.AddUsedBy(userType, flags))
  2832. return;
  2833. if (checkDType->IsGenericTypeInstance())
  2834. {
  2835. auto genericTypeInstance = (BfTypeInstance*) checkDType;
  2836. for (auto genericArg : genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments)
  2837. {
  2838. AddDependency(genericArg, userType, depFlag);
  2839. }
  2840. }
  2841. if (checkDType->IsTuple())
  2842. {
  2843. for (auto& field : checkDType->ToTypeInstance()->mFieldInstances)
  2844. {
  2845. if (field.mDataIdx != -1)
  2846. AddDependency(field.mResolvedType, userType, depFlag);
  2847. }
  2848. }
  2849. }
  2850. void BfModule::AddCallDependency(BfMethodInstance* methodInstance, bool devirtualized)
  2851. {
  2852. if ((mCurMethodState != NULL) && (mCurMethodState->mHotDataReferenceBuilder != NULL))
  2853. {
  2854. if (methodInstance->mHotMethod == NULL)
  2855. CheckHotMethod(methodInstance, "");
  2856. BF_ASSERT(methodInstance->mHotMethod != NULL);
  2857. if (devirtualized)
  2858. mCurMethodState->mHotDataReferenceBuilder->mDevirtualizedCalledMethods.Add(methodInstance->mHotMethod);
  2859. else
  2860. mCurMethodState->mHotDataReferenceBuilder->mCalledMethods.Add(methodInstance->mHotMethod);
  2861. }
  2862. }
  2863. bool BfModule::IsAttribute(BfTypeInstance* typeInst)
  2864. {
  2865. auto checkTypeInst = typeInst;
  2866. while (checkTypeInst != NULL)
  2867. {
  2868. if (checkTypeInst->mTypeDef == mCompiler->mAttributeTypeDef)
  2869. return true;
  2870. checkTypeInst = checkTypeInst->mBaseType;
  2871. }
  2872. return false;
  2873. }
  2874. void BfModule::PopulateGlobalContainersList(const BfGlobalLookup& globalLookup)
  2875. {
  2876. if (mContext->mCurTypeState == NULL)
  2877. return;
  2878. BP_ZONE("PopulateGlobalContainersList");
  2879. BfTypeDef* userTypeDef = mContext->mCurTypeState->mCurTypeDef;
  2880. if ((userTypeDef == NULL) && (mCurMethodInstance != NULL))
  2881. userTypeDef = mCurMethodInstance->mMethodDef->mDeclaringType;
  2882. if (userTypeDef == NULL)
  2883. userTypeDef = mCurTypeInstance->mTypeDef;
  2884. if (mContext->mCurTypeState->mGlobalContainerCurUserTypeDef != userTypeDef)
  2885. {
  2886. mContext->mCurTypeState->mGlobalContainers.Clear();
  2887. for (int namespaceIdx = -1; namespaceIdx < (int)userTypeDef->mNamespaceSearch.size(); namespaceIdx++)
  2888. {
  2889. BfAtomComposite findStr;
  2890. if (namespaceIdx != -1)
  2891. findStr.Reference(userTypeDef->mNamespaceSearch[namespaceIdx]);
  2892. auto typeDefItr = mSystem->mTypeDefs.TryGet(findStr);
  2893. while (typeDefItr)
  2894. {
  2895. auto typeDef = *typeDefItr;
  2896. if ((typeDef->mFullName == findStr) && (typeDef->mIsCombinedPartial) && (typeDef->IsGlobalsContainer()))
  2897. {
  2898. if (typeDef->mProject->ContainsReference(typeDef->mProject))
  2899. {
  2900. BfGlobalContainerEntry globalEntry;
  2901. globalEntry.mTypeDef = typeDef;
  2902. globalEntry.mTypeInst = NULL;
  2903. typeDef->PopulateMemberSets();
  2904. mContext->mCurTypeState->mGlobalContainers.Add(globalEntry);
  2905. }
  2906. }
  2907. else if (!typeDef->mIsPartial)
  2908. {
  2909. //break;
  2910. }
  2911. typeDefItr.MoveToNextHashMatch();
  2912. }
  2913. }
  2914. mContext->mCurTypeState->mGlobalContainerCurUserTypeDef = userTypeDef;
  2915. }
  2916. // Only create actual typeInst when we have an applicable member. This helps in keeping unused globals from
  2917. // reifing types
  2918. for (auto& globalEntry : mContext->mCurTypeState->mGlobalContainers)
  2919. {
  2920. if (globalEntry.mTypeInst == NULL)
  2921. {
  2922. bool include = false;
  2923. if (globalLookup.mKind == BfGlobalLookup::Kind_All)
  2924. include = true;
  2925. else if (globalLookup.mKind == BfGlobalLookup::Kind_Field)
  2926. {
  2927. if (globalEntry.mTypeDef->mFieldSet.ContainsWith(globalLookup.mName))
  2928. include = true;
  2929. if (globalEntry.mTypeDef->mPropertySet.ContainsWith(globalLookup.mName))
  2930. include = true;
  2931. }
  2932. else if (globalLookup.mKind == BfGlobalLookup::Kind_Method)
  2933. {
  2934. if (globalEntry.mTypeDef->mMethodSet.ContainsWith(globalLookup.mName))
  2935. include = true;
  2936. }
  2937. if (include)
  2938. {
  2939. auto type = ResolveTypeDef(globalEntry.mTypeDef);
  2940. if (type != NULL)
  2941. globalEntry.mTypeInst = type->ToTypeInstance();
  2942. }
  2943. }
  2944. }
  2945. }
  2946. BfStaticSearch* BfModule::GetStaticSearch()
  2947. {
  2948. auto activeTypeDef = GetActiveTypeDef();
  2949. BfStaticSearch* staticSearch = NULL;
  2950. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->mStaticSearchMap.TryGetValue(activeTypeDef, &staticSearch)))
  2951. return staticSearch;
  2952. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mStaticSearchMap.TryGetValue(activeTypeDef, &staticSearch)))
  2953. return staticSearch;
  2954. return NULL;
  2955. }
  2956. BfInternalAccessSet* BfModule::GetInternalAccessSet()
  2957. {
  2958. auto activeTypeDef = GetActiveTypeDef();
  2959. BfInternalAccessSet* internalAccessSet = NULL;
  2960. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->mInternalAccessMap.TryGetValue(activeTypeDef, &internalAccessSet)))
  2961. return internalAccessSet;
  2962. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mInternalAccessMap.TryGetValue(activeTypeDef, &internalAccessSet)))
  2963. return internalAccessSet;
  2964. return NULL;
  2965. }
  2966. bool BfModule::CheckInternalProtection(BfTypeDef* usingTypeDef)
  2967. {
  2968. auto internalAccessSet = GetInternalAccessSet();
  2969. if (internalAccessSet == NULL)
  2970. return false;
  2971. for (auto& nameComposite : internalAccessSet->mNamespaces)
  2972. {
  2973. if (usingTypeDef->mNamespace.StartsWith(nameComposite))
  2974. return true;
  2975. }
  2976. for (auto internalType : internalAccessSet->mTypes)
  2977. {
  2978. auto checkTypeDef = usingTypeDef;
  2979. while (checkTypeDef != NULL)
  2980. {
  2981. if (checkTypeDef == internalType->mTypeDef)
  2982. return true;
  2983. checkTypeDef = checkTypeDef->mOuterType;
  2984. }
  2985. }
  2986. return false;
  2987. }
  2988. void PrintUsers(llvm::MDNode* md);
  2989. BfModuleOptions BfModule::GetModuleOptions()
  2990. {
  2991. if (mIsScratchModule)
  2992. return BfModuleOptions();
  2993. if (mModuleOptions != NULL)
  2994. return *mModuleOptions;
  2995. BfModuleOptions moduleOptions;
  2996. moduleOptions.mEmitDebugInfo = mCompiler->mOptions.mEmitDebugInfo ? 1 : mCompiler->mOptions.mEmitLineInfo ? 2 : 0;
  2997. if (mProject != NULL)
  2998. {
  2999. moduleOptions.mSIMDSetting = mProject->mCodeGenOptions.mSIMDSetting;
  3000. moduleOptions.mOptLevel = mProject->mCodeGenOptions.mOptLevel;
  3001. }
  3002. auto headModule = this;
  3003. while (headModule->mParentModule != NULL)
  3004. headModule = headModule->mParentModule;
  3005. BF_ASSERT((headModule->mOwnedTypeInstances.size() > 0) || (mModuleName == "vdata"));
  3006. if (headModule->mOwnedTypeInstances.size() > 0)
  3007. {
  3008. auto typeInst = headModule->mOwnedTypeInstances[0];
  3009. PopulateType(typeInst);
  3010. if (typeInst->mTypeOptionsIdx != -1)
  3011. {
  3012. auto typeOptions = mSystem->GetTypeOptions(typeInst->mTypeOptionsIdx);
  3013. moduleOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)moduleOptions.mSIMDSetting, typeOptions->mSIMDSetting);
  3014. moduleOptions.mEmitDebugInfo = BfTypeOptions::Apply(moduleOptions.mEmitDebugInfo, typeOptions->mEmitDebugInfo);
  3015. moduleOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)moduleOptions.mOptLevel, (int)typeOptions->mOptimizationLevel);
  3016. }
  3017. }
  3018. return moduleOptions;
  3019. }
  3020. BfCheckedKind BfModule::GetDefaultCheckedKind()
  3021. {
  3022. if ((mCurMethodState != NULL) && (mCurMethodState->mDisableChecks))
  3023. return BfCheckedKind_Unchecked;
  3024. bool runtimeChecks = mCompiler->mOptions.mRuntimeChecks;
  3025. auto typeOptions = GetTypeOptions();
  3026. if (typeOptions != NULL)
  3027. runtimeChecks = typeOptions->Apply(runtimeChecks, BfOptionFlags_RuntimeChecks);
  3028. return runtimeChecks ? BfCheckedKind_Checked : BfCheckedKind_Unchecked;
  3029. }
  3030. void BfModule::AddFailType(BfTypeInstance* typeInstance)
  3031. {
  3032. BF_ASSERT(typeInstance != NULL);
  3033. mContext->mFailTypes.Add(typeInstance);
  3034. }
  3035. void BfModule::CheckAddFailType()
  3036. {
  3037. //TODO: We removed this line, because failures in resolve-only generic method can occur in non-owning modules
  3038. // but we still need to add the owning type to the FailTypes list
  3039. //.. OLD:
  3040. // While we're inlining, it's possible that mCurTypeInstance belongs to another module, ignore it
  3041. /*if (mCurTypeInstance->mModule != this)
  3042. return;*/
  3043. // Using mHadBuildWarning to insert into mFailTypes is our core of our strategy for reasserting
  3044. // warnings on rebuilds where otherwise the warnings wouldn't be generated because no code was
  3045. // being recompiled. This forces types with warnings to be recompiled.
  3046. // We had this 'mIsResolveOnly' check for speed in resolveOnly, but we removed it so the IDE can be
  3047. // constantly warning-aware
  3048. if ((mHadBuildError) ||
  3049. (mHadBuildWarning /*&& !mCompiler->mIsResolveOnly*/))
  3050. {
  3051. //mContext->mFailTypes.Add(mCurTypeInstance);
  3052. }
  3053. }
  3054. void BfModule::MarkDerivedDirty(BfTypeInstance* typeInst)
  3055. {
  3056. if (!mCompiler->IsHotCompile())
  3057. return;
  3058. typeInst->mDirty = true;
  3059. for (auto& dep : typeInst->mDependencyMap)
  3060. {
  3061. auto depType = dep.mKey;
  3062. auto depFlags = dep.mValue.mFlags;
  3063. if ((depFlags & BfDependencyMap::DependencyFlag_DerivedFrom) != 0)
  3064. {
  3065. MarkDerivedDirty(depType->ToTypeInstance());
  3066. }
  3067. }
  3068. }
  3069. void BfModule::CreateStaticField(BfFieldInstance* fieldInstance, bool isThreadLocal)
  3070. {
  3071. auto fieldType = fieldInstance->GetResolvedType();
  3072. auto field = fieldInstance->GetFieldDef();
  3073. if (fieldType->IsVar())
  3074. return;
  3075. BfIRValue initValue;
  3076. if (field->mIsConst)
  3077. {
  3078. if (fieldType->IsPointer())
  3079. fieldType = fieldType->GetUnderlyingType();
  3080. }
  3081. BfIRStorageKind storageKind = BfIRStorageKind_Normal;
  3082. if ((fieldInstance->mCustomAttributes != NULL) && (fieldInstance->mCustomAttributes->Get(mCompiler->mExportAttributeTypeDef)))
  3083. storageKind = BfIRStorageKind_Export;
  3084. else if ((fieldInstance->mCustomAttributes != NULL) && (fieldInstance->mCustomAttributes->Get(mCompiler->mImportAttributeTypeDef)))
  3085. storageKind = BfIRStorageKind_Import;
  3086. if ((!field->mIsExtern) && (storageKind != BfIRStorageKind_Import))
  3087. initValue = GetDefaultValue(fieldType);
  3088. if (fieldInstance->mOwner->IsUnspecializedType())
  3089. {
  3090. // Placeholder
  3091. auto ptrVal = CreatePointerType(fieldType);
  3092. mStaticFieldRefs[fieldInstance] = GetDefaultValue(ptrVal);
  3093. }
  3094. else
  3095. {
  3096. BfLogSysM("Creating static field Module:%p Type:%p\n", this, fieldType);
  3097. StringT<128> staticVarName;
  3098. BfMangler::Mangle(staticVarName, mCompiler->GetMangleKind(), fieldInstance);
  3099. if ((!fieldType->IsValuelessType()) && (!staticVarName.StartsWith("#")))
  3100. {
  3101. BfIRValue globalVar = mBfIRBuilder->CreateGlobalVariable(
  3102. mBfIRBuilder->MapType(fieldType, BfIRPopulateType_Eventually_Full),
  3103. false,
  3104. BfIRLinkageType_External,
  3105. initValue,
  3106. staticVarName,
  3107. isThreadLocal);
  3108. mBfIRBuilder->GlobalVar_SetAlignment(globalVar, fieldType->mAlign);
  3109. if (storageKind != BfIRStorageKind_Normal)
  3110. mBfIRBuilder->GlobalVar_SetStorageKind(globalVar, storageKind);
  3111. BF_ASSERT(globalVar);
  3112. mStaticFieldRefs[fieldInstance] = globalVar;
  3113. }
  3114. }
  3115. }
  3116. void BfModule::ResolveConstField(BfTypeInstance* typeInstance, BfFieldInstance* fieldInstance, BfFieldDef* fieldDef, bool forceResolve)
  3117. {
  3118. bool autoCompleteOnly = mCompiler->IsAutocomplete();
  3119. BfType* fieldType = NULL;
  3120. if (fieldInstance != NULL)
  3121. {
  3122. fieldType = fieldInstance->GetResolvedType();
  3123. if (fieldType == NULL)
  3124. fieldType = ResolveTypeRef(fieldDef->mTypeRef);
  3125. }
  3126. else
  3127. {
  3128. BF_ASSERT(mCompiler->IsAutocomplete());
  3129. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3130. if ((typeInstance->IsEnum()) && (fieldDef->mTypeRef == NULL))
  3131. {
  3132. fieldType = typeInstance;
  3133. }
  3134. else
  3135. {
  3136. auto isLet = (fieldDef->mTypeRef != NULL) && (fieldDef->mTypeRef->IsExact<BfLetTypeReference>());
  3137. auto isVar = (fieldDef->mTypeRef != NULL) && (fieldDef->mTypeRef->IsExact<BfVarTypeReference>());
  3138. if (isLet || isVar)
  3139. fieldType = GetPrimitiveType(BfTypeCode_Var);
  3140. else
  3141. fieldType = ResolveTypeRef(fieldDef->mTypeRef);
  3142. if (fieldType == NULL)
  3143. fieldType = mContext->mBfObjectType;
  3144. }
  3145. }
  3146. if ((fieldInstance != NULL) && (fieldInstance->mConstIdx != -1) && (!forceResolve))
  3147. return;
  3148. if (mContext->mFieldResolveReentrys.size() > 1)
  3149. {
  3150. if (mContext->mFieldResolveReentrys.IndexOf(fieldInstance, 1) != -1)
  3151. {
  3152. String failStr = "Circular data reference detected between the following fields:";
  3153. for (int i = 1; i < (int)mContext->mFieldResolveReentrys.size(); i++)
  3154. {
  3155. if (i > 1)
  3156. failStr += ",";
  3157. failStr += "\n '" + TypeToString(typeInstance) + "." + mContext->mFieldResolveReentrys[i]->GetFieldDef()->mName + "'";
  3158. }
  3159. BfError* err = Fail(failStr, fieldDef->mFieldDeclaration);
  3160. if (err)
  3161. err->mIsPersistent = true;
  3162. return;
  3163. }
  3164. }
  3165. mContext->mFieldResolveReentrys.push_back(fieldInstance);
  3166. AutoPopBack<decltype (mContext->mFieldResolveReentrys)> popTypeResolveReentry(&mContext->mFieldResolveReentrys);
  3167. if (fieldInstance == NULL)
  3168. popTypeResolveReentry.Pop();
  3169. auto typeDef = typeInstance->mTypeDef;
  3170. BfIRValue constValue;
  3171. if (fieldDef->mIsExtern)
  3172. {
  3173. if (!fieldDef->mTypeRef->IsA<BfPointerTypeRef>())
  3174. {
  3175. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3176. Fail("Extern consts must be pointer types", fieldDef->mFieldDeclaration->mTypeRef);
  3177. }
  3178. if (fieldDef->mInitializer != NULL)
  3179. {
  3180. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3181. Fail("Extern consts cannot have initializers", fieldDef->mFieldDeclaration->mNameNode);
  3182. }
  3183. }
  3184. else if (fieldDef->mInitializer == NULL)
  3185. {
  3186. if (fieldDef->IsEnumCaseEntry())
  3187. {
  3188. if (typeInstance->IsTypedPrimitive())
  3189. {
  3190. BfFieldInstance* prevFieldInstance = NULL;
  3191. for (int i = fieldDef->mIdx - 1; i >= 0; i--)
  3192. {
  3193. BfFieldInstance* checkFieldInst = &typeInstance->mFieldInstances[i];
  3194. if (checkFieldInst->GetFieldDef()->IsEnumCaseEntry())
  3195. {
  3196. prevFieldInstance = checkFieldInst;
  3197. break;
  3198. }
  3199. }
  3200. if (prevFieldInstance == NULL)
  3201. constValue = GetConstValue(0, typeInstance);
  3202. else
  3203. {
  3204. ResolveConstField(typeInstance, prevFieldInstance, prevFieldInstance->GetFieldDef());
  3205. if (prevFieldInstance->mConstIdx == -1)
  3206. {
  3207. if (!mCompiler->IsAutocomplete())
  3208. AssertErrorState();
  3209. constValue = GetConstValue(0, typeInstance);
  3210. }
  3211. else
  3212. {
  3213. auto prevConstant = ConstantToCurrent(typeInstance->mConstHolder->GetConstantById(prevFieldInstance->mConstIdx), typeInstance->mConstHolder, typeInstance);
  3214. constValue = mBfIRBuilder->CreateAdd(prevConstant, GetConstValue(1, typeInstance));
  3215. }
  3216. }
  3217. }
  3218. }
  3219. else
  3220. {
  3221. Fail("Const requires initializer", fieldDef->mFieldDeclaration->mNameNode);
  3222. }
  3223. }
  3224. else if (mBfIRBuilder != NULL)
  3225. {
  3226. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3227. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  3228. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL);
  3229. BfMethodState methodState;
  3230. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  3231. methodState.mTempKind = BfMethodState::TempKind_Static;
  3232. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  3233. if (fieldType->IsVar())
  3234. {
  3235. auto initValue = GetFieldInitializerValue(fieldInstance, fieldDef->mInitializer, fieldDef, fieldType);
  3236. if (!initValue)
  3237. {
  3238. AssertErrorState();
  3239. initValue = GetDefaultTypedValue(mContext->mBfObjectType);
  3240. }
  3241. if (fieldInstance != NULL)
  3242. {
  3243. fieldInstance->mResolvedType = initValue.mType;
  3244. }
  3245. constValue = initValue.mValue;
  3246. }
  3247. else
  3248. {
  3249. auto uncastedInitValue = GetFieldInitializerValue(fieldInstance, fieldDef->mInitializer, fieldDef, fieldType);
  3250. constValue = uncastedInitValue.mValue;
  3251. }
  3252. if ((mCurTypeInstance->IsPayloadEnum()) && (fieldDef->IsEnumCaseEntry()))
  3253. {
  3254. // Illegal
  3255. constValue = BfIRValue();
  3256. }
  3257. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  3258. }
  3259. if (fieldInstance != NULL)
  3260. {
  3261. fieldType = fieldInstance->GetResolvedType();
  3262. if ((fieldType == NULL) || (fieldType->IsVar()))
  3263. {
  3264. AssertErrorState();
  3265. // Default const type is 'int'
  3266. BfTypedValue initValue = GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr));
  3267. if (fieldInstance != NULL)
  3268. {
  3269. fieldInstance->mResolvedType = initValue.mType;
  3270. }
  3271. constValue = initValue.mValue;
  3272. }
  3273. if ((constValue) && (fieldInstance->mConstIdx == -1))
  3274. {
  3275. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3276. CurrentAddToConstHolder(constValue);
  3277. fieldInstance->mConstIdx = constValue.mId;
  3278. }
  3279. }
  3280. }
  3281. BfType* BfModule::ResolveVarFieldType(BfTypeInstance* typeInstance, BfFieldInstance* fieldInstance, BfFieldDef* field)
  3282. {
  3283. bool isDeclType = BfNodeDynCastExact<BfDeclTypeRef>(field->mFieldDeclaration->mTypeRef) != NULL;
  3284. auto fieldType = fieldInstance->GetResolvedType();
  3285. if ((field->mIsConst) && (!isDeclType))
  3286. {
  3287. ResolveConstField(typeInstance, fieldInstance, field);
  3288. return fieldInstance->GetResolvedType();
  3289. }
  3290. bool staticOnly = (field->mIsStatic) && (!isDeclType);
  3291. if (!fieldInstance->mIsInferredType)
  3292. return fieldType;
  3293. if (!fieldType->IsVar())
  3294. return fieldType;
  3295. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3296. BfTypeState typeState(mCurTypeInstance, mContext->mCurTypeState);
  3297. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState, mContext->mCurTypeState->mTypeInstance != typeInstance);
  3298. auto typeDef = typeInstance->mTypeDef;
  3299. if ((!field->mIsStatic) && (typeDef->mIsStatic))
  3300. {
  3301. AssertErrorState();
  3302. return GetPrimitiveType(BfTypeCode_Var);
  3303. }
  3304. bool hadInferenceCycle = false;
  3305. if (mContext->mFieldResolveReentrys.size() > 1)
  3306. {
  3307. if (mContext->mFieldResolveReentrys.IndexOf(fieldInstance, 1) != -1)
  3308. {
  3309. for (int i = 1; i < (int)mContext->mFieldResolveReentrys.size(); i++)
  3310. {
  3311. auto fieldInst = mContext->mFieldResolveReentrys[i];
  3312. auto fieldDef = fieldInst->GetFieldDef();
  3313. auto fieldOwner = fieldInst->mOwner;
  3314. auto fieldModule = fieldOwner->mModule;
  3315. SetAndRestoreValue<bool> prevIgnoreError(fieldModule->mIgnoreErrors, false);
  3316. fieldModule->Fail(StrFormat("Field '%s.%s' creates a type inference cycle", TypeToString(fieldOwner).c_str(), fieldDef->mName.c_str()), fieldDef->mTypeRef, true);
  3317. }
  3318. return GetPrimitiveType(BfTypeCode_Var);
  3319. }
  3320. }
  3321. mContext->mFieldResolveReentrys.push_back(fieldInstance);
  3322. AutoPopBack<decltype (mContext->mFieldResolveReentrys)> popTypeResolveReentry(&mContext->mFieldResolveReentrys);
  3323. SetAndRestoreValue<bool> prevResolvingVar(typeInstance->mResolvingVarField, true);
  3324. SetAndRestoreValue<bool> prevCtxResolvingVar(mContext->mResolvingVarField, true);
  3325. if ((field->mInitializer == NULL) && (!isDeclType))
  3326. {
  3327. if ((field->mTypeRef->IsA<BfVarTypeReference>()) || (field->mTypeRef->IsA<BfLetTypeReference>()))
  3328. Fail("Implicitly-typed fields must be initialized", field->GetRefNode());
  3329. return GetPrimitiveType(BfTypeCode_Var);
  3330. }
  3331. BfType* resolvedType = NULL;
  3332. if (!hadInferenceCycle)
  3333. {
  3334. BfTypeState typeState;
  3335. typeState.mPrevState = mContext->mCurTypeState;
  3336. typeState.mTypeInstance = typeInstance;
  3337. typeState.mCurFieldDef = field;
  3338. typeState.mResolveKind = BfTypeState::ResolveKind_ResolvingVarType;
  3339. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  3340. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  3341. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL/*ctorMethod.mMethodInstance*/);
  3342. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  3343. BfMethodState methodState;
  3344. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  3345. methodState.mTempKind = staticOnly ? BfMethodState::TempKind_Static : BfMethodState::TempKind_NonStatic;
  3346. if (!staticOnly)
  3347. {
  3348. //BfLocalVariable localVar;
  3349. //methodState.mLocals.push_back(localVar);
  3350. }
  3351. if (isDeclType)
  3352. {
  3353. auto fieldDef = fieldInstance->GetFieldDef();
  3354. resolvedType = ResolveTypeRef(fieldDef->mTypeRef, BfPopulateType_Identity);
  3355. }
  3356. else
  3357. {
  3358. BfTypedValue valueFromExpr;
  3359. valueFromExpr = GetFieldInitializerValue(fieldInstance);
  3360. FixIntUnknown(valueFromExpr);
  3361. resolvedType = valueFromExpr.mType;
  3362. }
  3363. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  3364. }
  3365. if (resolvedType == NULL)
  3366. return GetPrimitiveType(BfTypeCode_Var);
  3367. fieldInstance->SetResolvedType(resolvedType);
  3368. if (field->mIsStatic)
  3369. {
  3370. }
  3371. else if (fieldInstance->mDataIdx >= 0)
  3372. {
  3373. }
  3374. else
  3375. {
  3376. BF_ASSERT(typeInstance->IsIncomplete());
  3377. }
  3378. return resolvedType;
  3379. }
  3380. void BfModule::MarkFieldInitialized(BfFieldInstance* fieldInstance)
  3381. {
  3382. BF_ASSERT(fieldInstance->mOwner == mCurTypeInstance);
  3383. auto fieldType = fieldInstance->GetResolvedType();
  3384. if ((fieldInstance->mMergedDataIdx != -1) && (mCurMethodState != NULL))
  3385. {
  3386. int fieldIdx = 0;
  3387. int fieldCount = 0;
  3388. fieldInstance->GetDataRange(fieldIdx, fieldCount);
  3389. fieldIdx--;
  3390. int count = fieldCount;
  3391. if (fieldIdx == -1)
  3392. count = 1;
  3393. //TODO: Under what circumstances could 'thisVariable' be NULL?
  3394. auto thisVariable = GetThisVariable();
  3395. if (thisVariable != NULL)
  3396. {
  3397. for (int i = 0; i < count; i++)
  3398. mCurMethodState->LocalDefined(thisVariable, fieldIdx + i);
  3399. }
  3400. }
  3401. }
  3402. bool BfModule::IsThreadLocal(BfFieldInstance * fieldInstance)
  3403. {
  3404. if (fieldInstance->mCustomAttributes == NULL)
  3405. return false;
  3406. auto fieldDef = fieldInstance->GetFieldDef();
  3407. if (!fieldDef->mIsStatic)
  3408. return false;
  3409. bool isThreadLocal = false;
  3410. if (fieldInstance->mCustomAttributes != NULL)
  3411. {
  3412. for (auto customAttr : fieldInstance->mCustomAttributes->mAttributes)
  3413. {
  3414. if (customAttr.mType->ToTypeInstance()->mTypeDef == mCompiler->mThreadStaticAttributeTypeDef)
  3415. return true;
  3416. }
  3417. }
  3418. return false;
  3419. }
  3420. BfTypedValue BfModule::GetFieldInitializerValue(BfFieldInstance* fieldInstance, BfExpression* initializer, BfFieldDef* fieldDef, BfType* fieldType, bool doStore)
  3421. {
  3422. if (fieldDef == NULL)
  3423. fieldDef = fieldInstance->GetFieldDef();
  3424. if (fieldType == NULL)
  3425. fieldType = fieldInstance->GetResolvedType();
  3426. if (initializer == NULL)
  3427. {
  3428. if (fieldDef == NULL)
  3429. return BfTypedValue();
  3430. initializer = fieldDef->mInitializer;
  3431. }
  3432. BfTypedValue staticVarRef;
  3433. BfTypedValue result;
  3434. if (initializer == NULL)
  3435. {
  3436. result = GetDefaultTypedValue(fieldInstance->mResolvedType);
  3437. }
  3438. else
  3439. {
  3440. if ((mCompiler->mIsResolveOnly) && (mCompiler->mResolvePassData->mSourceClassifier != NULL) && (initializer->IsFromParser(mCompiler->mResolvePassData->mParser)))
  3441. {
  3442. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(initializer, BfSourceElementType_Normal);
  3443. mCompiler->mResolvePassData->mSourceClassifier->VisitChildNoRef(initializer);
  3444. }
  3445. if ((mCurTypeInstance->IsPayloadEnum()) && (fieldDef->IsEnumCaseEntry()))
  3446. {
  3447. Fail("Enums with payloads cannot have explicitly-defined discriminators", initializer);
  3448. BfConstResolver constResolver(this);
  3449. constResolver.Resolve(initializer);
  3450. return GetDefaultTypedValue(fieldType);
  3451. }
  3452. else if (fieldDef->mIsConst)
  3453. {
  3454. BfTypeState typeState;
  3455. typeState.mTypeInstance = mCurTypeInstance;
  3456. typeState.mCurTypeDef = fieldDef->mDeclaringType;
  3457. typeState.mCurFieldDef = fieldDef;
  3458. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  3459. BfConstResolver constResolver(this);
  3460. if (fieldType->IsVar())
  3461. return constResolver.Resolve(initializer);
  3462. else
  3463. {
  3464. BfConstResolveFlags resolveFlags = BfConstResolveFlag_None;
  3465. if ((mCompiler->mResolvePassData != NULL) && (mCurTypeInstance->IsEnum()) && (fieldDef->IsEnumCaseEntry()) &&
  3466. (mCompiler->mResolvePassData->mAutoCompleteTempTypes.Contains(fieldDef->mDeclaringType)))
  3467. {
  3468. // We avoid doing the cast here because the value we're typing may not be in the range of the current
  3469. // auto-created underlying type and it will cause an 'error flash'. We defer errors until the full resolve for that purpose
  3470. resolveFlags = BfConstResolveFlag_NoCast;
  3471. }
  3472. UpdateSrcPos(initializer);
  3473. return constResolver.Resolve(initializer, fieldType, resolveFlags);
  3474. }
  3475. }
  3476. BfExprEvaluator exprEvaluator(this);
  3477. if (doStore)
  3478. {
  3479. staticVarRef = ReferenceStaticField(fieldInstance);
  3480. exprEvaluator.mReceivingValue = &staticVarRef;
  3481. }
  3482. if (fieldType->IsVar())
  3483. result = CreateValueFromExpression(exprEvaluator, initializer, NULL, (BfEvalExprFlags)(BfEvalExprFlags_NoValueAddr | BfEvalExprFlags_FieldInitializer));
  3484. else
  3485. result = CreateValueFromExpression(exprEvaluator, initializer, fieldType, (BfEvalExprFlags)(BfEvalExprFlags_NoValueAddr | BfEvalExprFlags_FieldInitializer));
  3486. if (doStore)
  3487. {
  3488. if (exprEvaluator.mReceivingValue == NULL)
  3489. doStore = false; // Already stored
  3490. }
  3491. }
  3492. if (fieldInstance != NULL)
  3493. MarkFieldInitialized(fieldInstance);
  3494. if ((doStore) && (result))
  3495. {
  3496. result = LoadValue(result);
  3497. if (!result.mType->IsValuelessType())
  3498. mBfIRBuilder->CreateStore(result.mValue, staticVarRef.mValue);
  3499. }
  3500. return result;
  3501. }
  3502. void BfModule::CheckInterfaceMethod(BfMethodInstance* methodInstance)
  3503. {
  3504. }
  3505. void BfModule::FindSubTypes(BfTypeInstance* classType, SizedArrayImpl<int>* outVals, SizedArrayImpl<BfTypeInstance*>* exChecks, bool isInterfacePass)
  3506. {
  3507. PopulateType(classType);
  3508. if (isInterfacePass)
  3509. {
  3510. for (auto ifaceInst : classType->mInterfaces)
  3511. {
  3512. if (exChecks->Contains(ifaceInst.mInterfaceType))
  3513. continue;
  3514. if (outVals->Contains(ifaceInst.mInterfaceType->mTypeId))
  3515. continue;
  3516. if (ifaceInst.mDeclaringType->IsExtension())
  3517. {
  3518. bool needsExCheck = false;
  3519. if (ifaceInst.mDeclaringType->mProject != classType->mTypeDef->mProject)
  3520. {
  3521. PopulateType(ifaceInst.mInterfaceType, BfPopulateType_DataAndMethods);
  3522. if (ifaceInst.mInterfaceType->mVirtualMethodTableSize > 0)
  3523. {
  3524. exChecks->push_back(ifaceInst.mInterfaceType);
  3525. continue;
  3526. }
  3527. else
  3528. {
  3529. // We can only do an 'exCheck' if we're actually going to slot this interface
  3530. }
  3531. }
  3532. }
  3533. outVals->push_back(ifaceInst.mInterfaceType->mTypeId);
  3534. }
  3535. }
  3536. else
  3537. {
  3538. outVals->push_back(classType->mTypeId);
  3539. }
  3540. if (classType->mBaseType != NULL)
  3541. {
  3542. FindSubTypes(classType->mBaseType, outVals, exChecks, isInterfacePass);
  3543. }
  3544. }
  3545. void BfModule::CreateDynamicCastMethod()
  3546. {
  3547. auto objType = mContext->mBfObjectType;
  3548. if ((mCompiler->mIsResolveOnly) || (!mIsReified))
  3549. {
  3550. // The main reason to punt on this method for ResolveOnly is because types can be created
  3551. // and destroyed quickly during autocomplete and the typeId creep can generate lots of
  3552. // entries in the LLVM ConstantInt pool, primarily from the FindSubTypes call. We can
  3553. // remove this punt when we recycle typeId's
  3554. mBfIRBuilder->CreateRet(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(objType)));
  3555. mCurMethodState->mHadReturn = true;
  3556. return;
  3557. }
  3558. bool isInterfacePass = mCurMethodInstance->mMethodDef->mName == BF_METHODNAME_DYNAMICCAST_INTERFACE;
  3559. auto func = mCurMethodState->mIRFunction;
  3560. auto thisValue = mBfIRBuilder->GetArgument(0);
  3561. auto typeIdValue = mBfIRBuilder->GetArgument(1);
  3562. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  3563. auto int32Type = GetPrimitiveType(BfTypeCode_Int32);
  3564. typeIdValue = CastToValue(NULL, BfTypedValue(typeIdValue, intPtrType), int32Type, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_SilentFail));
  3565. auto thisObject = mBfIRBuilder->CreateBitCast(thisValue, mBfIRBuilder->MapType(objType));
  3566. auto trueBB = mBfIRBuilder->CreateBlock("check.true");
  3567. //auto falseBB = mBfIRBuilder->CreateBlock("check.false");
  3568. auto exitBB = mBfIRBuilder->CreateBlock("exit");
  3569. SizedArray<int, 8> typeMatches;
  3570. SizedArray<BfTypeInstance*, 8> exChecks;
  3571. FindSubTypes(mCurTypeInstance, &typeMatches, &exChecks, isInterfacePass);
  3572. if ((mCurTypeInstance->IsGenericTypeInstance()) && (!mCurTypeInstance->IsUnspecializedType()))
  3573. {
  3574. // Add 'unbound' type id to cast list so things like "List<int> is List<>" work
  3575. auto genericTypeInst = mCurTypeInstance->mTypeDef;
  3576. BfTypeVector genericArgs;
  3577. for (int i = 0; i < (int) genericTypeInst->mGenericParamDefs.size(); i++)
  3578. genericArgs.push_back(GetGenericParamType(BfGenericParamKind_Type, i));
  3579. auto unboundType = ResolveTypeDef(mCurTypeInstance->mTypeDef, genericArgs, BfPopulateType_Declaration);
  3580. typeMatches.push_back(unboundType->mTypeId);
  3581. }
  3582. if (mCurTypeInstance->IsBoxed())
  3583. {
  3584. BfBoxedType* boxedType = (BfBoxedType*)mCurTypeInstance;
  3585. BfTypeInstance* innerType = boxedType->mElementType->ToTypeInstance();
  3586. FindSubTypes(innerType, &typeMatches, &exChecks, isInterfacePass);
  3587. if (innerType->IsTypedPrimitive())
  3588. {
  3589. auto underlyingType = innerType->GetUnderlyingType();
  3590. typeMatches.push_back(underlyingType->mTypeId);
  3591. }
  3592. auto innerTypeInst = innerType->ToTypeInstance();
  3593. if ((innerTypeInst->mTypeDef == mCompiler->mSizedArrayTypeDef) ||
  3594. (innerTypeInst->mTypeDef == mCompiler->mPointerTTypeDef) ||
  3595. (innerTypeInst->mTypeDef == mCompiler->mMethodRefTypeDef))
  3596. {
  3597. PopulateType(innerTypeInst);
  3598. //TODO: What case was this supposed to handle?
  3599. //typeMatches.push_back(innerTypeInst->mFieldInstances[0].mResolvedType->mTypeId);
  3600. }
  3601. }
  3602. auto curBlock = mBfIRBuilder->GetInsertBlock();
  3603. BfIRValue vDataPtr;
  3604. if (!exChecks.empty())
  3605. {
  3606. BfType* intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  3607. auto ptrPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(intPtrType)));
  3608. auto vDataPtrPtr = mBfIRBuilder->CreateBitCast(thisValue, ptrPtrType);
  3609. vDataPtr = FixClassVData(mBfIRBuilder->CreateLoad(vDataPtrPtr/*, "vtable"*/));
  3610. }
  3611. auto switchStatement = mBfIRBuilder->CreateSwitch(typeIdValue, exitBB, (int)typeMatches.size() + (int)exChecks.size());
  3612. for (auto typeMatch : typeMatches)
  3613. mBfIRBuilder->AddSwitchCase(switchStatement, GetConstValue32(typeMatch), trueBB);
  3614. Array<BfIRValue> incomingFalses;
  3615. for (auto ifaceTypeInst : exChecks)
  3616. {
  3617. BfIRBlock nextBB = mBfIRBuilder->CreateBlock("exCheck", true);
  3618. mBfIRBuilder->AddSwitchCase(switchStatement, GetConstValue32(ifaceTypeInst->mTypeId), nextBB);
  3619. mBfIRBuilder->SetInsertPoint(nextBB);
  3620. BfIRValue slotOfs = GetInterfaceSlotNum(ifaceTypeInst);
  3621. auto ifacePtrPtr = mBfIRBuilder->CreateInBoundsGEP(vDataPtr, slotOfs/*, "iface"*/);
  3622. auto ifacePtr = mBfIRBuilder->CreateLoad(ifacePtrPtr);
  3623. auto cmpResult = mBfIRBuilder->CreateCmpNE(ifacePtr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0));
  3624. mBfIRBuilder->CreateCondBr(cmpResult, trueBB, exitBB);
  3625. incomingFalses.push_back(nextBB);
  3626. }
  3627. mBfIRBuilder->AddBlock(trueBB);
  3628. mBfIRBuilder->SetInsertPoint(trueBB);
  3629. mBfIRBuilder->CreateBr(exitBB);
  3630. mBfIRBuilder->AddBlock(exitBB);
  3631. mBfIRBuilder->SetInsertPoint(exitBB);
  3632. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapTypeInstPtr(objType), 2);
  3633. mBfIRBuilder->AddPhiIncoming(phi, thisObject, trueBB);
  3634. auto nullValue = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(objType));
  3635. for (auto incomingFalseBlock : incomingFalses)
  3636. mBfIRBuilder->AddPhiIncoming(phi, nullValue, incomingFalseBlock);
  3637. mBfIRBuilder->AddPhiIncoming(phi, nullValue, curBlock);
  3638. mBfIRBuilder->CreateRet(phi);
  3639. mCurMethodState->mHadReturn = true;
  3640. }
  3641. void BfModule::EmitEquals(BfTypedValue leftValue, BfTypedValue rightValue, BfIRBlock exitBB, bool strictEquals)
  3642. {
  3643. BfExprEvaluator exprEvaluator(this);
  3644. exprEvaluator.mExpectingType = mCurMethodInstance->mReturnType;
  3645. auto typeInst = rightValue.mType->ToTypeInstance();
  3646. exprEvaluator.PerformBinaryOperation((BfAstNode*)NULL, (BfAstNode*)NULL, strictEquals ? BfBinaryOp_StrictEquality : BfBinaryOp_Equality, NULL, BfBinOpFlag_IgnoreOperatorWithWrongResult, leftValue, rightValue);
  3647. BfTypedValue result = exprEvaluator.GetResult();
  3648. if (result.mType != GetPrimitiveType(BfTypeCode_Boolean))
  3649. {
  3650. // Fail?
  3651. }
  3652. if ((result) && (!result.mType->IsVar()))
  3653. {
  3654. auto nextBB = mBfIRBuilder->CreateBlock("next");
  3655. mBfIRBuilder->CreateCondBr(result.mValue, nextBB, exitBB);
  3656. mBfIRBuilder->AddBlock(nextBB);
  3657. mBfIRBuilder->SetInsertPoint(nextBB);
  3658. }
  3659. }
  3660. void BfModule::CreateFakeCallerMethod(const String& funcName)
  3661. {
  3662. if (mCurMethodInstance->mHasFailed)
  3663. return;
  3664. if (mCurMethodInstance->mMethodDef->mIsSkipCall)
  3665. return;
  3666. BF_ASSERT(mCurMethodInstance->mIRFunction);
  3667. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  3668. SizedArray<BfIRType, 4> paramTypes;
  3669. BfIRFunctionType funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  3670. BfIRFunction func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_Internal, "FORCELINK_" + funcName);
  3671. mBfIRBuilder->SetActiveFunction(func);
  3672. auto entryBlock = mBfIRBuilder->CreateBlock("main", true);
  3673. mBfIRBuilder->SetInsertPoint(entryBlock);
  3674. BfMethodState methodState;
  3675. methodState.mIRHeadBlock = entryBlock;
  3676. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  3677. SizedArray<BfIRValue, 8> args;
  3678. BfExprEvaluator exprEvaluator(this);
  3679. if (mCurMethodInstance->GetStructRetIdx() != -1)
  3680. {
  3681. auto retPtrType = CreatePointerType(mCurMethodInstance->mReturnType);
  3682. exprEvaluator.PushArg(GetDefaultTypedValue(retPtrType, true, BfDefaultValueKind_Const), args);
  3683. }
  3684. if (mCurMethodInstance->HasThis())
  3685. {
  3686. auto thisValue = GetDefaultTypedValue(mCurMethodInstance->GetOwner(), true, mCurTypeInstance->IsComposite() ? BfDefaultValueKind_Addr : BfDefaultValueKind_Const);
  3687. exprEvaluator.PushThis(NULL, thisValue, mCurMethodInstance, args);
  3688. }
  3689. for (int paramIdx = 0; paramIdx < mCurMethodInstance->GetParamCount(); paramIdx++)
  3690. {
  3691. auto paramType = mCurMethodInstance->GetParamType(paramIdx);
  3692. if (paramType->IsValuelessType())
  3693. continue;
  3694. exprEvaluator.PushArg(GetDefaultTypedValue(paramType, true, paramType->IsComposite() ? BfDefaultValueKind_Addr : BfDefaultValueKind_Const), args);
  3695. }
  3696. mBfIRBuilder->CreateCall(mCurMethodInstance->mIRFunction, args);
  3697. mBfIRBuilder->CreateRetVoid();
  3698. }
  3699. void BfModule::CreateValueTypeEqualsMethod(bool strictEquals)
  3700. {
  3701. if (mCurMethodInstance->mIsUnspecialized)
  3702. return;
  3703. if (mBfIRBuilder->mIgnoreWrites)
  3704. return;
  3705. BF_ASSERT(!mCurTypeInstance->IsBoxed());
  3706. auto compareType = mCurMethodInstance->mParams[0].mResolvedType;
  3707. bool isValid = true;
  3708. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  3709. if (compareType->IsValuelessType())
  3710. {
  3711. mBfIRBuilder->CreateRet(GetDefaultValue(boolType));
  3712. return;
  3713. }
  3714. if (compareType->IsTypedPrimitive())
  3715. {
  3716. BfExprEvaluator exprEvaluator(this);
  3717. BfTypedValue leftTypedVal = LoadValue(exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]));
  3718. BfTypedValue rightTypedVal = LoadValue(exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]));
  3719. auto cmpResult = mBfIRBuilder->CreateCmpEQ(leftTypedVal.mValue, rightTypedVal.mValue);
  3720. mBfIRBuilder->CreateRet(cmpResult);
  3721. return;
  3722. }
  3723. auto compareDType = compareType->ToDependedType();
  3724. BfTypeInstance* compareTypeInst = compareType->ToTypeInstance();
  3725. if (compareTypeInst != NULL)
  3726. {
  3727. if (compareType->IsPrimitiveType())
  3728. compareTypeInst = GetWrappedStructType(compareType);
  3729. if ((compareTypeInst == NULL) || (!compareTypeInst->IsValueType()))
  3730. {
  3731. isValid = false;
  3732. }
  3733. mBfIRBuilder->PopulateType(compareTypeInst);
  3734. }
  3735. if (!isValid)
  3736. {
  3737. ClearLifetimeEnds();
  3738. mBfIRBuilder->CreateRet(GetDefaultValue(boolType));
  3739. return;
  3740. }
  3741. AddDependency(compareDType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  3742. auto refNode = mCurTypeInstance->mTypeDef->GetRefNode();
  3743. if (refNode == NULL)
  3744. refNode = mCompiler->mValueTypeTypeDef->GetRefNode();
  3745. UpdateSrcPos(refNode);
  3746. SetIllegalSrcPos();
  3747. auto resultVal = CreateAlloca(boolType);
  3748. mBfIRBuilder->CreateStore(GetConstValue(0, boolType), resultVal);
  3749. auto exitBB = mBfIRBuilder->CreateBlock("exit");
  3750. if (compareType->IsValuelessType())
  3751. {
  3752. // Always equal, nothing to do
  3753. }
  3754. else if (compareType->IsSizedArray())
  3755. {
  3756. auto sizedArrayType = (BfSizedArrayType*)compareType;
  3757. auto _SizedIndex = [&](BfIRValue target, BfIRValue index)
  3758. {
  3759. BfTypedValue result;
  3760. if (sizedArrayType->mElementType->IsSizeAligned())
  3761. {
  3762. auto ptrType = CreatePointerType(sizedArrayType->mElementType);
  3763. auto ptrValue = mBfIRBuilder->CreateBitCast(target, mBfIRBuilder->MapType(ptrType));
  3764. auto gepResult = mBfIRBuilder->CreateInBoundsGEP(ptrValue, index);
  3765. result = BfTypedValue(gepResult, sizedArrayType->mElementType, BfTypedValueKind_Addr);
  3766. }
  3767. else
  3768. {
  3769. auto indexResult = CreateIndexedValue(sizedArrayType->mElementType, target, index);
  3770. result = BfTypedValue(indexResult, sizedArrayType->mElementType, BfTypedValueKind_Addr);
  3771. }
  3772. if (!result.mType->IsValueType())
  3773. result = LoadValue(result);
  3774. return result;
  3775. };
  3776. if (sizedArrayType->mElementCount > 6)
  3777. {
  3778. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  3779. auto itr = CreateAlloca(intPtrType);
  3780. mBfIRBuilder->CreateStore(GetDefaultValue(intPtrType), itr);
  3781. auto loopBB = mBfIRBuilder->CreateBlock("loop", true);
  3782. auto bodyBB = mBfIRBuilder->CreateBlock("body", true);
  3783. auto doneBB = mBfIRBuilder->CreateBlock("done", true);
  3784. mBfIRBuilder->CreateBr(loopBB);
  3785. mBfIRBuilder->SetInsertPoint(loopBB);
  3786. auto loadedItr = mBfIRBuilder->CreateLoad(itr);
  3787. auto cmpRes = mBfIRBuilder->CreateCmpGTE(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)sizedArrayType->mElementCount), true);
  3788. mBfIRBuilder->CreateCondBr(cmpRes, doneBB, bodyBB);
  3789. mBfIRBuilder->SetInsertPoint(bodyBB);
  3790. BfTypedValue leftValue = _SizedIndex(mCurMethodState->mLocals[0]->mValue, loadedItr);
  3791. BfTypedValue rightValue = _SizedIndex(mCurMethodState->mLocals[1]->mValue, loadedItr);
  3792. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  3793. auto incValue = mBfIRBuilder->CreateAdd(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  3794. mBfIRBuilder->CreateStore(incValue, itr);
  3795. mBfIRBuilder->CreateBr(loopBB);
  3796. mBfIRBuilder->SetInsertPoint(doneBB);
  3797. }
  3798. else
  3799. {
  3800. for (int dataIdx = 0; dataIdx < sizedArrayType->mElementCount; dataIdx++)
  3801. {
  3802. BfTypedValue leftValue = _SizedIndex(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, dataIdx));
  3803. BfTypedValue rightValue = _SizedIndex(mCurMethodState->mLocals[1]->mValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, dataIdx));
  3804. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  3805. }
  3806. }
  3807. }
  3808. else if (compareType->IsMethodRef())
  3809. {
  3810. auto methodRefType = (BfMethodRefType*)compareType;
  3811. BfMethodInstance* methodInstance = methodRefType->mMethodRef;
  3812. BfExprEvaluator exprEvaluator(this);
  3813. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  3814. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  3815. // We only need to compare the 'this' capture. The rationale is that it's impossible to capture any other non-matching
  3816. // values for the same method reference -- they will always refer back to the same local variables.
  3817. int dataIdx = methodRefType->GetDataIdxFromParamIdx(-1);
  3818. if (dataIdx != -1)
  3819. {
  3820. bool failed = false;
  3821. BfTypedValue leftValue = exprEvaluator.DoImplicitArgCapture(NULL, methodInstance, methodRefType->GetParamIdxFromDataIdx(dataIdx), failed, BfImplicitParamKind_General, leftTypedVal);
  3822. BfTypedValue rightValue = exprEvaluator.DoImplicitArgCapture(NULL, methodInstance, methodRefType->GetParamIdxFromDataIdx(dataIdx), failed, BfImplicitParamKind_General, rightTypedVal);
  3823. BF_ASSERT(!failed);
  3824. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  3825. }
  3826. }
  3827. else if (compareTypeInst->IsEnum())
  3828. {
  3829. //auto intType = GetPrimitiveType(BfTypeCode_Int32);
  3830. BfExprEvaluator exprEvaluator(this);
  3831. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  3832. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  3833. auto dscrType = compareTypeInst->GetDiscriminatorType();
  3834. BfTypedValue leftValue = ExtractValue(leftTypedVal, NULL, 2);
  3835. leftValue = LoadValue(leftValue);
  3836. BfTypedValue rightValue = ExtractValue(rightTypedVal, NULL, 2);
  3837. rightValue = LoadValue(rightValue);
  3838. BfTypedValue leftPayload = ExtractValue(leftTypedVal, NULL, 1);
  3839. BfTypedValue rightPayload = ExtractValue(rightTypedVal, NULL, 1);
  3840. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  3841. int enumCount = 0;
  3842. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  3843. {
  3844. BfFieldInstance* fieldInstance = &fieldRef;
  3845. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  3846. if ((fieldDef != NULL) && (fieldDef->IsEnumCaseEntry()))
  3847. {
  3848. enumCount = -fieldInstance->mDataIdx;
  3849. }
  3850. }
  3851. if (enumCount > 0)
  3852. {
  3853. BfIRBlock matchedBlock = mBfIRBuilder->CreateBlock("matched");
  3854. auto switchVal = mBfIRBuilder->CreateSwitch(leftValue.mValue, exitBB, enumCount);
  3855. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  3856. {
  3857. BfFieldInstance* fieldInstance = &fieldRef;
  3858. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  3859. if ((fieldDef != NULL) && (fieldDef->IsEnumCaseEntry()))
  3860. {
  3861. int enumIdx = -fieldInstance->mDataIdx - 1;
  3862. if (fieldInstance->mResolvedType->mSize == 0)
  3863. {
  3864. mBfIRBuilder->AddSwitchCase(switchVal, mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, enumIdx), matchedBlock);
  3865. }
  3866. else
  3867. {
  3868. auto caseBlock = mBfIRBuilder->CreateBlock("case", true);
  3869. mBfIRBuilder->SetInsertPoint(caseBlock);
  3870. auto tuplePtr = CreatePointerType(fieldInstance->mResolvedType);
  3871. BfTypedValue leftTuple;
  3872. BfTypedValue rightTuple;
  3873. if (leftPayload.IsAddr())
  3874. {
  3875. leftTuple = BfTypedValue(mBfIRBuilder->CreateBitCast(leftPayload.mValue, mBfIRBuilder->MapType(tuplePtr)), fieldInstance->mResolvedType, true);
  3876. rightTuple = BfTypedValue(mBfIRBuilder->CreateBitCast(rightPayload.mValue, mBfIRBuilder->MapType(tuplePtr)), fieldInstance->mResolvedType, true);
  3877. }
  3878. else
  3879. {
  3880. leftTuple = Cast(NULL, leftPayload, fieldInstance->mResolvedType, BfCastFlags_Force);
  3881. rightTuple = Cast(NULL, rightPayload, fieldInstance->mResolvedType, BfCastFlags_Force);
  3882. }
  3883. EmitEquals(leftTuple, rightTuple, exitBB, strictEquals);
  3884. mBfIRBuilder->CreateBr(matchedBlock);
  3885. mBfIRBuilder->AddSwitchCase(switchVal, mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, enumIdx), caseBlock);
  3886. }
  3887. }
  3888. }
  3889. mBfIRBuilder->AddBlock(matchedBlock);
  3890. mBfIRBuilder->SetInsertPoint(matchedBlock);
  3891. }
  3892. }
  3893. else if (compareTypeInst->IsUnion())
  3894. {
  3895. auto innerType = compareTypeInst->GetUnionInnerType();
  3896. if (!innerType->IsValuelessType())
  3897. {
  3898. BfExprEvaluator exprEvaluator(this);
  3899. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  3900. BfTypedValue leftUnionTypedVal = ExtractValue(leftTypedVal, NULL, 1);
  3901. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  3902. BfTypedValue rightUnionTypedVal = ExtractValue(rightTypedVal, NULL, 1);
  3903. EmitEquals(leftUnionTypedVal, rightUnionTypedVal, exitBB, strictEquals);
  3904. }
  3905. }
  3906. else
  3907. {
  3908. BfExprEvaluator exprEvaluator(this);
  3909. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  3910. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  3911. bool hadComparison = false;
  3912. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  3913. {
  3914. BfFieldInstance* fieldInstance = &fieldRef;
  3915. if (fieldInstance->mDataOffset == -1)
  3916. continue;
  3917. if (fieldInstance->mResolvedType->IsValuelessType())
  3918. continue;
  3919. if (fieldInstance->mResolvedType->IsVar())
  3920. continue;
  3921. BfTypedValue leftValue = ExtractValue(leftTypedVal, fieldInstance, fieldInstance->mDataIdx);
  3922. BfTypedValue rightValue = ExtractValue(rightTypedVal, fieldInstance, fieldInstance->mDataIdx);
  3923. if (!fieldInstance->mResolvedType->IsComposite())
  3924. {
  3925. leftValue = LoadValue(leftValue);
  3926. rightValue = LoadValue(rightValue);
  3927. }
  3928. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  3929. }
  3930. auto baseTypeInst = compareTypeInst->mBaseType;
  3931. if ((baseTypeInst != NULL) && (baseTypeInst->mTypeDef != mCompiler->mValueTypeTypeDef))
  3932. {
  3933. BfTypedValue leftValue = Cast(NULL, leftTypedVal, baseTypeInst);
  3934. BfTypedValue rightValue = Cast(NULL, rightTypedVal, baseTypeInst);
  3935. EmitEquals(leftValue, rightValue, exitBB, strictEquals);
  3936. }
  3937. }
  3938. mBfIRBuilder->CreateStore(GetConstValue(1, boolType), resultVal);
  3939. mBfIRBuilder->CreateBr(exitBB);
  3940. mBfIRBuilder->AddBlock(exitBB);
  3941. mBfIRBuilder->SetInsertPoint(exitBB);
  3942. auto loadedResult = mBfIRBuilder->CreateLoad(resultVal);
  3943. ClearLifetimeEnds();
  3944. mBfIRBuilder->CreateRet(loadedResult);
  3945. mCurMethodState->mHadReturn = true;
  3946. }
  3947. BfIRValue BfModule::CreateClassVDataGlobal(BfTypeInstance* typeInstance, int* outNumElements, String* outMangledName)
  3948. {
  3949. if (mBfIRBuilder->mIgnoreWrites)
  3950. return mBfIRBuilder->GetFakeVal();
  3951. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  3952. BfType* classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  3953. BfIRValue* globalVariablePtr = NULL;
  3954. mClassVDataRefs.TryGetValue(typeInstance, &globalVariablePtr);
  3955. int numElements = 1;
  3956. if ((outNumElements != NULL) || (globalVariablePtr == NULL))
  3957. {
  3958. numElements += mCompiler->mMaxInterfaceSlots;
  3959. auto maxIFaceVirtIdx = 0;
  3960. if (!typeInstance->IsInterface())
  3961. {
  3962. int dynCastDataElems = 1 + mCompiler->mMaxInterfaceSlots;
  3963. numElements += ((dynCastDataElems * 4) + mSystem->mPtrSize - 1) / mSystem->mPtrSize;
  3964. numElements += typeInstance->GetOrigVTableSize();
  3965. int ifaceMethodLen = typeInstance->GetIFaceVMethodSize();
  3966. if (typeInstance->mHotTypeData != NULL)
  3967. {
  3968. if (typeInstance->mHotTypeData->mOrigInterfaceMethodsLength != -1)
  3969. ifaceMethodLen = typeInstance->mHotTypeData->mOrigInterfaceMethodsLength;
  3970. }
  3971. numElements += ifaceMethodLen;
  3972. }
  3973. if (outNumElements != NULL)
  3974. *outNumElements = numElements;
  3975. }
  3976. StringT<128> classVDataName;
  3977. String memberName = "sBfClassVData";
  3978. if ((typeInstance->mHotTypeData != NULL) && ((typeInstance->mHotTypeData->mHadDataChange) || (typeInstance->mHotTypeData->mPendingDataChange)))
  3979. {
  3980. auto curVersion = typeInstance->mHotTypeData->GetLatestVersion();
  3981. memberName += "_";
  3982. memberName += BfTypeUtils::HashEncode64(curVersion->mDataHash.mLow);
  3983. memberName += BfTypeUtils::HashEncode64(curVersion->mDataHash.mHigh);
  3984. }
  3985. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), typeInstance, memberName, classVDataType);
  3986. if (outMangledName != NULL)
  3987. *outMangledName = classVDataName;
  3988. /*if (itr != mClassVDataRefs.end())
  3989. {
  3990. globalVariable = itr->second;
  3991. }*/
  3992. BfIRValue globalVariable;
  3993. if (globalVariablePtr != NULL)
  3994. {
  3995. globalVariable = *globalVariablePtr;
  3996. }
  3997. else
  3998. {
  3999. BfLogSysM("Creating VData %s\n", classVDataName.c_str());
  4000. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), numElements);
  4001. globalVariable = mBfIRBuilder->CreateGlobalVariable(
  4002. arrayType,
  4003. true,
  4004. BfIRLinkageType_External,
  4005. BfIRValue(),
  4006. classVDataName);
  4007. mClassVDataRefs[typeInstance] = globalVariable;
  4008. }
  4009. return globalVariable;
  4010. }
  4011. BfIRValue BfModule::GetClassVDataPtr(BfTypeInstance* typeInstance)
  4012. {
  4013. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  4014. return mBfIRBuilder->CreateBitCast(CreateClassVDataGlobal(typeInstance), mBfIRBuilder->MapType(CreatePointerType(classVDataType)));
  4015. }
  4016. BfIRValue BfModule::CreateClassVDataExtGlobal(BfTypeInstance* declTypeInst, BfTypeInstance* implTypeInst, int startVirtIdx)
  4017. {
  4018. if (mBfIRBuilder->mIgnoreWrites)
  4019. return mBfIRBuilder->GetFakeVal();
  4020. int numElements = declTypeInst->GetSelfVTableSize() - declTypeInst->GetOrigSelfVTableSize();
  4021. BF_ASSERT(numElements >= 0);
  4022. if (numElements <= 0)
  4023. return BfIRValue();
  4024. BF_ASSERT(implTypeInst->mVirtualMethodTable[startVirtIdx].mDeclaringMethod.mMethodNum == -1);
  4025. BF_ASSERT(implTypeInst->mVirtualMethodTable[startVirtIdx].mDeclaringMethod.mTypeInstance == declTypeInst);
  4026. if (declTypeInst->mInheritDepth == implTypeInst->mInheritDepth)
  4027. BF_ASSERT(declTypeInst == implTypeInst);
  4028. else
  4029. BF_ASSERT(implTypeInst->mInheritDepth > declTypeInst->mInheritDepth);
  4030. if (declTypeInst != implTypeInst)
  4031. {
  4032. BfTypeInstance* highestImpl = declTypeInst;
  4033. for (int virtIdx = startVirtIdx + 1; virtIdx < (int)declTypeInst->mVirtualMethodTable.size(); virtIdx++)
  4034. {
  4035. if (implTypeInst->mVirtualMethodTable[virtIdx].mDeclaringMethod.mMethodNum == -1)
  4036. break; // Start of an ext entry for another type
  4037. auto checkImplTypeInst = implTypeInst->mVirtualMethodTable[virtIdx].mImplementingMethod.mTypeInstance;
  4038. if ((checkImplTypeInst != NULL) && (checkImplTypeInst->mInheritDepth > highestImpl->mInheritDepth))
  4039. highestImpl = checkImplTypeInst;
  4040. }
  4041. if (highestImpl != implTypeInst)
  4042. return CreateClassVDataExtGlobal(declTypeInst, highestImpl, startVirtIdx);
  4043. }
  4044. BfVDataExtEntry mapEntry;
  4045. mapEntry.mDeclTypeInst = declTypeInst;
  4046. mapEntry.mImplTypeInst = implTypeInst;
  4047. BfIRValue* irValuePtr = NULL;
  4048. if (mClassVDataExtRefs.TryGetValue(mapEntry, &irValuePtr))
  4049. return *irValuePtr;
  4050. PopulateType(declTypeInst, BfPopulateType_DataAndMethods);
  4051. PopulateType(implTypeInst, BfPopulateType_DataAndMethods);
  4052. StringT<128> classVDataName;
  4053. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), implTypeInst, "bf_hs_replace_VDataExt");
  4054. if (declTypeInst != implTypeInst)
  4055. {
  4056. classVDataName += StrFormat("_%d", implTypeInst->mInheritDepth - declTypeInst->mInheritDepth);
  4057. }
  4058. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  4059. auto voidPtrIRType = mBfIRBuilder->MapType(voidPtrType);
  4060. SizedArray<BfIRValue, 32> vData;
  4061. auto voidPtrNull = GetDefaultValue(voidPtrType);
  4062. for (int virtIdx = startVirtIdx + declTypeInst->GetOrigSelfVTableSize(); virtIdx < (int)declTypeInst->mVirtualMethodTable.size(); virtIdx++)
  4063. {
  4064. if (implTypeInst->mVirtualMethodTable[virtIdx].mDeclaringMethod.mMethodNum == -1)
  4065. break; // Start of an ext entry for another type
  4066. BfIRValue vValue;
  4067. auto& entry = implTypeInst->mVirtualMethodTable[virtIdx];
  4068. BfMethodInstance* declaringMethodInstance = (BfMethodInstance*)entry.mDeclaringMethod;
  4069. if ((declaringMethodInstance != NULL) && (declaringMethodInstance->mMethodInstanceGroup->IsImplemented()) && (declaringMethodInstance->mIsReified))
  4070. {
  4071. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].IsImplemented());
  4072. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].mDefault->mIsReified);
  4073. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  4074. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  4075. {
  4076. BF_ASSERT(implTypeInst->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject));
  4077. auto moduleMethodInst = GetMethodInstanceAtIdx(methodInstance->mMethodInstanceGroup->mOwner, methodInstance->mMethodInstanceGroup->mMethodIdx, NULL, BfGetMethodInstanceFlag_NoInline);
  4078. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  4079. vValue = funcPtr;
  4080. }
  4081. }
  4082. if (!vValue)
  4083. vValue = voidPtrNull;
  4084. vData.Add(vValue);
  4085. }
  4086. BF_ASSERT((int)vData.size() == numElements);
  4087. BfLogSysM("Creating VDataExt %s\n", classVDataName.c_str());
  4088. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), numElements);
  4089. auto globalVariable = mBfIRBuilder->CreateGlobalVariable(arrayType, true,
  4090. BfIRLinkageType_External, BfIRValue(), classVDataName);
  4091. BfIRType extVTableType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)vData.size());
  4092. BfIRValue extVTableConst = mBfIRBuilder->CreateConstArray(extVTableType, vData);
  4093. mBfIRBuilder->GlobalVar_SetInitializer(globalVariable, extVTableConst);
  4094. mClassVDataExtRefs[mapEntry] = globalVariable;
  4095. return globalVariable;
  4096. }
  4097. BfIRValue BfModule::CreateTypeDataRef(BfType* type)
  4098. {
  4099. if (mBfIRBuilder->mIgnoreWrites)
  4100. {
  4101. return mBfIRBuilder->CreateTypeOf(type);
  4102. }
  4103. BfIRValue globalVariable;
  4104. BfIRValue* globalVariablePtr = NULL;
  4105. if (mTypeDataRefs.TryGetValue(type, &globalVariablePtr))
  4106. {
  4107. globalVariable = *globalVariablePtr;
  4108. if (globalVariable)
  4109. return globalVariable;
  4110. }
  4111. auto typeTypeDef = ResolveTypeDef(mCompiler->mTypeTypeDef);
  4112. auto typeTypeInst = typeTypeDef->ToTypeInstance();
  4113. auto typeInstance = type->ToTypeInstance();
  4114. StringT<128> typeDataName;
  4115. if (typeInstance != NULL)
  4116. {
  4117. BfMangler::MangleStaticFieldName(typeDataName, mCompiler->GetMangleKind(), typeInstance, "sBfTypeData");
  4118. }
  4119. else
  4120. {
  4121. typeDataName += "sBfTypeData.";
  4122. BfMangler::Mangle(typeDataName, mCompiler->GetMangleKind(), type, this);
  4123. }
  4124. BfLogSysM("Creating TypeData %s\n", typeDataName.c_str());
  4125. globalVariable = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(typeTypeInst, BfIRPopulateType_Full), true, BfIRLinkageType_External, BfIRValue(), typeDataName);
  4126. mTypeDataRefs[type] = globalVariable;
  4127. return globalVariable;
  4128. }
  4129. BfIRValue BfModule::CreateTypeData(BfType* type, Dictionary<int, int>& usedStringIdMap, bool forceReflectFields, bool needsTypeData, bool needsTypeNames, bool needsVData)
  4130. {
  4131. if ((mCompiler->IsHotCompile()) && (!type->mDirty))
  4132. return BfIRValue();
  4133. BfIRValue* irValuePtr = NULL;
  4134. if (mTypeDataRefs.TryGetValue(type, &irValuePtr))
  4135. {
  4136. return *irValuePtr;
  4137. }
  4138. BfTypeInstance* typeInstance = type->ToTypeInstance();
  4139. BfType* typeInstanceType = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef);
  4140. mBfIRBuilder->PopulateType(typeInstanceType, BfIRPopulateType_Full_ForceDefinition);
  4141. if (typeInstanceType == NULL)
  4142. {
  4143. AssertErrorState();
  4144. return BfIRValue();
  4145. }
  4146. BfIRValue typeTypeData;
  4147. int typeFlags = 0;
  4148. if (needsTypeData)
  4149. {
  4150. BfTypeInstance* typeInstanceTypeInstance = typeInstanceType->ToTypeInstance();
  4151. BfTypeInstance* typeDataSource = NULL;
  4152. if (typeInstance != NULL)
  4153. {
  4154. if (typeInstance->IsUnspecializedType())
  4155. {
  4156. typeDataSource = ResolveTypeDef(mCompiler->mReflectUnspecializedGenericType)->ToTypeInstance();
  4157. typeFlags |= BfTypeFlags_UnspecializedGeneric;
  4158. }
  4159. else if (typeInstance->IsArray())
  4160. {
  4161. typeDataSource = ResolveTypeDef(mCompiler->mReflectArrayType)->ToTypeInstance();
  4162. typeFlags |= BfTypeFlags_Array;
  4163. }
  4164. else if (typeInstance->IsGenericTypeInstance())
  4165. {
  4166. typeDataSource = ResolveTypeDef(mCompiler->mReflectSpecializedGenericType)->ToTypeInstance();
  4167. typeFlags |= BfTypeFlags_SpecializedGeneric;
  4168. }
  4169. else
  4170. typeDataSource = typeInstanceTypeInstance;
  4171. }
  4172. else if (type->IsPointer())
  4173. typeDataSource = ResolveTypeDef(mCompiler->mReflectPointerType)->ToTypeInstance();
  4174. else if (type->IsRef())
  4175. typeDataSource = ResolveTypeDef(mCompiler->mReflectRefType)->ToTypeInstance();
  4176. else if (type->IsSizedArray())
  4177. typeDataSource = ResolveTypeDef(mCompiler->mReflectSizedArrayType)->ToTypeInstance();
  4178. else
  4179. typeDataSource = mContext->mBfTypeType;
  4180. if ((!mTypeDataRefs.ContainsKey(typeDataSource)) && (typeDataSource != type))
  4181. {
  4182. CreateTypeData(typeDataSource, usedStringIdMap, false, true, needsTypeNames, true);
  4183. }
  4184. typeTypeData = CreateClassVDataGlobal(typeDataSource);
  4185. }
  4186. else
  4187. typeTypeData = CreateClassVDataGlobal(typeInstanceType->ToTypeInstance());
  4188. BfType* longType = GetPrimitiveType(BfTypeCode_Int64);
  4189. BfType* intType = GetPrimitiveType(BfTypeCode_Int32);
  4190. BfType* intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  4191. BfType* shortType = GetPrimitiveType(BfTypeCode_Int16);
  4192. BfType* byteType = GetPrimitiveType(BfTypeCode_Int8);
  4193. BfType* typeIdType = intType;
  4194. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  4195. auto voidPtrIRType = mBfIRBuilder->MapType(voidPtrType);
  4196. auto voidPtrPtrIRType = mBfIRBuilder->GetPointerTo(voidPtrIRType);
  4197. auto voidPtrNull = GetDefaultValue(voidPtrType);
  4198. SizedArray<BfIRValue, 4> typeValueParams;
  4199. GetConstClassValueParam(typeTypeData, typeValueParams);
  4200. BfIRValue objectData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(mContext->mBfObjectType, BfIRPopulateType_Full), typeValueParams);
  4201. StringT<128> typeDataName;
  4202. if ((typeInstance != NULL) && (!typeInstance->IsTypeAlias()))
  4203. {
  4204. BfMangler::MangleStaticFieldName(typeDataName, mCompiler->GetMangleKind(), typeInstance, "sBfTypeData");
  4205. if (typeInstance->mTypeDef->IsGlobalsContainer())
  4206. typeDataName += "`G`" + typeInstance->mTypeDef->mProject->mName;
  4207. }
  4208. else
  4209. {
  4210. typeDataName += "sBfTypeData.";
  4211. BfMangler::Mangle(typeDataName, mCompiler->GetMangleKind(), type, mContext->mScratchModule);
  4212. }
  4213. int typeCode = BfTypeCode_None;
  4214. if (typeInstance != NULL)
  4215. {
  4216. typeCode = typeInstance->mTypeDef->mTypeCode;
  4217. }
  4218. else if (type->IsPrimitiveType())
  4219. {
  4220. BfPrimitiveType* primType = (BfPrimitiveType*)type;
  4221. typeCode = primType->mTypeDef->mTypeCode;
  4222. }
  4223. else if (type->IsPointer())
  4224. {
  4225. typeCode = BfTypeCode_Pointer;
  4226. typeFlags |= BfTypeFlags_Pointer;
  4227. }
  4228. else if (type->IsRef())
  4229. {
  4230. typeCode = BfTypeCode_Pointer;
  4231. typeFlags |= BfTypeFlags_Pointer;
  4232. }
  4233. if (type->IsObject())
  4234. {
  4235. typeFlags |= BfTypeFlags_Object;
  4236. BfMethodInstance* methodInstance = typeInstance->mVirtualMethodTable[mCompiler->GetVTableMethodOffset() + 0].mImplementingMethod;
  4237. if (methodInstance->GetOwner() != mContext->mBfObjectType)
  4238. typeFlags |= BfTypeFlags_HasDestructor;
  4239. }
  4240. if (type->IsStruct())
  4241. typeFlags |= BfTypeFlags_Struct;
  4242. if (type->IsInterface())
  4243. typeFlags |= BfTypeFlags_Interface;
  4244. if (type->IsBoxed())
  4245. {
  4246. typeFlags |= BfTypeFlags_Boxed;
  4247. if (((BfBoxedType*)type)->IsBoxedStructPtr())
  4248. typeFlags |= BfTypeFlags_Pointer;
  4249. }
  4250. if (type->IsPrimitiveType())
  4251. typeFlags |= BfTypeFlags_Primitive;
  4252. if (type->IsTypedPrimitive())
  4253. typeFlags |= BfTypeFlags_TypedPrimitive;
  4254. if (type->IsTuple())
  4255. typeFlags |= BfTypeFlags_Tuple;
  4256. if (type->IsNullable())
  4257. typeFlags |= BfTypeFlags_Nullable;
  4258. if (type->IsSizedArray())
  4259. typeFlags |= BfTypeFlags_SizedArray;
  4260. if (type->IsSplattable())
  4261. typeFlags |= BfTypeFlags_Splattable;
  4262. if (type->IsUnion())
  4263. typeFlags |= BfTypeFlags_Union;
  4264. if (type->IsDelegate())
  4265. typeFlags |= BfTypeFlags_Delegate;
  4266. if (type->IsFunction())
  4267. typeFlags |= BfTypeFlags_Function;
  4268. if (type->WantsGCMarking())
  4269. typeFlags |= BfTypeFlags_WantsMarking;
  4270. int virtSlotIdx = -1;
  4271. if ((typeInstance != NULL) && (typeInstance->mSlotNum >= 0))
  4272. virtSlotIdx = typeInstance->mSlotNum + 1 + mCompiler->GetDynCastVDataCount();
  4273. int memberDataOffset = 0;
  4274. if (type->IsInterface())
  4275. memberDataOffset = virtSlotIdx * mSystem->mPtrSize;
  4276. else if (typeInstance != NULL)
  4277. {
  4278. for (auto& fieldInstance : typeInstance->mFieldInstances)
  4279. {
  4280. if (fieldInstance.mDataOffset != -1)
  4281. {
  4282. memberDataOffset = fieldInstance.mDataOffset;
  4283. break;
  4284. }
  4285. }
  4286. }
  4287. int boxedTypeId = 0;
  4288. if ((type->IsValueType()) || (type->IsWrappableType()))
  4289. {
  4290. auto boxedType = CreateBoxedType(type, false);
  4291. if ((boxedType != NULL) && (boxedType->mIsReified))
  4292. boxedTypeId = boxedType->mTypeId;
  4293. }
  4294. SizedArray<BfIRValue, 8> typeDataParams =
  4295. {
  4296. objectData,
  4297. GetConstValue(type->mSize, intType), // mSize
  4298. GetConstValue(type->mTypeId, typeIdType), // mTypeId
  4299. GetConstValue(boxedTypeId, typeIdType), // mBoxedType
  4300. GetConstValue(typeFlags, intType), // mTypeFlags
  4301. GetConstValue(memberDataOffset, intType), // mMemberDataOffset
  4302. GetConstValue(typeCode, byteType), // mTypeCode
  4303. GetConstValue(type->mAlign, byteType),
  4304. };
  4305. auto typeData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(mContext->mBfTypeType, BfIRPopulateType_Full), typeDataParams);
  4306. if (typeInstance == NULL)
  4307. {
  4308. BfIRValue typeDataVar;
  4309. if (needsTypeData)
  4310. {
  4311. if (type->IsPointer())
  4312. {
  4313. auto pointerType = (BfPointerType*)type;
  4314. SizedArray<BfIRValue, 3> pointerTypeDataParms =
  4315. {
  4316. typeData,
  4317. GetConstValue(pointerType->mElementType->mTypeId, typeIdType),
  4318. };
  4319. auto reflectPointerType = ResolveTypeDef(mCompiler->mReflectPointerType)->ToTypeInstance();
  4320. auto pointerTypeData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectPointerType, BfIRPopulateType_Full), pointerTypeDataParms);
  4321. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectPointerType), true,
  4322. BfIRLinkageType_External, pointerTypeData, typeDataName);
  4323. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  4324. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  4325. }
  4326. else if (type->IsRef())
  4327. {
  4328. auto refType = (BfRefType*)type;
  4329. SizedArray<BfIRValue, 3> refTypeDataParms =
  4330. {
  4331. typeData,
  4332. GetConstValue(refType->mElementType->mTypeId, typeIdType),
  4333. GetConstValue((int8)refType->mRefKind, byteType),
  4334. };
  4335. auto reflectRefType = ResolveTypeDef(mCompiler->mReflectRefType)->ToTypeInstance();
  4336. auto refTypeData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectRefType, BfIRPopulateType_Full), refTypeDataParms);
  4337. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectRefType), true,
  4338. BfIRLinkageType_External, refTypeData, typeDataName);
  4339. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  4340. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  4341. }
  4342. else if (type->IsSizedArray())
  4343. {
  4344. auto sizedArrayType = (BfSizedArrayType*)type;
  4345. SizedArray<BfIRValue, 3> sizedArrayTypeDataParms =
  4346. {
  4347. typeData,
  4348. GetConstValue(sizedArrayType->mElementType->mTypeId, typeIdType),
  4349. GetConstValue(sizedArrayType->mElementCount, intType)
  4350. };
  4351. auto reflectSizedArrayType = ResolveTypeDef(mCompiler->mReflectSizedArrayType)->ToTypeInstance();
  4352. auto sizedArrayTypeData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectSizedArrayType, BfIRPopulateType_Full), sizedArrayTypeDataParms);
  4353. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectSizedArrayType), true,
  4354. BfIRLinkageType_External, sizedArrayTypeData, typeDataName);
  4355. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  4356. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  4357. }
  4358. else
  4359. {
  4360. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(mContext->mBfTypeType), true,
  4361. BfIRLinkageType_External, typeData, typeDataName);
  4362. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  4363. }
  4364. }
  4365. else
  4366. typeDataVar = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(mContext->mBfTypeType));
  4367. mTypeDataRefs[typeInstance] = typeDataVar;
  4368. return typeDataVar;
  4369. }
  4370. // Reserve position
  4371. mTypeDataRefs[typeInstance] = BfIRValue();
  4372. if (typeInstance->IsReified())
  4373. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  4374. BfTypeDef* typeDef = typeInstance->mTypeDef;
  4375. StringT<128> mangledName;
  4376. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), typeInstance, typeInstance->mModule);
  4377. for (int methodIdx = 0; methodIdx < (int)typeDef->mMethods.size(); methodIdx++)
  4378. {
  4379. auto methodDef = typeDef->mMethods[methodIdx];
  4380. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  4381. if (methodInstance == NULL)
  4382. continue;
  4383. if (typeInstance->IsUnspecializedType())
  4384. continue;
  4385. if (!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, mProject))
  4386. {
  4387. if (methodInstance->mChainType == BfMethodChainType_ChainMember)
  4388. {
  4389. BF_ASSERT(!methodInstance->GetOwner()->IsUnspecializedType());
  4390. // We need to create an empty thunk for this chained method
  4391. BfIRFunction func = CreateFunctionFrom(methodInstance, false, methodInstance->mAlwaysInline);
  4392. mBfIRBuilder->SetActiveFunction(func);
  4393. auto block = mBfIRBuilder->CreateBlock("entry", true);
  4394. mBfIRBuilder->SetInsertPoint(block);
  4395. mBfIRBuilder->CreateRetVoid();
  4396. mBfIRBuilder->SetActiveFunction(BfIRFunction());
  4397. }
  4398. }
  4399. }
  4400. SizedArray<BfIRValue, 32> vData;
  4401. BfIRValue classVDataVar;
  4402. String classVDataName;
  4403. if (typeInstance->mSlotNum >= 0)
  4404. {
  4405. // For interfaces we ONLY emit the slot num
  4406. StringT<128> slotVarName;
  4407. BfMangler::MangleStaticFieldName(slotVarName, mCompiler->GetMangleKind(), typeInstance, "sBfSlotOfs");
  4408. auto intType = GetPrimitiveType(BfTypeCode_Int32);
  4409. auto slotNumVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(intType), true, BfIRLinkageType_External,
  4410. GetConstValue32(virtSlotIdx), slotVarName);
  4411. }
  4412. else if ((typeInstance->IsObject()) && (!typeInstance->IsUnspecializedType()) && (needsVData))
  4413. {
  4414. int dynCastDataElems = 0;
  4415. int numElements = 1;
  4416. int vDataOfs = 1; // The number of intptrs before the iface slot map
  4417. numElements += mCompiler->mMaxInterfaceSlots;
  4418. if (!typeInstance->IsInterface())
  4419. {
  4420. dynCastDataElems = 1 + mCompiler->mMaxInterfaceSlots;
  4421. numElements += mCompiler->GetDynCastVDataCount();
  4422. numElements += typeInstance->mVirtualMethodTableSize;
  4423. }
  4424. int expectNumElements = 0;
  4425. if (!typeDef->mIsStatic)
  4426. {
  4427. classVDataVar = CreateClassVDataGlobal(typeInstance, &expectNumElements, &classVDataName);
  4428. }
  4429. vData.push_back(BfIRValue()); // Type*
  4430. SizedArray<BfIRValue, 1> extVTableData;
  4431. SizedArrayImpl<BfIRValue>* vFuncDataExt = &extVTableData;
  4432. if (!typeInstance->IsInterface())
  4433. {
  4434. Array<int32> dynCastData;
  4435. if (typeInstance->IsBoxed())
  4436. {
  4437. auto underlyingType = typeInstance->GetUnderlyingType()->ToTypeInstance();
  4438. dynCastData.Add(underlyingType->mInheritanceId);
  4439. }
  4440. else
  4441. dynCastData.Add(typeInstance->mInheritanceId);
  4442. for (int i = 0; i < mCompiler->mMaxInterfaceSlots; i++)
  4443. dynCastData.Add(0);
  4444. dynCastData.Add(0);
  4445. auto checkTypeInst = typeInstance;
  4446. while (checkTypeInst != NULL)
  4447. {
  4448. for (auto&& interfaceEntry : checkTypeInst->mInterfaces)
  4449. {
  4450. if (interfaceEntry.mInterfaceType->mSlotNum >= 0)
  4451. {
  4452. if (dynCastData[interfaceEntry.mInterfaceType->mSlotNum + 1] == 0)
  4453. dynCastData[interfaceEntry.mInterfaceType->mSlotNum + 1] = interfaceEntry.mInterfaceType->mTypeId;
  4454. }
  4455. }
  4456. checkTypeInst = checkTypeInst->GetImplBaseType();
  4457. }
  4458. if (mSystem->mPtrSize == 8)
  4459. {
  4460. int intPtrCount = (dynCastDataElems + 1) / 2;
  4461. vDataOfs += intPtrCount;
  4462. uint64* intPtrData = (uint64*)&dynCastData[0];
  4463. for (int i = 0; i < intPtrCount; i++)
  4464. {
  4465. uint64 val = intPtrData[i];
  4466. if (val == 0)
  4467. {
  4468. vData.push_back(voidPtrNull);
  4469. }
  4470. else
  4471. {
  4472. auto intPtrVal = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, val);
  4473. vData.push_back(mBfIRBuilder->CreateBitCast(intPtrVal, voidPtrIRType));
  4474. }
  4475. }
  4476. }
  4477. else
  4478. {
  4479. int intPtrCount = dynCastDataElems;
  4480. vDataOfs += intPtrCount;
  4481. uint32* intPtrData = (uint32*)&dynCastData[0];
  4482. for (int i = 0; i < intPtrCount; i++)
  4483. {
  4484. uint32 val = intPtrData[i];
  4485. if (val == 0)
  4486. {
  4487. vData.push_back(voidPtrNull);
  4488. }
  4489. else
  4490. {
  4491. auto intPtrVal = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (int)val);
  4492. vData.push_back(mBfIRBuilder->CreateBitCast(intPtrVal, voidPtrIRType));
  4493. }
  4494. }
  4495. }
  4496. }
  4497. for (int iSlotIdx = 0; iSlotIdx < mCompiler->mMaxInterfaceSlots; iSlotIdx++)
  4498. vData.push_back(voidPtrNull);
  4499. struct _InterfaceMatchEntry
  4500. {
  4501. BfTypeInterfaceEntry* mEntry;
  4502. BfTypeInstance* mEntrySource;
  4503. Array<BfTypeInterfaceEntry*> mAmbiguousEntries;
  4504. };
  4505. int highestIFaceVirtIdx = 0;
  4506. Dictionary<BfTypeInstance*, _InterfaceMatchEntry> interfaceMap;
  4507. auto checkTypeInst = typeInstance;
  4508. bool forceInterfaceSet = false;
  4509. while (checkTypeInst != NULL)
  4510. {
  4511. for (auto&& interfaceEntry : checkTypeInst->mInterfaces)
  4512. {
  4513. highestIFaceVirtIdx = BF_MAX(highestIFaceVirtIdx, interfaceEntry.mStartVirtualIdx + interfaceEntry.mInterfaceType->mVirtualMethodTableSize);
  4514. if (!typeInstance->IsTypeMemberAccessible(interfaceEntry.mDeclaringType, mProject))
  4515. continue;
  4516. _InterfaceMatchEntry* matchEntry = NULL;
  4517. if (interfaceMap.TryGetValue(interfaceEntry.mInterfaceType, &matchEntry))
  4518. {
  4519. BfTypeInstance* compareCheckTypeInst = checkTypeInst;
  4520. if (compareCheckTypeInst->IsBoxed())
  4521. compareCheckTypeInst = compareCheckTypeInst->GetUnderlyingType()->ToTypeInstance();
  4522. BfTypeInstance* compareEntrySource = matchEntry->mEntrySource;
  4523. if (compareEntrySource->IsBoxed())
  4524. compareEntrySource = compareEntrySource->GetUnderlyingType()->ToTypeInstance();
  4525. auto prevEntry = matchEntry->mEntry;
  4526. bool isBetter = TypeIsSubTypeOf(compareCheckTypeInst, compareEntrySource);
  4527. bool isWorse = TypeIsSubTypeOf(compareEntrySource, compareCheckTypeInst);
  4528. if ((!isBetter) && (!isWorse))
  4529. {
  4530. // Unboxed comparison to Object fix
  4531. if (compareCheckTypeInst == mContext->mBfObjectType)
  4532. isWorse = true;
  4533. else if (compareEntrySource == mContext->mBfObjectType)
  4534. isBetter = true;
  4535. }
  4536. if (forceInterfaceSet)
  4537. {
  4538. isBetter = true;
  4539. isWorse = false;
  4540. }
  4541. if (isBetter == isWorse)
  4542. CompareDeclTypes(interfaceEntry.mDeclaringType, prevEntry->mDeclaringType, isBetter, isWorse);
  4543. if (isBetter == isWorse)
  4544. {
  4545. if (matchEntry->mAmbiguousEntries.empty())
  4546. matchEntry->mAmbiguousEntries.push_back(prevEntry);
  4547. matchEntry->mAmbiguousEntries.push_back(&interfaceEntry);
  4548. continue;
  4549. }
  4550. else if (isBetter)
  4551. {
  4552. matchEntry->mEntry = &interfaceEntry;
  4553. matchEntry->mEntrySource = checkTypeInst;
  4554. matchEntry->mAmbiguousEntries.Clear();
  4555. }
  4556. else
  4557. continue;
  4558. }
  4559. else
  4560. {
  4561. _InterfaceMatchEntry matchEntry;
  4562. matchEntry.mEntry = &interfaceEntry;
  4563. matchEntry.mEntrySource = checkTypeInst;
  4564. interfaceMap[interfaceEntry.mInterfaceType] = matchEntry;
  4565. }
  4566. }
  4567. checkTypeInst = checkTypeInst->GetImplBaseType();
  4568. }
  4569. for (auto interfacePair : interfaceMap)
  4570. {
  4571. auto& interfaceMatchEntry = interfacePair.mValue;
  4572. if (!interfaceMatchEntry.mAmbiguousEntries.empty())
  4573. {
  4574. 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());
  4575. if (error != NULL)
  4576. {
  4577. for (auto ambiguiousEntry : interfaceMatchEntry.mAmbiguousEntries)
  4578. mCompiler->mPassInstance->MoreInfo("See other declaration", ambiguiousEntry->mDeclaringType->GetRefNode());
  4579. }
  4580. }
  4581. }
  4582. if ((!typeInstance->IsInterface()) && (typeInstance->mVirtualMethodTableSize > 0) && (needsVData))
  4583. {
  4584. int startTabIdx = (int)vData.size();
  4585. SizedArray<BfTypeInstance*, 8> origVirtTypeStack;
  4586. BfTypeInstance* checkTypeInst = typeInstance;
  4587. while (checkTypeInst != NULL)
  4588. {
  4589. origVirtTypeStack.push_back(checkTypeInst);
  4590. checkTypeInst = checkTypeInst->GetImplBaseType();
  4591. }
  4592. Array<BfVirtualMethodEntry> origVTable;
  4593. int origVirtIdx = 0;
  4594. if (typeInstance->mTypeDef->mIsCombinedPartial)
  4595. {
  4596. HashSet<String> reslotNames;
  4597. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  4598. {
  4599. auto& entry = typeInstance->mVirtualMethodTable[virtIdx];
  4600. if (entry.mDeclaringMethod.mMethodNum == -1)
  4601. continue;
  4602. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  4603. if ((methodInstance == NULL) || (!typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject)))
  4604. {
  4605. if (origVTable.empty())
  4606. origVTable = typeInstance->mVirtualMethodTable;
  4607. BfMethodInstance* declMethodInstance = entry.mDeclaringMethod;
  4608. if (typeInstance->IsTypeMemberAccessible(declMethodInstance->mMethodDef->mDeclaringType, mProject))
  4609. {
  4610. // Prepare to reslot...
  4611. entry.mImplementingMethod = entry.mDeclaringMethod;
  4612. reslotNames.Add(declMethodInstance->mMethodDef->mName);
  4613. }
  4614. else
  4615. {
  4616. // Decl isn't accessible, null out entry
  4617. entry.mImplementingMethod = BfMethodRef();
  4618. }
  4619. }
  4620. }
  4621. if (!reslotNames.IsEmpty())
  4622. {
  4623. BfAmbiguityContext ambiguityContext;
  4624. ambiguityContext.mTypeInstance = typeInstance;
  4625. ambiguityContext.mModule = this;
  4626. ambiguityContext.mIsProjectSpecific = true;
  4627. ambiguityContext.mIsReslotting = true;
  4628. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  4629. for (auto& methodGroup : typeInstance->mMethodInstanceGroups)
  4630. {
  4631. auto methodInstance = methodGroup.mDefault;
  4632. if ((methodInstance == NULL) || (!methodInstance->mMethodDef->mIsOverride))
  4633. continue;
  4634. if (!reslotNames.Contains(methodInstance->mMethodDef->mName))
  4635. continue;
  4636. if (!typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject))
  4637. continue;
  4638. if ((methodInstance->mChainType != BfMethodChainType_None) && (methodInstance->mChainType != BfMethodChainType_ChainHead))
  4639. continue;
  4640. SlotVirtualMethod(methodInstance, &ambiguityContext);
  4641. }
  4642. ambiguityContext.Finish();
  4643. }
  4644. }
  4645. bool isInExts = false;
  4646. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  4647. {
  4648. BfIRValue vValue = voidPtrNull;
  4649. auto& entry = typeInstance->mVirtualMethodTable[virtIdx];
  4650. BfModuleMethodInstance moduleMethodInst;
  4651. if (entry.mDeclaringMethod.mMethodNum == -1)
  4652. {
  4653. // mMethodNum of -1 indicates a vExt slot rather than an actual method reference
  4654. isInExts = true;
  4655. BfIRValue vExt = CreateClassVDataExtGlobal(entry.mDeclaringMethod.mTypeInstance, typeInstance, virtIdx);
  4656. if (vExt)
  4657. vValue = mBfIRBuilder->CreateBitCast(vExt, voidPtrIRType);
  4658. }
  4659. else
  4660. {
  4661. BfMethodInstance* declaringMethodInstance = (BfMethodInstance*)entry.mDeclaringMethod;
  4662. if ((declaringMethodInstance != NULL) && (declaringMethodInstance->mMethodInstanceGroup->IsImplemented()) && (declaringMethodInstance->mIsReified))
  4663. {
  4664. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].IsImplemented());
  4665. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].mDefault->mIsReified);
  4666. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  4667. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  4668. {
  4669. BF_ASSERT(typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject));
  4670. moduleMethodInst = GetMethodInstanceAtIdx(methodInstance->mMethodInstanceGroup->mOwner, methodInstance->mMethodInstanceGroup->mMethodIdx, NULL, BfGetMethodInstanceFlag_NoInline);
  4671. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  4672. vValue = funcPtr;
  4673. }
  4674. }
  4675. }
  4676. while (origVirtTypeStack.size() != 0)
  4677. {
  4678. BfTypeInstance* useTypeInst = origVirtTypeStack[origVirtTypeStack.size() - 1];
  4679. if (virtIdx >= useTypeInst->mVirtualMethodTableSize)
  4680. {
  4681. // Moved past current base vtable size
  4682. origVirtTypeStack.pop_back();
  4683. continue;
  4684. }
  4685. if (origVirtIdx < useTypeInst->GetOrigVTableSize())
  4686. {
  4687. // We are within the original vtable size
  4688. int idx = startTabIdx + origVirtIdx;
  4689. origVirtIdx++;
  4690. vData.push_back(vValue);
  4691. }
  4692. else
  4693. {
  4694. // This is a new entry, it only gets added to the ext
  4695. BF_ASSERT(isInExts);
  4696. }
  4697. break;
  4698. }
  4699. }
  4700. if (!origVTable.empty())
  4701. typeInstance->mVirtualMethodTable = origVTable;
  4702. }
  4703. int ifaceMethodExtStart = (int)typeInstance->GetIFaceVMethodSize();
  4704. if (typeInstance->mHotTypeData != NULL)
  4705. {
  4706. if (typeInstance->mHotTypeData->mOrigInterfaceMethodsLength != -1)
  4707. ifaceMethodExtStart = typeInstance->mHotTypeData->mOrigInterfaceMethodsLength;
  4708. }
  4709. SizedArray<BfIRValue, 32> ifaceMethodExtData;
  4710. int iFaceMethodStartIdx = (int)vData.size();
  4711. vData.resize(iFaceMethodStartIdx + ifaceMethodExtStart);
  4712. for (int i = iFaceMethodStartIdx; i < iFaceMethodStartIdx + ifaceMethodExtStart; i++)
  4713. vData[i] = voidPtrNull;
  4714. if (expectNumElements != 0)
  4715. BF_ASSERT(expectNumElements == vData.size());
  4716. //BF_ASSERT(vData.size() == expectNumElements);
  4717. // for (int i = 0; i < (int)typeInstance->mInterfaceMethodTable.size() - ifaceMethodExtStart; i++)
  4718. // ifaceMethodExtData.Add(voidPtrNull);
  4719. int ifaceEntryIdx = iFaceMethodStartIdx;
  4720. for (auto& interfacePair : interfaceMap)
  4721. {
  4722. auto interfaceEntry = interfacePair.mValue.mEntry;
  4723. bool makeEmpty = false;
  4724. if (!typeInstance->IsTypeMemberAccessible(interfaceEntry->mDeclaringType, mProject))
  4725. makeEmpty = true;
  4726. int endVirtualIdx = interfaceEntry->mStartVirtualIdx + interfaceEntry->mInterfaceType->mVirtualMethodTableSize;
  4727. bool useExt = endVirtualIdx > ifaceMethodExtStart;
  4728. for (int methodIdx = 0; methodIdx < (int)interfaceEntry->mInterfaceType->mMethodInstanceGroups.size(); methodIdx++)
  4729. {
  4730. BfIRValue pushValue;
  4731. BfMethodInstance* ifaceMethodInstance = interfaceEntry->mInterfaceType->mMethodInstanceGroups[methodIdx].mDefault;
  4732. if ((ifaceMethodInstance == NULL) || (ifaceMethodInstance->mVirtualTableIdx == -1))
  4733. continue;
  4734. if ((!ifaceMethodInstance->mIsReified) || (!ifaceMethodInstance->mMethodInstanceGroup->IsImplemented()))
  4735. continue;
  4736. if (makeEmpty)
  4737. {
  4738. pushValue = voidPtrNull;
  4739. }
  4740. else
  4741. {
  4742. auto& methodRef = typeInstance->mInterfaceMethodTable[interfaceEntry->mStartInterfaceTableIdx + methodIdx].mMethodRef;
  4743. auto methodInstance = (BfMethodInstance*)methodRef;
  4744. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  4745. {
  4746. BF_ASSERT(methodInstance->mIsReified);
  4747. // This doesn't work because we may have FOREIGN methods from implicit interface methods
  4748. //auto moduleMethodInst = GetMethodInstanceAtIdx(methodRef.mTypeInstance, methodRef.mMethodNum);
  4749. auto moduleMethodInst = ReferenceExternalMethodInstance(methodInstance, BfGetMethodInstanceFlag_NoInline);
  4750. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  4751. pushValue = funcPtr;
  4752. }
  4753. else
  4754. {
  4755. pushValue = voidPtrNull;
  4756. }
  4757. }
  4758. int idx = interfaceEntry->mStartVirtualIdx + ifaceMethodInstance->mVirtualTableIdx;
  4759. if (idx < ifaceMethodExtStart)
  4760. {
  4761. BF_ASSERT(iFaceMethodStartIdx + idx < (int)vData.size());
  4762. vData[iFaceMethodStartIdx + idx] = pushValue;
  4763. }
  4764. else
  4765. {
  4766. BF_ASSERT(useExt);
  4767. int extIdx = idx - ifaceMethodExtStart;
  4768. while (extIdx >= ifaceMethodExtData.size())
  4769. ifaceMethodExtData.Add(voidPtrNull);
  4770. ifaceMethodExtData[extIdx] = pushValue;
  4771. }
  4772. }
  4773. }
  4774. if (typeInstance->IsBoxed())
  4775. {
  4776. BfBoxedType* boxedType = (BfBoxedType*)typeInstance;
  4777. if (boxedType->IsBoxedStructPtr())
  4778. {
  4779. // Force override of GetHashCode so we use the pointer address as the hash code
  4780. checkTypeInst = CreateBoxedType(ResolveTypeDef(mCompiler->mPointerTypeDef));
  4781. // Force override of GetHashCode so we use the pointer address as the hash code
  4782. for (auto& checkIFace : checkTypeInst->mInterfaces)
  4783. {
  4784. for (int methodIdx = 0; methodIdx < (int)checkIFace.mInterfaceType->mMethodInstanceGroups.size(); methodIdx++)
  4785. {
  4786. BfIRValue pushValue;
  4787. BfMethodInstance* ifaceMethodInstance = checkIFace.mInterfaceType->mMethodInstanceGroups[methodIdx].mDefault;
  4788. if ((ifaceMethodInstance == NULL) || (ifaceMethodInstance->mVirtualTableIdx == -1))
  4789. continue;
  4790. if ((!ifaceMethodInstance->mIsReified) || (!ifaceMethodInstance->mMethodInstanceGroup->IsImplemented()))
  4791. continue;
  4792. auto& methodRef = checkTypeInst->mInterfaceMethodTable[checkIFace.mStartInterfaceTableIdx + methodIdx].mMethodRef;
  4793. auto methodInstance = (BfMethodInstance*)methodRef;
  4794. BF_ASSERT(methodInstance->mIsReified);
  4795. // This doesn't work because we may have FOREIGN methods from implicit interface methods
  4796. //auto moduleMethodInst = GetMethodInstanceAtIdx(methodRef.mTypeInstance, methodRef.mMethodNum);
  4797. auto moduleMethodInst = ReferenceExternalMethodInstance(methodInstance, BfGetMethodInstanceFlag_NoInline);
  4798. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  4799. int idx = checkIFace.mStartVirtualIdx + ifaceMethodInstance->mVirtualTableIdx;
  4800. vData[iFaceMethodStartIdx + idx] = funcPtr;
  4801. }
  4802. }
  4803. }
  4804. }
  4805. if ((needsVData) && (!typeInstance->mTypeDef->mIsStatic))
  4806. {
  4807. BfIRValue ifaceMethodExtVar;
  4808. if (!ifaceMethodExtData.IsEmpty())
  4809. {
  4810. StringT<128> classVDataName;
  4811. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), typeInstance, "bf_hs_replace_IFaceExt");
  4812. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), (int)ifaceMethodExtData.size());
  4813. ifaceMethodExtVar = mBfIRBuilder->CreateGlobalVariable(arrayType, true,
  4814. BfIRLinkageType_External, BfIRValue(), classVDataName);
  4815. BfIRType extVTableType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)ifaceMethodExtData.size());
  4816. BfIRValue extVTableConst = mBfIRBuilder->CreateConstArray(extVTableType, ifaceMethodExtData);
  4817. mBfIRBuilder->GlobalVar_SetInitializer(ifaceMethodExtVar, extVTableConst);
  4818. }
  4819. for (auto& ifaceInstPair : interfaceMap)
  4820. {
  4821. auto interfaceEntry = ifaceInstPair.mValue.mEntry;
  4822. int slotNum = interfaceEntry->mInterfaceType->mSlotNum;
  4823. if (slotNum >= 0)
  4824. {
  4825. BfIRValue vtablePtr;
  4826. int idx = interfaceEntry->mStartVirtualIdx;
  4827. int endVirtualIdx = interfaceEntry->mStartVirtualIdx + interfaceEntry->mInterfaceType->mVirtualMethodTableSize;
  4828. if (endVirtualIdx > ifaceMethodExtStart)
  4829. vtablePtr = mBfIRBuilder->CreateInBoundsGEP(ifaceMethodExtVar, 0, interfaceEntry->mStartVirtualIdx - ifaceMethodExtStart);
  4830. else
  4831. vtablePtr = mBfIRBuilder->CreateInBoundsGEP(classVDataVar, 0, iFaceMethodStartIdx + interfaceEntry->mStartVirtualIdx);
  4832. int slotVirtIdx = slotNum + vDataOfs;
  4833. if (vData[slotVirtIdx] == voidPtrNull)
  4834. {
  4835. vData[slotVirtIdx] = mBfIRBuilder->CreateBitCast(vtablePtr, voidPtrIRType);
  4836. }
  4837. else
  4838. {
  4839. if (mCompiler->IsHotCompile())
  4840. Fail("Interface slot collision error. Restart program or undo interface changes.", typeDef->GetRefNode());
  4841. else
  4842. Fail("Interface slot collision error", typeDef->GetRefNode());
  4843. }
  4844. }
  4845. }
  4846. }
  4847. }
  4848. BfIRValue typeNameConst;
  4849. BfIRValue namespaceConst;
  4850. if (needsTypeNames)
  4851. {
  4852. typeNameConst = GetStringObjectValue(typeDef->mName->mString, true);
  4853. namespaceConst = GetStringObjectValue(typeDef->mNamespace.ToString(), true);
  4854. }
  4855. else
  4856. {
  4857. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  4858. typeNameConst = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(stringType));
  4859. namespaceConst = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(stringType));
  4860. }
  4861. int baseTypeId = 0;
  4862. if (typeInstance->mBaseType != NULL)
  4863. {
  4864. baseTypeId = typeInstance->mBaseType->mTypeId;
  4865. }
  4866. BfTypeOptions* typeOptions = NULL;
  4867. if (typeInstance->mTypeOptionsIdx >= 0)
  4868. typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  4869. SizedArray<BfIRValue, 16> customAttrs;
  4870. BfTypeInstance* attributeType = mContext->mUnreifiedModule->ResolveTypeDef(mCompiler->mAttributeTypeDef)->ToTypeInstance();
  4871. BfIRValue castedClassVData;
  4872. if (classVDataVar)
  4873. castedClassVData = mBfIRBuilder->CreateBitCast(classVDataVar, mBfIRBuilder->MapType(mContext->mBfClassVDataPtrType));
  4874. else
  4875. castedClassVData = GetDefaultValue(mContext->mBfClassVDataPtrType);
  4876. bool freflectIncludeTypeData = false;
  4877. bool reflectIncludeAllFields = false;
  4878. bool reflectIncludeAllMethods = false;
  4879. if (TypeIsSubTypeOf(typeInstance, attributeType))
  4880. {
  4881. reflectIncludeAllFields = true;
  4882. reflectIncludeAllMethods = true;
  4883. }
  4884. BfReflectKind reflectKind = BfReflectKind_Type;
  4885. auto _GetReflectUserFromDirective = [&](BfAttributeDirective* attributesDirective, BfAttributeTargets attrTarget)
  4886. {
  4887. BfReflectKind reflectKind = BfReflectKind_None;
  4888. auto customAttrs = GetCustomAttributes(attributesDirective, attrTarget);
  4889. if (customAttrs != NULL)
  4890. {
  4891. for (auto& attr : customAttrs->mAttributes)
  4892. {
  4893. reflectKind = (BfReflectKind)(reflectKind | GetUserReflectKind(attr.mType));
  4894. }
  4895. }
  4896. return reflectKind;
  4897. };
  4898. reflectKind = GetReflectKind(reflectKind, typeInstance);
  4899. // Fields
  4900. BfType* reflectFieldDataType = ResolveTypeDef(mCompiler->mReflectFieldDataDef);
  4901. BfIRValue emptyValueType = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance()->mBaseType), SizedArray<BfIRValue, 1>());
  4902. auto _HandleCustomAttrs = [&](BfCustomAttributes* customAttributes)
  4903. {
  4904. if (customAttributes == NULL)
  4905. return -1;
  4906. Array<BfCustomAttribute*> reflectAttributes;
  4907. for (auto& attr : customAttributes->mAttributes)
  4908. {
  4909. bool wantAttribute = false;
  4910. if (attr.mType->mCustomAttributes != NULL)
  4911. {
  4912. auto usageAttribute = attr.mType->mCustomAttributes->Get(mCompiler->mAttributeUsageAttributeTypeDef);
  4913. if (usageAttribute != NULL)
  4914. {
  4915. // Check for Flags arg
  4916. if (usageAttribute->mCtorArgs.size() < 2)
  4917. continue;
  4918. auto constant = attr.mType->mConstHolder->GetConstant(usageAttribute->mCtorArgs[1]);
  4919. if (constant == NULL)
  4920. continue;
  4921. if (constant->mTypeCode == BfTypeCode_Boolean)
  4922. continue;
  4923. if ((constant->mInt8 & BfCustomAttributeFlags_ReflectAttribute) != 0)
  4924. wantAttribute = true;
  4925. }
  4926. }
  4927. if ((wantAttribute) && (attr.mType->mIsReified))
  4928. {
  4929. reflectAttributes.Add(&attr);
  4930. }
  4931. }
  4932. if (reflectAttributes.size() == 0)
  4933. return -1;
  4934. #define PUSH_INT8(val) data.push_back((uint8)val)
  4935. #define PUSH_INT16(val) { data.push_back(val & 0xFF); data.push_back((val >> 8) & 0xFF); }
  4936. #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); }
  4937. #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); \
  4938. data.push_back((val >> 32) & 0xFF); data.push_back((val >> 40) & 0xFF); data.push_back((val >> 48) & 0xFF); data.push_back((val >> 56) & 0xFF); }
  4939. SizedArray<uint8, 16> data;
  4940. int customAttrIdx = (int)customAttrs.size();
  4941. data.push_back((uint8)reflectAttributes.size());
  4942. for (auto attr : reflectAttributes)
  4943. {
  4944. // Size prefix
  4945. int sizeIdx = (int)data.size();
  4946. PUSH_INT16(0); // mSize
  4947. PUSH_INT32(attr->mType->mTypeId); // mType
  4948. PUSH_INT16(attr->mCtor->mIdx);
  4949. auto ctorMethodInstance = GetRawMethodInstanceAtIdx(attr->mType, attr->mCtor->mIdx);
  4950. int argIdx = 0;
  4951. for (auto arg : attr->mCtorArgs)
  4952. {
  4953. auto constant = typeInstance->mConstHolder->GetConstant(arg);
  4954. bool handled = false;
  4955. if (constant != NULL)
  4956. {
  4957. auto argType = ctorMethodInstance->GetParamType(argIdx);
  4958. if (argType->IsObject())
  4959. {
  4960. BF_ASSERT(argType->ToTypeInstance()->mTypeDef == mCompiler->mStringTypeDef);
  4961. int stringId = constant->mInt32;
  4962. int* orderedIdPtr;
  4963. if (usedStringIdMap.TryAdd(stringId, NULL, &orderedIdPtr))
  4964. {
  4965. *orderedIdPtr = (int)usedStringIdMap.size() - 1;
  4966. }
  4967. GetStringObjectValue(stringId);
  4968. PUSH_INT8(0xFF); // String
  4969. PUSH_INT32(*orderedIdPtr);
  4970. argIdx++;
  4971. continue;
  4972. }
  4973. if (argType->IsPointer())
  4974. {
  4975. if (argType->GetUnderlyingType() == GetPrimitiveType(BfTypeCode_Char8))
  4976. {
  4977. if (constant->mTypeCode == BfTypeCode_StringId)
  4978. {
  4979. int stringId = constant->mInt32;
  4980. int* orderedIdPtr;
  4981. if (usedStringIdMap.TryAdd(stringId, NULL, &orderedIdPtr))
  4982. {
  4983. *orderedIdPtr = (int)usedStringIdMap.size() - 1;
  4984. }
  4985. GetStringObjectValue(stringId);
  4986. PUSH_INT8(0xFF); // String
  4987. PUSH_INT32(*orderedIdPtr);
  4988. argIdx++;
  4989. continue;
  4990. }
  4991. }
  4992. }
  4993. PUSH_INT8(constant->mTypeCode);
  4994. if ((constant->mTypeCode == BfTypeCode_Int64) ||
  4995. (constant->mTypeCode == BfTypeCode_UInt64) ||
  4996. (constant->mTypeCode == BfTypeCode_Double))
  4997. {
  4998. PUSH_INT64(constant->mInt64);
  4999. }
  5000. else if ((constant->mTypeCode == BfTypeCode_Int32) ||
  5001. (constant->mTypeCode == BfTypeCode_UInt32) ||
  5002. (constant->mTypeCode == BfTypeCode_Char32))
  5003. {
  5004. PUSH_INT32(constant->mInt32);
  5005. }
  5006. else if (constant->mTypeCode == BfTypeCode_Float)
  5007. {
  5008. float val = (float)constant->mDouble;
  5009. PUSH_INT32(*(int*)&val);
  5010. }
  5011. else if ((constant->mTypeCode == BfTypeCode_Int16) ||
  5012. (constant->mTypeCode == BfTypeCode_UInt16) ||
  5013. (constant->mTypeCode == BfTypeCode_Char16))
  5014. {
  5015. PUSH_INT16(constant->mInt16);
  5016. }
  5017. else if ((constant->mTypeCode == BfTypeCode_Int8) ||
  5018. (constant->mTypeCode == BfTypeCode_UInt8) ||
  5019. (constant->mTypeCode == BfTypeCode_Boolean) ||
  5020. (constant->mTypeCode == BfTypeCode_Char8))
  5021. {
  5022. PUSH_INT8(constant->mInt8);
  5023. }
  5024. else
  5025. {
  5026. Fail(StrFormat("Unhandled attribute constant data in '%s'", TypeToString(type).c_str()));
  5027. }
  5028. }
  5029. else if (!handled)
  5030. {
  5031. BFMODULE_FATAL(this, "Unhandled");
  5032. }
  5033. argIdx++;
  5034. }
  5035. int size = (int)data.size() - sizeIdx;
  5036. *((uint16*)&data[sizeIdx]) = size;
  5037. }
  5038. #undef PUSH_INT8
  5039. #undef PUSH_INT16
  5040. #undef PUSH_INT32
  5041. SizedArray<BfIRValue, 16> dataValues;
  5042. for (uint8 val : data)
  5043. dataValues.push_back(GetConstValue8(val));
  5044. auto dataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(byteType), (int)data.size());
  5045. auto customAttrConst = mBfIRBuilder->CreateConstArray(dataArrayType, dataValues);
  5046. BfIRValue customAttrArray = mBfIRBuilder->CreateGlobalVariable(dataArrayType, true, BfIRLinkageType_Internal,
  5047. customAttrConst, typeDataName + StrFormat(".customAttr%d", customAttrIdx));
  5048. BfIRValue customAttrArrayPtr = mBfIRBuilder->CreateBitCast(customAttrArray, voidPtrIRType);
  5049. customAttrs.push_back(customAttrArrayPtr);
  5050. return customAttrIdx;
  5051. };
  5052. int typeCustomAttrIdx = _HandleCustomAttrs(typeInstance->mCustomAttributes);
  5053. SizedArray<int, 16> reflectFieldIndices;
  5054. for (int pass = 0; pass < 2; pass++)
  5055. {
  5056. bool skippedField = false;
  5057. reflectFieldIndices.clear();
  5058. for (int fieldIdx = 0; fieldIdx < (int)typeInstance->mFieldInstances.size(); fieldIdx++)
  5059. {
  5060. BfFieldInstance* fieldInstance = &typeInstance->mFieldInstances[fieldIdx];
  5061. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  5062. if (fieldDef == NULL)
  5063. continue;
  5064. auto fieldReflectKind = (BfReflectKind)(reflectKind & ~BfReflectKind_User);
  5065. bool includeField = reflectIncludeAllFields;
  5066. if (fieldInstance->mCustomAttributes != NULL)
  5067. {
  5068. for (auto& customAttr : fieldInstance->mCustomAttributes->mAttributes)
  5069. {
  5070. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  5071. {
  5072. includeField = true;
  5073. }
  5074. else
  5075. {
  5076. auto userReflectKind = GetUserReflectKind(customAttr.mType);
  5077. fieldReflectKind = (BfReflectKind)(fieldReflectKind | userReflectKind);
  5078. }
  5079. }
  5080. }
  5081. if ((fieldReflectKind & BfReflectKind_User) != 0)
  5082. includeField = true;
  5083. if ((!fieldDef->mIsStatic) && ((fieldReflectKind & BfReflectKind_NonStaticFields) != 0))
  5084. includeField = true;
  5085. if ((fieldDef->mIsStatic) && ((fieldReflectKind & BfReflectKind_StaticFields) != 0))
  5086. includeField = true;
  5087. if ((!fieldDef->mIsStatic) && (typeOptions != NULL))
  5088. includeField = typeOptions->Apply(includeField, BfOptionFlags_ReflectNonStaticFields);
  5089. if ((fieldDef->mIsStatic) && (typeOptions != NULL))
  5090. includeField = typeOptions->Apply(includeField, BfOptionFlags_ReflectStaticFields);
  5091. includeField |= forceReflectFields;
  5092. if (!includeField)
  5093. {
  5094. skippedField = true;
  5095. continue;
  5096. }
  5097. reflectFieldIndices.Add(fieldIdx);
  5098. }
  5099. // For a splattable type, we need to either include all fields or zero fields. This is to allow us to correctly splat
  5100. // params for reflected method calls even if we don't have reflection field info for the splatted type. This is
  5101. // possible because we write out a SplatData structure containing just TypeIds in that case
  5102. if (pass == 0)
  5103. {
  5104. if (!typeInstance->IsSplattable())
  5105. break;
  5106. if (!skippedField)
  5107. break;
  5108. if (reflectFieldIndices.size() == 0)
  5109. break;
  5110. }
  5111. }
  5112. SizedArray<BfIRValue, 16> fieldTypes;
  5113. enum FieldFlags
  5114. {
  5115. FieldFlags_Protected = 3,
  5116. FieldFlags_Public = 6,
  5117. FieldFlags_Static = 0x10,
  5118. FieldFlags_Const = 0x40,
  5119. FieldFlags_SpecialName = 0x80,
  5120. FieldFlags_EnumPayload = 0x100,
  5121. FieldFlags_EnumDiscriminator = 0x200
  5122. };
  5123. if ((typeInstance->IsPayloadEnum()) && (!typeInstance->IsBoxed()))
  5124. {
  5125. BfType* payloadType = typeInstance->GetUnionInnerType();
  5126. if (!payloadType->IsValuelessType())
  5127. {
  5128. BfIRValue payloadNameConst = GetStringObjectValue("$payload", true);
  5129. SizedArray<BfIRValue, 8> payloadFieldVals =
  5130. {
  5131. emptyValueType,
  5132. payloadNameConst, // mName
  5133. GetConstValue(0, intPtrType), // mData
  5134. GetConstValue(payloadType->mTypeId, typeIdType), // mFieldTypeId
  5135. GetConstValue(FieldFlags_SpecialName | FieldFlags_EnumPayload, shortType), // mFlags
  5136. GetConstValue(-1, intType), // mCustomAttributesIdx
  5137. };
  5138. auto payloadFieldData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance(), BfIRPopulateType_Full), payloadFieldVals);
  5139. fieldTypes.push_back(payloadFieldData);
  5140. }
  5141. BfType* dscrType = typeInstance->GetDiscriminatorType();
  5142. BfIRValue dscrNameConst = GetStringObjectValue("$discriminator", true);
  5143. SizedArray<BfIRValue, 8> dscrFieldVals =
  5144. {
  5145. emptyValueType,
  5146. dscrNameConst, // mName
  5147. GetConstValue(BF_ALIGN(payloadType->mSize, dscrType->mAlign), intPtrType), // mData
  5148. GetConstValue(dscrType->mTypeId, typeIdType), // mFieldTypeId
  5149. GetConstValue(FieldFlags_SpecialName | FieldFlags_EnumDiscriminator, shortType), // mFlags
  5150. GetConstValue(-1, intType), // mCustomAttributesIdx
  5151. };
  5152. auto dscrFieldData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance(), BfIRPopulateType_Full), dscrFieldVals);
  5153. fieldTypes.push_back(dscrFieldData);
  5154. }
  5155. for (auto fieldIdx : reflectFieldIndices)
  5156. {
  5157. if (!needsTypeData)
  5158. break;
  5159. BfFieldInstance* fieldInstance = &typeInstance->mFieldInstances[fieldIdx];
  5160. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  5161. BfIRValue fieldNameConst = GetStringObjectValue(fieldDef->mName, true);
  5162. int typeId = 0;
  5163. auto fieldType = fieldInstance->GetResolvedType();
  5164. if (fieldType->IsGenericParam())
  5165. {
  5166. //TODO:
  5167. }
  5168. else
  5169. typeId = fieldType->mTypeId;
  5170. FieldFlags fieldFlags = (FieldFlags)0;
  5171. if (fieldDef->mProtection == BfProtection_Protected)
  5172. fieldFlags = (FieldFlags)(fieldFlags | FieldFlags_Protected);
  5173. if (fieldDef->mProtection == BfProtection_Public)
  5174. fieldFlags = (FieldFlags)(fieldFlags | FieldFlags_Public);
  5175. if (fieldDef->mIsStatic)
  5176. fieldFlags = (FieldFlags)(fieldFlags | FieldFlags_Static);
  5177. if (fieldDef->mIsConst)
  5178. fieldFlags = (FieldFlags)(fieldFlags | FieldFlags_Const);
  5179. int customAttrIdx = _HandleCustomAttrs(fieldInstance->mCustomAttributes);
  5180. BfIRValue constValue;
  5181. if (fieldInstance->GetFieldDef()->mIsConst)
  5182. {
  5183. if (fieldInstance->mConstIdx != -1)
  5184. {
  5185. auto constant = typeInstance->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  5186. constValue = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, constant->mUInt64);
  5187. }
  5188. }
  5189. else if (fieldInstance->GetFieldDef()->mIsStatic)
  5190. {
  5191. auto refVal = ReferenceStaticField(fieldInstance);
  5192. if (refVal.mValue.IsConst())
  5193. {
  5194. auto constant = mBfIRBuilder->GetConstant(refVal.mValue);
  5195. if (constant->mConstType == BfConstType_GlobalVar)
  5196. {
  5197. auto globalVar = (BfGlobalVar*)constant;
  5198. if (globalVar->mName[0] == '#')
  5199. refVal = BfTypedValue();
  5200. }
  5201. }
  5202. if (refVal.IsAddr())
  5203. {
  5204. constValue = mBfIRBuilder->CreatePtrToInt(refVal.mValue, BfTypeCode_IntPtr);
  5205. }
  5206. }
  5207. if (!constValue)
  5208. constValue = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, fieldInstance->mDataOffset);
  5209. SizedArray<BfIRValue, 8> fieldVals =
  5210. {
  5211. emptyValueType,
  5212. fieldNameConst, // mName
  5213. constValue, // mConstValue
  5214. GetConstValue(typeId, typeIdType), // mFieldTypeId
  5215. GetConstValue(fieldFlags, shortType), // mFlags
  5216. GetConstValue(customAttrIdx, intType), // mCustomAttributesIdx
  5217. };
  5218. auto fieldData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance(), BfIRPopulateType_Full), fieldVals);
  5219. fieldTypes.push_back(fieldData);
  5220. }
  5221. auto reflectFieldDataIRType = mBfIRBuilder->MapType(reflectFieldDataType);
  5222. BfIRValue fieldDataPtr;
  5223. BfIRType fieldDataPtrType = mBfIRBuilder->GetPointerTo(reflectFieldDataIRType);
  5224. if (fieldTypes.size() == 0)
  5225. {
  5226. if ((type->IsSplattable()) && (type->IsStruct()) && (!type->IsValuelessType()) && (!typeInstance->mIsCRepr))
  5227. {
  5228. BfTypeInstance* reflectFieldSplatDataType = ResolveTypeDef(mCompiler->mReflectFieldSplatDataDef)->ToTypeInstance();
  5229. SizedArray<BfIRValue, 3> splatTypes;
  5230. SizedArray<BfIRValue, 3> splatOffsets;
  5231. std::function<void(BfType*, int)> _CheckSplat = [&](BfType* checkType, int offset)
  5232. {
  5233. auto checkTypeInstance = checkType->ToTypeInstance();
  5234. if ((checkTypeInstance != NULL) && (checkTypeInstance->IsValueType()) && (checkTypeInstance->IsDataIncomplete()))
  5235. PopulateType(checkTypeInstance);
  5236. if (checkType->IsStruct())
  5237. {
  5238. int dataEnd = offset;
  5239. if (checkTypeInstance->mBaseType != NULL)
  5240. _CheckSplat(checkTypeInstance->mBaseType, offset);
  5241. if (checkTypeInstance->mIsUnion)
  5242. {
  5243. BfType* unionInnerType = checkTypeInstance->GetUnionInnerType();
  5244. _CheckSplat(unionInnerType, offset);
  5245. }
  5246. else
  5247. {
  5248. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  5249. {
  5250. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  5251. if (fieldInstance->mDataIdx >= 0)
  5252. {
  5253. _CheckSplat(fieldInstance->GetResolvedType(), offset + fieldInstance->mDataOffset);
  5254. dataEnd = offset + fieldInstance->mDataOffset + fieldInstance->mResolvedType->mSize;
  5255. }
  5256. }
  5257. }
  5258. if (checkTypeInstance->IsEnum())
  5259. {
  5260. // Add discriminator
  5261. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  5262. if (!checkTypeInstance->mIsPacked)
  5263. dataEnd = BF_ALIGN(dataEnd, dscrType->mAlign);
  5264. _CheckSplat(dscrType, dataEnd);
  5265. }
  5266. }
  5267. else if (checkType->IsMethodRef())
  5268. {
  5269. // auto methodRefType = (BfMethodRefType*)checkType;
  5270. // for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  5271. // {
  5272. // if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  5273. // _CheckSplat(methodRefType->GetCaptureType(dataIdx), offsetof);
  5274. // else
  5275. // dataLambda(methodRefType->GetCaptureType(dataIdx));
  5276. // }
  5277. }
  5278. else if (!checkType->IsValuelessType())
  5279. {
  5280. splatTypes.Add(GetConstValue(checkType->mTypeId, typeIdType));
  5281. splatOffsets.Add(GetConstValue(offset, intType));
  5282. }
  5283. };
  5284. _CheckSplat(type, 0);
  5285. while (splatTypes.size() < 3)
  5286. {
  5287. splatTypes.Add(GetConstValue(0, typeIdType));
  5288. splatOffsets.Add(GetConstValue(0, intType));
  5289. }
  5290. BfIRValue splatTypesConst = mBfIRBuilder->CreateConstArray(mBfIRBuilder->MapType(reflectFieldSplatDataType->mFieldInstances[0].mResolvedType), splatTypes);
  5291. BfIRValue splatOffsetsConst = mBfIRBuilder->CreateConstArray(mBfIRBuilder->MapType(reflectFieldSplatDataType->mFieldInstances[1].mResolvedType), splatOffsets);
  5292. SizedArray<BfIRValue, 8> splatVals =
  5293. {
  5294. emptyValueType,
  5295. splatTypesConst,
  5296. splatOffsetsConst
  5297. };
  5298. auto fieldSplatData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectFieldSplatDataType->ToTypeInstance(), BfIRPopulateType_Full), splatVals);
  5299. BfIRValue fieldDataArray = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(reflectFieldSplatDataType), true, BfIRLinkageType_Internal,
  5300. fieldSplatData, typeDataName + ".splats");
  5301. fieldDataPtr = mBfIRBuilder->CreateBitCast(fieldDataArray, fieldDataPtrType);
  5302. }
  5303. else
  5304. fieldDataPtr = mBfIRBuilder->CreateConstNull(fieldDataPtrType);
  5305. }
  5306. else
  5307. {
  5308. BfIRType fieldDataConstType = mBfIRBuilder->GetSizedArrayType(reflectFieldDataIRType, (int)fieldTypes.size());
  5309. BfIRValue fieldDataConst = mBfIRBuilder->CreateConstArray(fieldDataConstType, fieldTypes);
  5310. BfIRValue fieldDataArray = mBfIRBuilder->CreateGlobalVariable(fieldDataConstType, true, BfIRLinkageType_Internal,
  5311. fieldDataConst, "fields." + typeDataName);
  5312. fieldDataPtr = mBfIRBuilder->CreateBitCast(fieldDataArray, fieldDataPtrType);
  5313. }
  5314. /// Methods
  5315. BfType* reflectMethodDataType = ResolveTypeDef(mCompiler->mReflectMethodDataDef);
  5316. BfType* reflectParamDataType = ResolveTypeDef(mCompiler->mReflectParamDataDef);
  5317. BfType* reflectParamDataPtrType = CreatePointerType(reflectParamDataType);
  5318. SizedArray<BfIRValue, 16> methodTypes;
  5319. for (int methodIdx = 0; methodIdx < (int)typeDef->mMethods.size(); methodIdx++)
  5320. {
  5321. if (!needsTypeData)
  5322. break;
  5323. auto methodInstanceGroup = &typeInstance->mMethodInstanceGroups[methodIdx];
  5324. if (!methodInstanceGroup->IsImplemented())
  5325. continue;
  5326. auto methodDef = typeDef->mMethods[methodIdx];
  5327. if (methodDef->mIsNoReflect)
  5328. continue;
  5329. auto defaultMethod = methodInstanceGroup->mDefault;
  5330. if (defaultMethod == NULL)
  5331. continue;
  5332. if (defaultMethod->mIsUnspecialized)
  5333. continue;
  5334. if (!defaultMethod->mIsReified)
  5335. continue;
  5336. if ((defaultMethod->mChainType == BfMethodChainType_ChainMember) || (defaultMethod->mChainType == BfMethodChainType_ChainSkip))
  5337. continue;
  5338. if (defaultMethod->mMethodDef->mMethodType == BfMethodType_CtorNoBody)
  5339. continue;
  5340. auto methodReflectKind = (BfReflectKind)(reflectKind & ~BfReflectKind_User);
  5341. bool includeMethod = reflectIncludeAllMethods;
  5342. BfCustomAttributes* methodCustomAttributes = NULL;
  5343. if ((defaultMethod->mMethodInfoEx != NULL) && (defaultMethod->mMethodInfoEx->mMethodCustomAttributes != NULL) && (defaultMethod->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes != NULL))
  5344. {
  5345. methodCustomAttributes = defaultMethod->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes;
  5346. for (auto& customAttr : defaultMethod->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes->mAttributes)
  5347. {
  5348. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  5349. {
  5350. includeMethod = true;
  5351. }
  5352. else
  5353. {
  5354. auto userReflectKind = GetUserReflectKind(customAttr.mType);
  5355. methodReflectKind = (BfReflectKind)(methodReflectKind | userReflectKind);
  5356. }
  5357. }
  5358. }
  5359. if (!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, mProject))
  5360. continue;
  5361. if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  5362. {
  5363. for (BfParameterDeclaration* paramDecl : methodDeclaration->mParams)
  5364. {
  5365. if (paramDecl->mAttributes != NULL)
  5366. methodReflectKind = (BfReflectKind)(methodReflectKind | _GetReflectUserFromDirective(paramDecl->mAttributes, BfAttributeTargets_Parameter));
  5367. }
  5368. if (methodDeclaration->mReturnAttributes != NULL)
  5369. methodReflectKind = (BfReflectKind)(methodReflectKind | _GetReflectUserFromDirective(methodDeclaration->mReturnAttributes, BfAttributeTargets_ReturnValue));
  5370. }
  5371. if ((methodReflectKind & (BfReflectKind_Methods | BfReflectKind_User)) != 0)
  5372. includeMethod = true;
  5373. if ((methodDef->mIsStatic) && ((methodReflectKind & BfReflectKind_StaticMethods) != 0))
  5374. includeMethod = true;
  5375. if ((!includeMethod) && (typeOptions != NULL))
  5376. includeMethod = ApplyTypeOptionMethodFilters(includeMethod, methodDef, typeOptions);
  5377. if (!includeMethod)
  5378. continue;
  5379. BfModuleMethodInstance moduleMethodInstance;
  5380. BfIRValue funcVal = voidPtrNull;
  5381. if (((!typeInstance->IsBoxed()) || (!methodDef->mIsStatic)) &&
  5382. (!typeInstance->IsUnspecializedType()) &&
  5383. (methodDef->mMethodType != BfMethodType_Ignore) &&
  5384. (methodDef->mMethodType != BfMethodType_Mixin) &&
  5385. (!methodDef->mIsAbstract) &&
  5386. (methodDef->mGenericParams.size() == 0))
  5387. {
  5388. moduleMethodInstance = GetMethodInstanceAtIdx(typeInstance, methodIdx, NULL, BfGetMethodInstanceFlag_NoInline);
  5389. if (moduleMethodInstance.mFunc)
  5390. funcVal = mBfIRBuilder->CreateBitCast(moduleMethodInstance.mFunc, voidPtrIRType);
  5391. }
  5392. BfIRValue methodNameConst = GetStringObjectValue(methodDef->mName, true);
  5393. enum MethodFlags
  5394. {
  5395. MethodFlags_Protected = 3,
  5396. MethodFlags_Public = 6,
  5397. MethodFlags_Static = 0x10,
  5398. MethodFlags_Virtual = 0x40,
  5399. MethodFlags_StdCall = 0x1000,
  5400. MethodFlags_FastCall = 0x2000,
  5401. MethodFlags_ThisCall = 0x3000,
  5402. MethodFlags_Mutating = 0x4000,
  5403. MethodFlags_Constructor = 0x8000,
  5404. };
  5405. MethodFlags methodFlags = (MethodFlags)0;
  5406. if (methodDef->mProtection == BfProtection_Protected)
  5407. methodFlags = (MethodFlags)(methodFlags | MethodFlags_Protected);
  5408. if (methodDef->mProtection == BfProtection_Public)
  5409. methodFlags = (MethodFlags)(methodFlags | MethodFlags_Public);
  5410. if (methodDef->mIsStatic)
  5411. methodFlags = (MethodFlags)(methodFlags | MethodFlags_Static);
  5412. if ((methodDef->mIsVirtual) || (moduleMethodInstance.mMethodInstance->mVirtualTableIdx != -1))
  5413. methodFlags = (MethodFlags)(methodFlags | MethodFlags_Virtual);
  5414. if (methodDef->mCallingConvention == BfCallingConvention_Fastcall)
  5415. methodFlags = (MethodFlags)(methodFlags | MethodFlags_FastCall);
  5416. if (methodDef->mIsMutating)
  5417. methodFlags = (MethodFlags)(methodFlags | MethodFlags_Mutating);
  5418. if (methodDef->mMethodType == BfMethodType_Ctor)
  5419. methodFlags = (MethodFlags)(methodFlags | MethodFlags_Constructor);
  5420. auto callingConvention = GetIRCallingConvention(defaultMethod);
  5421. if (callingConvention == BfIRCallingConv_ThisCall)
  5422. methodFlags = (MethodFlags)(methodFlags | MethodFlags_ThisCall);
  5423. else if (callingConvention == BfIRCallingConv_StdCall)
  5424. methodFlags = (MethodFlags)(methodFlags | MethodFlags_StdCall);
  5425. else if (callingConvention == BfIRCallingConv_FastCall)
  5426. methodFlags = (MethodFlags)(methodFlags | MethodFlags_FastCall);
  5427. int customAttrIdx = _HandleCustomAttrs(methodCustomAttributes);
  5428. enum ParamFlags
  5429. {
  5430. ParamFlag_None = 0,
  5431. ParamFlag_Splat = 1,
  5432. ParamFlag_Implicit = 2,
  5433. };
  5434. SizedArray<BfIRValue, 8> paramVals;
  5435. for (int paramIdx = 0; paramIdx < defaultMethod->GetParamCount(); paramIdx++)
  5436. {
  5437. String paramName = defaultMethod->GetParamName(paramIdx);
  5438. BfType* paramType = defaultMethod->GetParamType(paramIdx);
  5439. ParamFlags paramFlags = ParamFlag_None;
  5440. if (defaultMethod->GetParamIsSplat(paramIdx))
  5441. paramFlags = (ParamFlags)(paramFlags | ParamFlag_Splat);
  5442. BfIRValue paramNameConst = GetStringObjectValue(paramName, true);
  5443. SizedArray<BfIRValue, 8> paramDataVals =
  5444. {
  5445. emptyValueType,
  5446. paramNameConst,
  5447. GetConstValue(paramType->mTypeId, typeIdType),
  5448. GetConstValue((int32)paramFlags, shortType),
  5449. GetConstValue(customAttrIdx, intType) // defaultIdx
  5450. };
  5451. auto paramData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapType(reflectParamDataType, BfIRPopulateType_Full), paramDataVals);
  5452. paramVals.Add(paramData);
  5453. }
  5454. BfIRValue paramsVal;
  5455. if (paramVals.size() > 0)
  5456. {
  5457. BfIRType paramDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(reflectParamDataType, BfIRPopulateType_Full), (int)paramVals.size());
  5458. BfIRValue paramDataConst = mBfIRBuilder->CreateConstArray(paramDataArrayType, paramVals);
  5459. BfIRValue paramDataArray = mBfIRBuilder->CreateGlobalVariable(paramDataArrayType, true, BfIRLinkageType_Internal,
  5460. paramDataConst, typeDataName + StrFormat(".params%d", methodIdx));
  5461. paramsVal = mBfIRBuilder->CreateBitCast(paramDataArray, mBfIRBuilder->MapType(reflectParamDataPtrType));
  5462. }
  5463. else
  5464. paramsVal = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(reflectParamDataPtrType));
  5465. int vDataVal = -1;
  5466. if (defaultMethod->mVirtualTableIdx != -1)
  5467. {
  5468. int vDataIdx = -1;
  5469. if (type->IsInterface())
  5470. {
  5471. vDataIdx = defaultMethod->mVirtualTableIdx;
  5472. }
  5473. else
  5474. {
  5475. vDataIdx = 1 + mCompiler->GetDynCastVDataCount() + mCompiler->mMaxInterfaceSlots;
  5476. if ((mCompiler->mOptions.mHasVDataExtender) && (mCompiler->IsHotCompile()))
  5477. {
  5478. auto typeInst = defaultMethod->mMethodInstanceGroup->mOwner;
  5479. int extMethodIdx = (defaultMethod->mVirtualTableIdx - typeInst->GetImplBaseVTableSize()) - typeInst->GetOrigSelfVTableSize();
  5480. if (extMethodIdx >= 0)
  5481. {
  5482. // Extension?
  5483. int vExtOfs = typeInst->GetOrigImplBaseVTableSize();
  5484. vDataVal = ((vDataIdx + vExtOfs + 1) << 20) | (extMethodIdx);
  5485. }
  5486. else
  5487. {
  5488. // Map this new virtual index back to the original index
  5489. vDataIdx += (defaultMethod->mVirtualTableIdx - typeInst->GetImplBaseVTableSize()) + typeInst->GetOrigImplBaseVTableSize();
  5490. }
  5491. }
  5492. else
  5493. {
  5494. vDataIdx += defaultMethod->mVirtualTableIdx;
  5495. }
  5496. }
  5497. if (vDataVal == -1)
  5498. vDataVal = vDataIdx * mSystem->mPtrSize;
  5499. }
  5500. SizedArray<BfIRValue, 8> methodDataVals =
  5501. {
  5502. emptyValueType,
  5503. methodNameConst, // mName
  5504. funcVal, // mFuncPtr
  5505. paramsVal,
  5506. GetConstValue(defaultMethod->mReturnType->mTypeId, typeIdType),
  5507. GetConstValue((int)paramVals.size(), shortType),
  5508. GetConstValue(methodFlags, shortType),
  5509. GetConstValue(methodIdx, intType),
  5510. GetConstValue(vDataVal, intType),
  5511. GetConstValue(customAttrIdx, intType),
  5512. };
  5513. auto methodData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectMethodDataType->ToTypeInstance(), BfIRPopulateType_Full), methodDataVals);
  5514. methodTypes.push_back(methodData);
  5515. }
  5516. BfIRValue methodDataPtr;
  5517. BfIRType methodDataPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(reflectMethodDataType));
  5518. if (methodTypes.size() == 0)
  5519. methodDataPtr = mBfIRBuilder->CreateConstNull(methodDataPtrType);
  5520. else
  5521. {
  5522. BfIRType methodDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(reflectMethodDataType, BfIRPopulateType_Full), (int)methodTypes.size());
  5523. BfIRValue methodDataConst = mBfIRBuilder->CreateConstArray(methodDataArrayType, methodTypes);
  5524. BfIRValue methodDataArray = mBfIRBuilder->CreateGlobalVariable(methodDataArrayType, true, BfIRLinkageType_Internal,
  5525. methodDataConst, "methods." + typeDataName);
  5526. methodDataPtr = mBfIRBuilder->CreateBitCast(methodDataArray, methodDataPtrType);
  5527. }
  5528. /////
  5529. int interfaceCount = 0;
  5530. BfIRValue interfaceDataPtr;
  5531. BfType* reflectInterfaceDataType = ResolveTypeDef(mCompiler->mReflectInterfaceDataDef);
  5532. BfIRType interfaceDataPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(reflectInterfaceDataType));
  5533. Array<bool> wantsIfaceMethod;
  5534. bool wantsIfaceMethods = false;
  5535. if (typeInstance->mInterfaces.IsEmpty())
  5536. interfaceDataPtr = mBfIRBuilder->CreateConstNull(interfaceDataPtrType);
  5537. else
  5538. {
  5539. SizedArray<BfIRValue, 16> interfaces;
  5540. for (auto& interface : typeInstance->mInterfaces)
  5541. {
  5542. SizedArray<BfIRValue, 8> interfaceDataVals =
  5543. {
  5544. emptyValueType,
  5545. GetConstValue(interface.mInterfaceType->mTypeId, typeIdType),
  5546. GetConstValue(interface.mStartInterfaceTableIdx, intType),
  5547. GetConstValue(interface.mStartVirtualIdx, intType),
  5548. };
  5549. auto interfaceData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectInterfaceDataType->ToTypeInstance(), BfIRPopulateType_Full), interfaceDataVals);
  5550. interfaces.push_back(interfaceData);
  5551. for (int methodIdx = 0; methodIdx < (int)interface.mInterfaceType->mMethodInstanceGroups.size(); methodIdx++)
  5552. {
  5553. auto ifaceMethodGroup = &interface.mInterfaceType->mMethodInstanceGroups[methodIdx];
  5554. if (ifaceMethodGroup->mExplicitlyReflected)
  5555. {
  5556. wantsIfaceMethods = true;
  5557. int tableIdx = interface.mStartInterfaceTableIdx + methodIdx;
  5558. while (tableIdx >= wantsIfaceMethod.size())
  5559. wantsIfaceMethod.Add(false);
  5560. wantsIfaceMethod[tableIdx] = true;
  5561. }
  5562. }
  5563. }
  5564. BfIRType interfaceDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(reflectInterfaceDataType, BfIRPopulateType_Full), (int)interfaces.size());
  5565. BfIRValue interfaceDataConst = mBfIRBuilder->CreateConstArray(interfaceDataArrayType, interfaces);
  5566. BfIRValue interfaceDataArray = mBfIRBuilder->CreateGlobalVariable(interfaceDataArrayType, true, BfIRLinkageType_Internal,
  5567. interfaceDataConst, "interfaces." + typeDataName);
  5568. interfaceDataPtr = mBfIRBuilder->CreateBitCast(interfaceDataArray, interfaceDataPtrType);
  5569. interfaceCount = (int)interfaces.size();
  5570. }
  5571. BfIRValue interfaceMethodTable;
  5572. int ifaceMethodTableSize = 0;
  5573. if ((wantsIfaceMethods) && (!typeInstance->IsInterface()) && (typeInstance->mIsReified) && (!typeInstance->IsUnspecializedType())
  5574. && (!typeInstance->mInterfaceMethodTable.IsEmpty()))
  5575. {
  5576. SizedArray<BfIRValue, 16> methods;
  5577. for (int tableIdx = 0; tableIdx < (int)typeInstance->mInterfaceMethodTable.size(); tableIdx++)
  5578. {
  5579. BfIRValue funcVal = voidPtrNull;
  5580. if ((tableIdx < (int)wantsIfaceMethod.size()) && (wantsIfaceMethod[tableIdx]))
  5581. {
  5582. auto methodEntry = typeInstance->mInterfaceMethodTable[tableIdx];
  5583. if (!methodEntry.mMethodRef.IsNull())
  5584. {
  5585. BfMethodInstance* methodInstance = methodEntry.mMethodRef;
  5586. if ((methodInstance->mIsReified) && (methodInstance->mMethodInstanceGroup->IsImplemented()) && (!methodInstance->mIsUnspecialized) &&
  5587. (!methodInstance->mMethodDef->mIsAbstract))
  5588. {
  5589. auto moduleMethodInstance = ReferenceExternalMethodInstance(methodInstance);
  5590. if (moduleMethodInstance.mFunc)
  5591. funcVal = mBfIRBuilder->CreateBitCast(moduleMethodInstance.mFunc, voidPtrIRType);
  5592. }
  5593. }
  5594. }
  5595. methods.Add(funcVal);
  5596. }
  5597. while ((!methods.IsEmpty()) && (methods.back() == voidPtrNull))
  5598. methods.pop_back();
  5599. if (!methods.IsEmpty())
  5600. {
  5601. BfIRType methodDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(voidPtrType, BfIRPopulateType_Full), (int)methods.size());
  5602. BfIRValue methodDataConst = mBfIRBuilder->CreateConstArray(methodDataArrayType, methods);
  5603. BfIRValue methodDataArray = mBfIRBuilder->CreateGlobalVariable(methodDataArrayType, true, BfIRLinkageType_Internal,
  5604. methodDataConst, "imethods." + typeDataName);
  5605. interfaceMethodTable = mBfIRBuilder->CreateBitCast(methodDataArray, voidPtrPtrIRType);
  5606. ifaceMethodTableSize = (int)methods.size();
  5607. }
  5608. }
  5609. if (!interfaceMethodTable)
  5610. interfaceMethodTable = mBfIRBuilder->CreateConstNull(voidPtrPtrIRType);
  5611. /////
  5612. int underlyingType = 0;
  5613. if ((typeInstance->IsTypedPrimitive()) || (typeInstance->IsBoxed()))
  5614. {
  5615. underlyingType = typeInstance->GetUnderlyingType()->mTypeId;
  5616. }
  5617. int outerTypeId = 0;
  5618. auto outerType = mContext->mUnreifiedModule->GetOuterType(typeInstance);
  5619. if (outerType != NULL)
  5620. {
  5621. outerTypeId = outerType->mTypeId;
  5622. }
  5623. //
  5624. BfIRValue customAttrDataPtr;
  5625. if (customAttrs.size() > 0)
  5626. {
  5627. BfIRType customAttrsArrayType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)customAttrs.size());
  5628. BfIRValue customAttrsConst = mBfIRBuilder->CreateConstArray(customAttrsArrayType, customAttrs);
  5629. BfIRValue customAttrsArray = mBfIRBuilder->CreateGlobalVariable(customAttrsArrayType, true, BfIRLinkageType_Internal,
  5630. customAttrsConst, "customAttrs." + typeDataName);
  5631. customAttrDataPtr = mBfIRBuilder->CreateBitCast(customAttrsArray, voidPtrPtrIRType);
  5632. }
  5633. else
  5634. {
  5635. customAttrDataPtr = mBfIRBuilder->CreateConstNull(voidPtrPtrIRType);
  5636. }
  5637. SizedArray<BfIRValue, 32> typeDataVals =
  5638. {
  5639. typeData,
  5640. castedClassVData, // mTypeClassVData
  5641. typeNameConst, // mName
  5642. namespaceConst, // mNamespace
  5643. GetConstValue(typeInstance->mInstSize, intType), // mInstSize
  5644. GetConstValue(typeInstance->mInstAlign, intType), // mInstAlign
  5645. GetConstValue(typeCustomAttrIdx, intType), // mCustomAttributes
  5646. GetConstValue(baseTypeId, typeIdType), // mBaseType
  5647. GetConstValue(underlyingType, typeIdType), // mUnderlyingType
  5648. GetConstValue(outerTypeId, typeIdType), // mOuterType
  5649. GetConstValue(typeInstance->mInheritanceId, intType), // mInheritanceId
  5650. GetConstValue(typeInstance->mInheritanceCount, intType), // mInheritanceCount
  5651. GetConstValue(typeInstance->mSlotNum, byteType), // mInterfaceSlot
  5652. GetConstValue(interfaceCount, byteType), // mInterfaceCount
  5653. GetConstValue(ifaceMethodTableSize, shortType), // mInterfaceMethodCount
  5654. GetConstValue((int)methodTypes.size(), shortType), // mMethodDataCount
  5655. GetConstValue(0, shortType), // mPropertyDataCount
  5656. GetConstValue((int)fieldTypes.size(), shortType), // mFieldDataCount
  5657. interfaceDataPtr, // mInterfaceDataPtr
  5658. interfaceMethodTable, // mInterfaceMethodTable
  5659. methodDataPtr, // mMethodDataPtr
  5660. voidPtrNull, // mPropertyDataPtr
  5661. fieldDataPtr, // mFieldDataPtr
  5662. customAttrDataPtr, // mCustomAttrDataPtr
  5663. };
  5664. BfIRType typeInstanceDataType = mBfIRBuilder->MapTypeInst(typeInstanceType->ToTypeInstance(), BfIRPopulateType_Full);
  5665. auto typeInstanceData = mBfIRBuilder->CreateConstStruct(typeInstanceDataType, typeDataVals);
  5666. if (!needsTypeData)
  5667. {
  5668. // No need for anything beyond typeInstanceData
  5669. }
  5670. else if ((typeInstance->IsGenericTypeInstance()) && (typeInstance->IsUnspecializedType()))
  5671. {
  5672. auto genericTypeInstance = typeInstance->ToGenericTypeInstance();
  5673. SizedArray<BfIRValue, 4> unspecializedData =
  5674. {
  5675. typeInstanceData,
  5676. GetConstValue((int)genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments.size(), byteType), // mGenericParamCount
  5677. };
  5678. auto reflectUnspecializedGenericType = ResolveTypeDef(mCompiler->mReflectUnspecializedGenericType);
  5679. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectUnspecializedGenericType->ToTypeInstance(), BfIRPopulateType_Full);
  5680. typeInstanceData = mBfIRBuilder->CreateConstStruct(typeInstanceDataType, unspecializedData);
  5681. }
  5682. else if (typeInstance->IsGenericTypeInstance())
  5683. {
  5684. auto genericTypeInstance = typeInstance->ToGenericTypeInstance();
  5685. auto reflectSpecializedGenericType = ResolveTypeDef(mCompiler->mReflectSpecializedGenericType);
  5686. auto unspecializedType = ResolveTypeDef(typeInstance->mTypeDef);
  5687. SizedArray<BfIRValue, 4> resolvedTypes;
  5688. for (auto typeGenericArg : genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments)
  5689. resolvedTypes.push_back(GetConstValue(typeGenericArg->mTypeId, typeIdType));
  5690. auto typeIRType = mBfIRBuilder->MapType(typeIdType);
  5691. auto typePtrIRType = mBfIRBuilder->GetPointerTo(typeIRType);
  5692. auto genericArrayType = mBfIRBuilder->GetSizedArrayType(typeIRType, (int)resolvedTypes.size());
  5693. BfIRValue resolvedTypesConst = mBfIRBuilder->CreateConstArray(genericArrayType, resolvedTypes);
  5694. BfIRValue resolvedTypesArray = mBfIRBuilder->CreateGlobalVariable(genericArrayType, true, BfIRLinkageType_Internal,
  5695. resolvedTypesConst, "resolvedTypes." + typeDataName);
  5696. BfIRValue resovledTypesPtr = mBfIRBuilder->CreateBitCast(resolvedTypesArray, typePtrIRType);
  5697. SizedArray<BfIRValue, 3> specGenericData =
  5698. {
  5699. typeInstanceData,
  5700. GetConstValue(unspecializedType->mTypeId, typeIdType), // mUnspecialziedType
  5701. resovledTypesPtr, // mFieldDataPtr
  5702. };
  5703. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectSpecializedGenericType->ToTypeInstance(), BfIRPopulateType_Full);
  5704. typeInstanceData = mBfIRBuilder->CreateConstStruct(typeInstanceDataType, specGenericData);
  5705. if (typeInstance->IsArray())
  5706. {
  5707. auto arrayType = (BfArrayType*)typeInstance;
  5708. BfType* elementType = genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments[0];
  5709. BfFieldInstance* elementFieldInstance = &genericTypeInstance->mFieldInstances[0];
  5710. SizedArray<BfIRValue, 4> arrayData =
  5711. {
  5712. typeInstanceData,
  5713. GetConstValue(elementType->mSize, intType), // mElementSize
  5714. GetConstValue(1, byteType), // mRank
  5715. GetConstValue(elementFieldInstance->mDataOffset, byteType), // mElementsDataOffset
  5716. };
  5717. auto reflectArrayType = ResolveTypeDef(mCompiler->mReflectArrayType);
  5718. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectArrayType->ToTypeInstance(), BfIRPopulateType_Full);
  5719. typeInstanceData = mBfIRBuilder->CreateConstStruct(typeInstanceDataType, arrayData);
  5720. }
  5721. }
  5722. BfIRValue typeDataVar;
  5723. if (needsTypeData)
  5724. {
  5725. typeDataVar = mBfIRBuilder->CreateGlobalVariable(typeInstanceDataType, true,
  5726. BfIRLinkageType_External, typeInstanceData, typeDataName);
  5727. mBfIRBuilder->GlobalVar_SetAlignment(typeDataVar, mSystem->mPtrSize);
  5728. if (mBfIRBuilder->DbgHasInfo())
  5729. {
  5730. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, typeDataName, typeDataName, BfIRMDNode(), 0, mBfIRBuilder->DbgGetTypeInst(typeInstanceType->ToTypeInstance()), false, typeDataVar);
  5731. }
  5732. }
  5733. else
  5734. {
  5735. typeDataVar = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(mContext->mBfTypeType));
  5736. }
  5737. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  5738. mTypeDataRefs[typeInstance] = typeDataVar;
  5739. if (classVDataVar)
  5740. {
  5741. BF_ASSERT(!classVDataName.IsEmpty());
  5742. vData[0] = mBfIRBuilder->CreateBitCast(typeDataVar, voidPtrIRType);
  5743. auto classVDataConstDataType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)vData.size());
  5744. auto classVDataConstData = mBfIRBuilder->CreateConstArray(classVDataConstDataType, vData);
  5745. mBfIRBuilder->GlobalVar_SetInitializer(classVDataVar, classVDataConstData);
  5746. if (mCompiler->mOptions.mObjectHasDebugFlags)
  5747. mBfIRBuilder->GlobalVar_SetAlignment(classVDataVar, 256);
  5748. else
  5749. mBfIRBuilder->GlobalVar_SetAlignment(classVDataVar, mContext->mBfClassVDataPtrType->mAlign);
  5750. if (mBfIRBuilder->DbgHasInfo())
  5751. {
  5752. BfType* voidType = GetPrimitiveType(BfTypeCode_None);
  5753. BfType* voidPtrType = CreatePointerType(voidType);
  5754. BfType* classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  5755. BfIRMDNode arrayType = mBfIRBuilder->DbgCreateArrayType(vData.size() * mSystem->mPtrSize * 8, mSystem->mPtrSize * 8, mBfIRBuilder->DbgGetType(voidPtrType), vData.size());
  5756. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, classVDataName, classVDataName, BfIRMDNode(), 0, arrayType, false, classVDataVar);
  5757. }
  5758. }
  5759. return typeDataVar;
  5760. }
  5761. BfIRValue BfModule::FixClassVData(BfIRValue value)
  5762. {
  5763. if (!mCompiler->mOptions.mObjectHasDebugFlags)
  5764. return value;
  5765. auto intptrValue = mBfIRBuilder->CreatePtrToInt(value, BfTypeCode_IntPtr);
  5766. auto maskedValue = mBfIRBuilder->CreateAnd(intptrValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)~0xFFULL));
  5767. return mBfIRBuilder->CreateIntToPtr(maskedValue, mBfIRBuilder->GetType(value));
  5768. }
  5769. void BfModule::CheckStaticAccess(BfTypeInstance* typeInstance)
  5770. {
  5771. // Note: this is not just for perf, it fixes a field var-type resolution issue
  5772. if (mBfIRBuilder->mIgnoreWrites)
  5773. return;
  5774. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  5775. //TODO: Create a hashset of these, we don't need to repeatedly call static ctors for a given type
  5776. // When we access classes with static constructors FROM a static constructor,
  5777. // we call that other class's static constructor first. Recursion cannot occur, since
  5778. // we simply ignore subsequent attempts to re-enter the constructor
  5779. if (!typeInstance->mHasStaticInitMethod)
  5780. return;
  5781. if ((mCurMethodInstance == NULL) || ((mCurMethodInstance->mMethodDef->mMethodType != BfMethodType_Ctor) || (!mCurMethodInstance->mMethodDef->mIsStatic)))
  5782. return;
  5783. if (mCurMethodInstance->mMethodInstanceGroup->mOwner == typeInstance)
  5784. return;
  5785. auto checkTypeDef = typeInstance->mTypeDef;
  5786. checkTypeDef->PopulateMemberSets();
  5787. BfMethodDef* nextMethodDef = NULL;
  5788. BfMemberSetEntry* entry;
  5789. if (checkTypeDef->mMethodSet.TryGetWith(String("__BfStaticCtor"), &entry))
  5790. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  5791. while (nextMethodDef != NULL)
  5792. {
  5793. auto checkMethod = nextMethodDef;
  5794. nextMethodDef = nextMethodDef->mNextWithSameName;
  5795. auto methodModule = GetMethodInstance(typeInstance, checkMethod, BfTypeVector());
  5796. if (methodModule)
  5797. {
  5798. auto methodInstance = methodModule.mMethodInstance;
  5799. if ((methodInstance != NULL) &&
  5800. (methodInstance->mMethodDef->mIsStatic) &&
  5801. (methodInstance->mMethodDef->mMethodType == BfMethodType_Ctor) &&
  5802. ((methodInstance->mChainType == BfMethodChainType_ChainHead) || (methodInstance->mChainType == BfMethodChainType_None)))
  5803. {
  5804. mBfIRBuilder->CreateCall(methodModule.mFunc, SizedArray<BfIRValue, 0>());
  5805. break;
  5806. }
  5807. }
  5808. }
  5809. }
  5810. BfIRFunction BfModule::GetIntrinsic(BfMethodInstance* methodInstance, bool reportFailure)
  5811. {
  5812. auto methodOwner = methodInstance->GetOwner();
  5813. auto methodDef = methodInstance->mMethodDef;
  5814. auto methodDeclaration = methodDef->GetMethodDeclaration();
  5815. if (!methodDef->mIsExtern)
  5816. return BfIRFunction();
  5817. if (methodInstance->GetCustomAttributes() == NULL)
  5818. return BfIRFunction();
  5819. for (auto& customAttribute : methodInstance->GetCustomAttributes()->mAttributes)
  5820. {
  5821. String typeName = TypeToString(customAttribute.mType);
  5822. if ((typeName == "System.IntrinsicAttribute") && (customAttribute.mCtorArgs.size() > 0))
  5823. {
  5824. methodInstance->mIsIntrinsic = true;
  5825. auto constant = methodOwner->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  5826. String error;
  5827. if ((constant != NULL) && (constant->mTypeCode = BfTypeCode_StringId))
  5828. {
  5829. int stringId = constant->mInt32;
  5830. auto entry = mContext->mStringObjectIdMap[stringId];
  5831. String intrinName = entry.mString;
  5832. // if (intrinName.StartsWith(":"))
  5833. // {
  5834. // SizedArray<BfIRType, 2> paramTypes;
  5835. // for (auto& param : methodInstance->mParams)
  5836. // paramTypes.push_back(mBfIRBuilder->MapType(param.mResolvedType));
  5837. // return mBfIRBuilder->GetIntrinsic(intrinName.Substring(1), mBfIRBuilder->MapType(methodInstance->mReturnType), paramTypes);
  5838. // }
  5839. // else
  5840. {
  5841. int intrinId = BfIRCodeGen::GetIntrinsicId(intrinName);
  5842. if (intrinId != -1)
  5843. {
  5844. if (intrinId == BfIRIntrinsic_Malloc)
  5845. {
  5846. return GetBuiltInFunc(BfBuiltInFuncType_Malloc);
  5847. }
  5848. else if (intrinId == BfIRIntrinsic_Free)
  5849. {
  5850. return GetBuiltInFunc(BfBuiltInFuncType_Free);
  5851. }
  5852. SizedArray<BfIRType, 2> paramTypes;
  5853. for (auto& param : methodInstance->mParams)
  5854. paramTypes.push_back(mBfIRBuilder->MapType(param.mResolvedType));
  5855. return mBfIRBuilder->GetIntrinsic(intrinName, intrinId, mBfIRBuilder->MapType(methodInstance->mReturnType), paramTypes);
  5856. }
  5857. else if (reportFailure)
  5858. error = StrFormat("Unable to find intrinsic '%s'", entry.mString.c_str());
  5859. }
  5860. }
  5861. else if (reportFailure)
  5862. error = "Intrinsic name must be a constant string";
  5863. if (reportFailure)
  5864. {
  5865. Fail(error, customAttribute.mRef);
  5866. }
  5867. }
  5868. }
  5869. return BfIRFunction();
  5870. }
  5871. BfIRFunction BfModule::GetBuiltInFunc(BfBuiltInFuncType funcTypeId)
  5872. {
  5873. if (mBfIRBuilder->mIgnoreWrites)
  5874. return mBfIRBuilder->GetFakeFunction();
  5875. if (!mBuiltInFuncs[(int)funcTypeId])
  5876. {
  5877. SizedArray<BfIRType, 4> paramTypes;
  5878. auto nullPtrType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr));
  5879. auto intType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_IntPtr));
  5880. auto int32Type = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int32));
  5881. auto intPtrType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_IntPtr));
  5882. auto byteType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int8));
  5883. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  5884. auto objType = mBfIRBuilder->MapType(mContext->mBfObjectType);
  5885. BfIRFunctionType funcType;
  5886. BfIRFunction func;
  5887. switch (funcTypeId)
  5888. {
  5889. case BfBuiltInFuncType_PrintF:
  5890. paramTypes.Add(nullPtrType);
  5891. funcType = mBfIRBuilder->CreateFunctionType(int32Type, paramTypes, true);
  5892. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, "PrintF");
  5893. break;
  5894. case BfBuiltInFuncType_Malloc:
  5895. {
  5896. if (mCompiler->mOptions.mDebugAlloc)
  5897. {
  5898. func = GetInternalMethod("Dbg_RawAlloc", 1).mFunc;
  5899. }
  5900. else
  5901. {
  5902. String funcName = mCompiler->mOptions.mMallocLinkName;
  5903. if (funcName.IsEmpty())
  5904. funcName = "malloc";
  5905. func = mBfIRBuilder->GetFunction(funcName);
  5906. if (!func)
  5907. {
  5908. paramTypes.clear();
  5909. paramTypes.push_back(intType);
  5910. funcType = mBfIRBuilder->CreateFunctionType(nullPtrType, paramTypes);
  5911. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, funcName);
  5912. mBfIRBuilder->Func_SetParamName(func, 1, "size");
  5913. }
  5914. }
  5915. }
  5916. break;
  5917. case BfBuiltInFuncType_Free:
  5918. {
  5919. if (mCompiler->mOptions.mDebugAlloc)
  5920. {
  5921. func = GetInternalMethod("Dbg_RawFree").mFunc;
  5922. }
  5923. else
  5924. {
  5925. String funcName = mCompiler->mOptions.mFreeLinkName;
  5926. if (funcName.IsEmpty())
  5927. funcName = "free";
  5928. func = mBfIRBuilder->GetFunction(funcName);
  5929. if (!func)
  5930. {
  5931. paramTypes.clear();
  5932. paramTypes.push_back(nullPtrType);
  5933. funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  5934. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, funcName);
  5935. mBfIRBuilder->Func_SetParamName(func, 1, "ptr");
  5936. }
  5937. }
  5938. }
  5939. break;
  5940. case BfBuiltInFuncType_LoadSharedLibraries:
  5941. paramTypes.clear();
  5942. funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  5943. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, "BfLoadSharedLibraries");
  5944. break;
  5945. default: break;
  5946. }
  5947. mBuiltInFuncs[(int)funcTypeId] = func;
  5948. return func;
  5949. }
  5950. return mBuiltInFuncs[(int)funcTypeId];
  5951. }
  5952. void BfModule::ResolveGenericParamConstraints(BfGenericParamInstance* genericParamInstance, bool isUnspecialized)
  5953. {
  5954. BfGenericParamDef* genericParamDef = genericParamInstance->GetGenericParamDef();
  5955. BfExternalConstraintDef* externConstraintDef = genericParamInstance->GetExternConstraintDef();
  5956. BfConstraintDef* constraintDef = genericParamInstance->GetConstraintDef();
  5957. BfType* startingTypeConstraint = genericParamInstance->mTypeConstraint;
  5958. BfAutoComplete* bfAutocomplete = NULL;
  5959. if ((mCompiler->mResolvePassData != NULL) && (isUnspecialized))
  5960. bfAutocomplete = mCompiler->mResolvePassData->mAutoComplete;
  5961. if ((bfAutocomplete != NULL) && (genericParamDef != NULL))
  5962. {
  5963. for (int nameIdx = 0; nameIdx < (int)genericParamDef->mNameNodes.size(); nameIdx++)
  5964. {
  5965. auto nameNode = genericParamDef->mNameNodes[nameIdx];
  5966. if (bfAutocomplete->IsAutocompleteNode(nameNode))
  5967. {
  5968. String filter = nameNode->ToString();
  5969. bfAutocomplete->mInsertStartIdx = nameNode->GetSrcStart();
  5970. bfAutocomplete->mInsertEndIdx = nameNode->GetSrcEnd();
  5971. if (nameIdx != 0)
  5972. {
  5973. bfAutocomplete->AddEntry(AutoCompleteEntry("generic", nameNode->ToString().c_str()), filter);
  5974. }
  5975. }
  5976. }
  5977. }
  5978. for (auto constraint : constraintDef->mConstraints)
  5979. {
  5980. if (auto opConstraint = BfNodeDynCast<BfGenericOperatorConstraint>(constraint))
  5981. {
  5982. BfGenericOperatorConstraintInstance opConstraintInstance;
  5983. if (opConstraint->mLeftType != NULL)
  5984. {
  5985. if (bfAutocomplete != NULL)
  5986. bfAutocomplete->CheckTypeRef(opConstraint->mLeftType, false);
  5987. opConstraintInstance.mLeftType = ResolveTypeRef(opConstraint->mLeftType, BfPopulateType_Interfaces);
  5988. if (opConstraintInstance.mLeftType == NULL)
  5989. continue;
  5990. }
  5991. if (opConstraint->mRightType == NULL)
  5992. {
  5993. // We had a failure in parsing
  5994. continue;
  5995. }
  5996. if (opConstraint->mRightType != NULL)
  5997. {
  5998. if (bfAutocomplete != NULL)
  5999. bfAutocomplete->CheckTypeRef(opConstraint->mRightType, false);
  6000. opConstraintInstance.mRightType = ResolveTypeRef(opConstraint->mRightType, BfPopulateType_Interfaces);
  6001. if (opConstraintInstance.mRightType == NULL)
  6002. continue;
  6003. }
  6004. if (opConstraint->mOpToken == NULL)
  6005. {
  6006. FailAfter("Missing operator", (opConstraint->mLeftType != NULL) ? (BfAstNode*)opConstraint->mLeftType : (BfAstNode*)opConstraint->mOperatorToken);
  6007. continue;
  6008. }
  6009. if (opConstraint->mLeftType != NULL)
  6010. {
  6011. if (opConstraint->mRightType == NULL)
  6012. {
  6013. // Parse should have failed
  6014. continue;
  6015. }
  6016. opConstraintInstance.mBinaryOp = BfTokenToBinaryOp(opConstraint->mOpToken->mToken);
  6017. if (opConstraintInstance.mBinaryOp == BfBinaryOp_None)
  6018. {
  6019. Fail("Invalid binary operator", opConstraint->mOpToken);
  6020. continue;
  6021. }
  6022. }
  6023. else if ((opConstraint->mOpToken->mToken == BfToken_Implicit) || (opConstraint->mOpToken->mToken == BfToken_Explicit))
  6024. {
  6025. opConstraintInstance.mCastToken = opConstraint->mOpToken->mToken;
  6026. }
  6027. else
  6028. {
  6029. opConstraintInstance.mUnaryOp = BfTokenToUnaryOp(opConstraint->mOpToken->mToken);
  6030. if (opConstraintInstance.mUnaryOp == BfUnaryOp_None)
  6031. {
  6032. Fail("Invalid unary operator", opConstraint->mOpToken);
  6033. continue;
  6034. }
  6035. }
  6036. if ((constraintDef->mGenericParamFlags & BfGenericParamFlag_Equals) != 0)
  6037. genericParamInstance->mGenericParamFlags = (BfGenericParamFlags)(genericParamInstance->mGenericParamFlags | BfGenericParamFlag_Equals_Op);
  6038. genericParamInstance->mOperatorConstraints.Add(opConstraintInstance);
  6039. continue;
  6040. }
  6041. auto constraintTypeRef = BfNodeDynCast<BfTypeReference>(constraint);
  6042. if (bfAutocomplete != NULL)
  6043. bfAutocomplete->CheckTypeRef(constraintTypeRef, true);
  6044. //TODO: Constraints may refer to other generic params (of either type or method)
  6045. // TO allow resolution, perhaps move this generic param initalization into GetMethodInstance (passing a genericPass bool)
  6046. auto constraintType = ResolveTypeRef(constraintTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_AllowGenericMethodParamConstValue);
  6047. if (constraintType != NULL)
  6048. {
  6049. if ((constraintDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  6050. {
  6051. bool isValidTypeCode = false;
  6052. BfTypeCode typeCode = BfTypeCode_None;
  6053. if (constraintType->IsTypedPrimitive())
  6054. {
  6055. auto underlyingType = constraintType->GetUnderlyingType();
  6056. if (underlyingType->IsPrimitiveType())
  6057. typeCode = ((BfPrimitiveType*)underlyingType)->mTypeDef->mTypeCode;
  6058. }
  6059. if (constraintType->IsPrimitiveType())
  6060. typeCode = ((BfPrimitiveType*)constraintType)->mTypeDef->mTypeCode;
  6061. switch (typeCode)
  6062. {
  6063. case BfTypeCode_Int8:
  6064. case BfTypeCode_UInt8:
  6065. case BfTypeCode_Int16:
  6066. case BfTypeCode_UInt16:
  6067. case BfTypeCode_Int32:
  6068. case BfTypeCode_UInt32:
  6069. case BfTypeCode_Int64:
  6070. case BfTypeCode_UInt64:
  6071. case BfTypeCode_IntPtr:
  6072. case BfTypeCode_UIntPtr:
  6073. case BfTypeCode_IntUnknown:
  6074. case BfTypeCode_UIntUnknown:
  6075. case BfTypeCode_Float:
  6076. case BfTypeCode_Double:
  6077. case BfTypeCode_Char8:
  6078. case BfTypeCode_Char16:
  6079. case BfTypeCode_Char32:
  6080. isValidTypeCode = true;
  6081. break;
  6082. default: break;
  6083. }
  6084. if (isValidTypeCode)
  6085. {
  6086. genericParamInstance->mTypeConstraint = constraintType;
  6087. }
  6088. else
  6089. {
  6090. Fail("Const constraint must be a primitive type", constraintTypeRef);
  6091. }
  6092. }
  6093. else
  6094. {
  6095. bool checkEquality = false;
  6096. if (constraintType->IsPrimitiveType())
  6097. {
  6098. if (isUnspecialized)
  6099. {
  6100. Fail("Primitive constraints are not allowed unless preceded with 'const'", constraintTypeRef);
  6101. continue;
  6102. }
  6103. checkEquality = true;
  6104. }
  6105. if (constraintType->IsArray())
  6106. {
  6107. if (isUnspecialized)
  6108. {
  6109. 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);
  6110. continue;
  6111. }
  6112. checkEquality = true;
  6113. }
  6114. if (constraintType->IsGenericParam())
  6115. {
  6116. continue;
  6117. }
  6118. if ((!constraintType->IsTypeInstance()) && (!constraintType->IsSizedArray()))
  6119. {
  6120. if (isUnspecialized)
  6121. {
  6122. Fail(StrFormat("Type '%s' is not allowed as a generic constraint", TypeToString(constraintType).c_str()), constraintTypeRef);
  6123. continue;
  6124. }
  6125. checkEquality = true;
  6126. }
  6127. if ((constraintDef->mGenericParamFlags & BfGenericParamFlag_Equals) != 0)
  6128. {
  6129. genericParamInstance->mGenericParamFlags = (BfGenericParamFlags)(genericParamInstance->mGenericParamFlags | BfGenericParamFlag_Equals_Type);
  6130. checkEquality = true;
  6131. }
  6132. if (checkEquality)
  6133. {
  6134. genericParamInstance->mTypeConstraint = constraintType;
  6135. }
  6136. else if (constraintType->IsInterface())
  6137. {
  6138. if ((constraintDef->mGenericParamFlags & BfGenericParamFlag_Equals) != 0)
  6139. genericParamInstance->mGenericParamFlags = (BfGenericParamFlags)(genericParamInstance->mGenericParamFlags | BfGenericParamFlag_Equals_IFace);
  6140. genericParamInstance->mInterfaceConstraints.push_back(constraintType->ToTypeInstance());
  6141. }
  6142. else
  6143. {
  6144. auto constraintTypeInst = constraintType->ToTypeInstance();
  6145. if (genericParamInstance->mTypeConstraint != NULL)
  6146. {
  6147. if ((constraintTypeInst != NULL) && (TypeIsSubTypeOf(constraintTypeInst, genericParamInstance->mTypeConstraint->ToTypeInstance(), false)))
  6148. {
  6149. // Allow more specific type
  6150. genericParamInstance->mTypeConstraint = constraintTypeInst;
  6151. }
  6152. else if ((constraintTypeInst != NULL) && (TypeIsSubTypeOf(genericParamInstance->mTypeConstraint->ToTypeInstance(), constraintTypeInst, false)))
  6153. {
  6154. // Silently ignore less-specific type
  6155. if ((startingTypeConstraint != NULL) && (startingTypeConstraint->IsDelegate()))
  6156. {
  6157. // 'System.Delegate' means that we are expecting an actual delegate instance. Simulate this by wanting a class.
  6158. genericParamInstance->mGenericParamFlags |= BfGenericParamFlag_Class;
  6159. }
  6160. }
  6161. else
  6162. {
  6163. Fail("Only one concrete type constraint may be specified", constraintTypeRef);
  6164. return;
  6165. }
  6166. }
  6167. else
  6168. genericParamInstance->mTypeConstraint = constraintType;
  6169. }
  6170. }
  6171. }
  6172. }
  6173. if (((constraintDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0) &&
  6174. (genericParamInstance->mTypeConstraint == NULL))
  6175. genericParamInstance->mTypeConstraint = GetPrimitiveType(BfTypeCode_IntPtr);
  6176. }
  6177. String BfModule::GenericParamSourceToString(const BfGenericParamSource & genericParamSource)
  6178. {
  6179. if (genericParamSource.mMethodInstance != NULL)
  6180. {
  6181. auto methodInst = GetUnspecializedMethodInstance(genericParamSource.mMethodInstance, false);
  6182. SetAndRestoreValue<BfMethodInstance*> prevMethodInst(methodInst, NULL);
  6183. return MethodToString(genericParamSource.mMethodInstance);
  6184. }
  6185. else
  6186. {
  6187. auto typeInst = GetUnspecializedTypeInstance(genericParamSource.mTypeInstance);
  6188. SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, NULL);
  6189. SetAndRestoreValue<BfTypeInstance*> prevTypeInst(mCurTypeInstance, typeInst);
  6190. return TypeToString(typeInst);
  6191. }
  6192. }
  6193. bool BfModule::CheckGenericConstraints(const BfGenericParamSource& genericParamSource, BfType* checkArgType, BfAstNode* checkArgTypeRef, BfGenericParamInstance* genericParamInst, BfTypeVector* methodGenericArgs, BfError** errorOut)
  6194. {
  6195. Array<String> methodParamNameOverrides;
  6196. auto _TypeToString = [&](BfType* type)
  6197. {
  6198. if (genericParamSource.mMethodInstance != NULL)
  6199. {
  6200. if (methodParamNameOverrides.IsEmpty())
  6201. {
  6202. for (auto genericParam : genericParamSource.mMethodInstance->mMethodDef->mGenericParams)
  6203. methodParamNameOverrides.Add(genericParam->mName);
  6204. }
  6205. return TypeToString(type, &methodParamNameOverrides);
  6206. }
  6207. return TypeToString(type);
  6208. };
  6209. bool ignoreErrors = mIgnoreErrors || (errorOut == NULL) ||
  6210. ((genericParamSource.mMethodInstance == NULL) && (genericParamSource.mTypeInstance == NULL));
  6211. BfType* origCheckArgType = checkArgType;
  6212. if (origCheckArgType->IsRef())
  6213. origCheckArgType = origCheckArgType->GetUnderlyingType();
  6214. bool argMayBeReferenceType = false;
  6215. int checkGenericParamFlags = 0;
  6216. if (checkArgType->IsGenericParam())
  6217. {
  6218. auto checkGenericParamInst = GetGenericParamInstance((BfGenericParamType*)checkArgType);
  6219. checkGenericParamFlags = checkGenericParamInst->mGenericParamFlags;
  6220. if (checkGenericParamInst->mTypeConstraint != NULL)
  6221. checkArgType = checkGenericParamInst->mTypeConstraint;
  6222. if ((checkGenericParamFlags & (BfGenericParamFlag_Struct | BfGenericParamFlag_StructPtr)) != 0)
  6223. {
  6224. argMayBeReferenceType = false;
  6225. }
  6226. else
  6227. {
  6228. argMayBeReferenceType = true;
  6229. }
  6230. }
  6231. if (checkArgType->IsObjectOrInterface())
  6232. argMayBeReferenceType = true;
  6233. BfTypeInstance* typeConstraintInst = NULL;
  6234. if (genericParamInst->mTypeConstraint != NULL)
  6235. typeConstraintInst = genericParamInst->mTypeConstraint->ToTypeInstance();
  6236. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Struct) &&
  6237. ((checkGenericParamFlags & (BfGenericParamFlag_Struct | BfGenericParamFlag_Var)) == 0) && (!checkArgType->IsValueType()))
  6238. {
  6239. if (!ignoreErrors)
  6240. *errorOut = Fail(StrFormat("The type '%s' must be a value type in order to use it as parameter '%s' for '%s'",
  6241. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  6242. return false;
  6243. }
  6244. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_StructPtr) &&
  6245. ((checkGenericParamFlags & (BfGenericParamFlag_StructPtr | BfGenericParamFlag_Var)) == 0) && (!checkArgType->IsPointer()))
  6246. {
  6247. if (!ignoreErrors)
  6248. *errorOut = Fail(StrFormat("The type '%s' must be a pointer type in order to use it as parameter '%s' for '%s'",
  6249. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  6250. return false;
  6251. }
  6252. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Class) &&
  6253. ((checkGenericParamFlags & (BfGenericParamFlag_Class | BfGenericParamFlag_Var)) == 0) && (!argMayBeReferenceType))
  6254. {
  6255. if (!ignoreErrors)
  6256. *errorOut = Fail(StrFormat("The type '%s' must be a reference type in order to use it as parameter '%s' for '%s'",
  6257. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  6258. return false;
  6259. }
  6260. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  6261. {
  6262. if (((checkGenericParamFlags & BfGenericParamFlag_Const) == 0) && (!checkArgType->IsConstExprValue()))
  6263. {
  6264. if (!ignoreErrors)
  6265. *errorOut = Fail(StrFormat("The type '%s' must be a const value in order to use it as parameter '%s' for '%s'",
  6266. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  6267. return false;
  6268. }
  6269. }
  6270. else
  6271. {
  6272. if (checkArgType->IsConstExprValue())
  6273. {
  6274. if (!ignoreErrors)
  6275. *errorOut = Fail(StrFormat("The value '%s' cannot be used for generic type parameter '%s' for '%s'",
  6276. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  6277. return false;
  6278. }
  6279. }
  6280. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Delete) != 0)
  6281. {
  6282. bool canDelete = false;
  6283. if (checkArgType->IsPointer())
  6284. canDelete = true;
  6285. else if (checkArgType->IsObjectOrInterface())
  6286. canDelete = true;
  6287. else if ((checkGenericParamFlags & BfGenericParamFlag_Delete) != 0)
  6288. canDelete = true;
  6289. if (!canDelete)
  6290. {
  6291. if (!ignoreErrors)
  6292. *errorOut = Fail(StrFormat("The type '%s' must be a deletable type in order to use it as parameter '%s' for '%s'",
  6293. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  6294. return false;
  6295. }
  6296. }
  6297. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_New) != 0)
  6298. {
  6299. bool canAlloc = false;
  6300. if (auto checkTypeInst = checkArgType->ToTypeInstance())
  6301. {
  6302. if (checkTypeInst->IsObjectOrStruct())
  6303. {
  6304. checkTypeInst->mTypeDef->PopulateMemberSets();
  6305. BfMemberSetEntry* entry = NULL;
  6306. BfMethodDef* checkMethodDef = NULL;
  6307. checkTypeInst->mTypeDef->mMethodSet.TryGetWith(String("__BfCtor"), &entry);
  6308. if (entry != NULL)
  6309. checkMethodDef = (BfMethodDef*)entry->mMemberDef;
  6310. bool hadProtected = false;
  6311. while (checkMethodDef != NULL)
  6312. {
  6313. if (checkMethodDef->mProtection == BfProtection_Public)
  6314. {
  6315. canAlloc = true;
  6316. break;
  6317. }
  6318. if (checkMethodDef->mProtection == BfProtection_Protected)
  6319. hadProtected = true;
  6320. checkMethodDef = checkMethodDef->mNextWithSameName;
  6321. }
  6322. if ((!canAlloc) && (hadProtected) && (mCurTypeInstance != NULL))
  6323. canAlloc = TypeIsSubTypeOf(mCurTypeInstance, checkTypeInst, false);
  6324. }
  6325. }
  6326. else
  6327. {
  6328. // Any primitive types and stuff can be allocated
  6329. canAlloc = true;
  6330. }
  6331. if (!canAlloc)
  6332. {
  6333. if (!ignoreErrors)
  6334. *errorOut = Fail(StrFormat("The type '%s' must have an accessible default constructor in order to use it as parameter '%s' for '%s'",
  6335. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  6336. return false;
  6337. }
  6338. }
  6339. if ((genericParamInst->mInterfaceConstraints.IsEmpty()) && (genericParamInst->mOperatorConstraints.IsEmpty()) && (genericParamInst->mTypeConstraint == NULL))
  6340. return true;
  6341. if (checkArgType->IsPointer())
  6342. {
  6343. auto ptrType = (BfPointerType*)checkArgType;
  6344. checkArgType = ptrType->mElementType;
  6345. }
  6346. if (genericParamInst->mTypeConstraint != NULL)
  6347. {
  6348. bool constraintMatched = false;
  6349. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  6350. {
  6351. if (checkArgType->IsConstExprValue())
  6352. {
  6353. auto constExprValueType = (BfConstExprValueType*)checkArgType;
  6354. if (genericParamInst->mTypeConstraint->IsPrimitiveType())
  6355. {
  6356. auto primType = (BfPrimitiveType*)genericParamInst->mTypeConstraint;
  6357. // Let either an exact typematch or an undef pass through. Eventually instead of undefs we may want to do
  6358. // actual expression comparisons, but we are overly permissive now and then we may fail on specialization
  6359. if ((constExprValueType->mValue.mTypeCode != primType->mTypeDef->mTypeCode) &&
  6360. (constExprValueType->mValue.mTypeCode != BfTypeCode_Let) &&
  6361. (primType->mTypeDef->mTypeCode != BfTypeCode_Let))
  6362. {
  6363. if (BfIRConstHolder::IsInt(constExprValueType->mValue.mTypeCode))
  6364. {
  6365. if (BfIRConstHolder::IsInt(primType->mTypeDef->mTypeCode))
  6366. {
  6367. if (!mCompiler->mSystem->DoesLiteralFit(primType->mTypeDef->mTypeCode, constExprValueType->mValue.mInt64))
  6368. {
  6369. if (!ignoreErrors)
  6370. *errorOut = Fail(StrFormat("Const generic argument '%s', declared with const '%lld', does not fit into const constraint '%s' for '%s'", genericParamInst->GetName().c_str(),
  6371. constExprValueType->mValue.mInt64, _TypeToString(genericParamInst->mTypeConstraint).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  6372. return false;
  6373. }
  6374. }
  6375. else
  6376. {
  6377. if (!ignoreErrors)
  6378. *errorOut = Fail(StrFormat("Const generic argument '%s', declared with integer const '%lld', is not compatible with const constraint '%s' for '%s'", genericParamInst->GetName().c_str(),
  6379. constExprValueType->mValue.mInt64, _TypeToString(genericParamInst->mTypeConstraint).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  6380. return false;
  6381. }
  6382. }
  6383. else
  6384. {
  6385. if (BfIRConstHolder::IsInt(primType->mTypeDef->mTypeCode))
  6386. {
  6387. char valStr[64];
  6388. ExactMinimalDoubleToStr(constExprValueType->mValue.mDouble, valStr);
  6389. if (!ignoreErrors)
  6390. *errorOut = Fail(StrFormat("Const generic argument '%s', declared with floating point const '%s', is not compatible with const constraint '%s' for '%s'", genericParamInst->GetName().c_str(),
  6391. valStr, _TypeToString(genericParamInst->mTypeConstraint).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  6392. return false;
  6393. }
  6394. }
  6395. }
  6396. }
  6397. }
  6398. }
  6399. else
  6400. {
  6401. BfType* convCheckConstraint = genericParamInst->mTypeConstraint;
  6402. if ((convCheckConstraint->IsUnspecializedType()) && (methodGenericArgs != NULL))
  6403. convCheckConstraint = ResolveGenericType(convCheckConstraint, NULL, methodGenericArgs);
  6404. if (convCheckConstraint == NULL)
  6405. return false;
  6406. if (((checkArgType->IsMethodRef()) || (checkArgType->IsFunction())) && (convCheckConstraint->IsDelegate()))
  6407. {
  6408. BfMethodInstance* checkMethodInstance;
  6409. if (checkArgType->IsMethodRef())
  6410. {
  6411. auto methodRefType = (BfMethodRefType*)checkArgType;
  6412. checkMethodInstance = methodRefType->mMethodRef;
  6413. }
  6414. else
  6415. {
  6416. checkMethodInstance = GetRawMethodInstanceAtIdx(checkArgType->ToTypeInstance(), 0, "Invoke");
  6417. }
  6418. auto invokeMethod = GetRawMethodInstanceAtIdx(convCheckConstraint->ToTypeInstance(), 0, "Invoke");
  6419. BfExprEvaluator exprEvaluator(this);
  6420. if (exprEvaluator.IsExactMethodMatch(checkMethodInstance, invokeMethod))
  6421. constraintMatched = true;
  6422. }
  6423. else if (CanCast(GetFakeTypedValue(checkArgType), convCheckConstraint))
  6424. {
  6425. constraintMatched = true;
  6426. }
  6427. else if (origCheckArgType->IsWrappableType())
  6428. {
  6429. if (origCheckArgType->IsSizedArray())
  6430. {
  6431. auto sizedArrayType = (BfSizedArrayType*)origCheckArgType;
  6432. if (convCheckConstraint->IsGenericTypeInstance())
  6433. {
  6434. auto convCheckConstraintInst = (BfTypeInstance*)convCheckConstraint;
  6435. if (convCheckConstraintInst->mTypeDef == mCompiler->mSizedArrayTypeDef)
  6436. {
  6437. if (convCheckConstraintInst->mGenericTypeInfo->mTypeGenericArguments[0] == sizedArrayType->mElementType)
  6438. {
  6439. auto constExprValueType = (BfConstExprValueType*)convCheckConstraintInst->mGenericTypeInfo->mTypeGenericArguments[1];
  6440. if (sizedArrayType->mElementCount == constExprValueType->mValue.mInt64)
  6441. constraintMatched = true;
  6442. }
  6443. }
  6444. }
  6445. }
  6446. if (!constraintMatched)
  6447. {
  6448. BfType* wrappedStructType = GetWrappedStructType(origCheckArgType, false);
  6449. if (CanCast(GetFakeTypedValue(wrappedStructType), convCheckConstraint))
  6450. constraintMatched = true;
  6451. }
  6452. }
  6453. if (!constraintMatched)
  6454. {
  6455. if (!ignoreErrors)
  6456. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must derive from '%s'", genericParamInst->GetName().c_str(),
  6457. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(), TypeToString(convCheckConstraint).c_str(),
  6458. _TypeToString(genericParamInst->mTypeConstraint).c_str()), checkArgTypeRef);
  6459. return false;
  6460. }
  6461. }
  6462. }
  6463. if ((genericParamInst->mInterfaceConstraints.size() > 0) && (origCheckArgType->IsInterface()))
  6464. {
  6465. PopulateType(origCheckArgType);
  6466. auto checkTypeInst = origCheckArgType->ToTypeInstance();
  6467. if (checkTypeInst->mTypeDef->mIsConcrete)
  6468. {
  6469. if (!ignoreErrors)
  6470. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be concrete interface '%s' for '%s', must be a concrete type", genericParamInst->GetName().c_str(),
  6471. TypeToString(origCheckArgType).c_str()), checkArgTypeRef);
  6472. return false;
  6473. }
  6474. }
  6475. for (auto checkConstraint : genericParamInst->mInterfaceConstraints)
  6476. {
  6477. BfType* convCheckConstraint = checkConstraint;
  6478. if (convCheckConstraint->IsUnspecializedType())
  6479. convCheckConstraint = ResolveGenericType(convCheckConstraint, NULL, methodGenericArgs);
  6480. if (convCheckConstraint == NULL)
  6481. return false;
  6482. BfTypeInstance* typeConstraintInst = convCheckConstraint->ToTypeInstance();
  6483. bool implementsInterface = false;
  6484. if (origCheckArgType != checkArgType)
  6485. {
  6486. implementsInterface = CanCast(BfTypedValue(BfIRValue::sValueless, origCheckArgType), convCheckConstraint);
  6487. }
  6488. if (!implementsInterface)
  6489. implementsInterface = CanCast(BfTypedValue(BfIRValue::sValueless, checkArgType), convCheckConstraint);
  6490. if ((!implementsInterface) && (origCheckArgType->IsWrappableType()))
  6491. {
  6492. BfTypeInstance* wrappedStructType = GetWrappedStructType(origCheckArgType, false);
  6493. if (TypeIsSubTypeOf(wrappedStructType, typeConstraintInst))
  6494. implementsInterface = true;
  6495. }
  6496. if ((!implementsInterface) && (origCheckArgType->IsTypedPrimitive()))
  6497. {
  6498. auto underlyingType = origCheckArgType->GetUnderlyingType();
  6499. BfTypeInstance* wrappedStructType = GetWrappedStructType(underlyingType, false);
  6500. if (TypeIsSubTypeOf(wrappedStructType, typeConstraintInst))
  6501. implementsInterface = true;
  6502. }
  6503. if (!implementsInterface)
  6504. {
  6505. if (!ignoreErrors)
  6506. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must implement '%s'", genericParamInst->GetName().c_str(),
  6507. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(), _TypeToString(checkConstraint).c_str()), checkArgTypeRef);
  6508. return false;
  6509. }
  6510. }
  6511. for (auto& checkOpConstraint : genericParamInst->mOperatorConstraints)
  6512. {
  6513. auto leftType = checkOpConstraint.mLeftType;
  6514. if ((leftType != NULL) && (leftType->IsUnspecializedType()))
  6515. leftType = ResolveGenericType(leftType, NULL, methodGenericArgs);
  6516. if (leftType != NULL)
  6517. leftType = FixIntUnknown(leftType);
  6518. auto rightType = checkOpConstraint.mRightType;
  6519. if ((rightType != NULL) && (rightType->IsUnspecializedType()))
  6520. rightType = ResolveGenericType(rightType, NULL, methodGenericArgs);
  6521. if (rightType != NULL)
  6522. rightType = FixIntUnknown(rightType);
  6523. BfConstraintState constraintSet;
  6524. constraintSet.mPrevState = mContext->mCurConstraintState;
  6525. constraintSet.mGenericParamInstance = genericParamInst;
  6526. constraintSet.mLeftType = leftType;
  6527. constraintSet.mRightType = rightType;
  6528. SetAndRestoreValue<BfConstraintState*> prevConstraintSet(mContext->mCurConstraintState, &constraintSet);
  6529. if (!CheckConstraintState(NULL))
  6530. return false;
  6531. if (checkOpConstraint.mBinaryOp != BfBinaryOp_None)
  6532. {
  6533. BfExprEvaluator exprEvaluator(this);
  6534. BfTypedValue leftValue(mBfIRBuilder->GetFakeVal(), leftType);
  6535. BfTypedValue rightValue(mBfIRBuilder->GetFakeVal(), rightType);
  6536. //
  6537. {
  6538. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  6539. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  6540. exprEvaluator.PerformBinaryOperation(NULL, NULL, checkOpConstraint.mBinaryOp, NULL, (BfBinOpFlags)(BfBinOpFlag_NoClassify | BfBinOpFlag_IsConstraintCheck), leftValue, rightValue);
  6541. }
  6542. if ((!exprEvaluator.mResult) ||
  6543. (!CanCast(exprEvaluator.mResult, origCheckArgType, BfCastFlags_NoConversionOperator)))
  6544. {
  6545. if (!ignoreErrors)
  6546. {
  6547. if (genericParamInst->mExternType != NULL)
  6548. *errorOut = Fail(StrFormat("Binary operation for '%s' must result in '%s' from binary operation '%s %s %s'",
  6549. GenericParamSourceToString(genericParamSource).c_str(), TypeToString(origCheckArgType).c_str(),
  6550. TypeToString(leftType).c_str(), BfGetOpName(checkOpConstraint.mBinaryOp), TypeToString(rightType).c_str()
  6551. ), checkArgTypeRef);
  6552. else
  6553. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must result from binary operation '%s %s %s'", genericParamInst->GetName().c_str(),
  6554. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(),
  6555. TypeToString(leftType).c_str(), BfGetOpName(checkOpConstraint.mBinaryOp), TypeToString(rightType).c_str()
  6556. ), checkArgTypeRef);
  6557. }
  6558. return false;
  6559. }
  6560. }
  6561. else
  6562. {
  6563. BfTypedValue rightValue(mBfIRBuilder->GetFakeVal(), rightType);
  6564. StringT<128> failedOpName;
  6565. if (checkOpConstraint.mCastToken == BfToken_Implicit)
  6566. {
  6567. if (!CanCast(rightValue, origCheckArgType, (BfCastFlags)(BfCastFlags_SilentFail | BfCastFlags_IsConstraintCheck)))
  6568. failedOpName = "implicit conversion from '";
  6569. }
  6570. else
  6571. {
  6572. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  6573. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  6574. if (checkOpConstraint.mCastToken == BfToken_Explicit)
  6575. {
  6576. if (!CastToValue(NULL, rightValue, origCheckArgType, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_SilentFail | BfCastFlags_IsConstraintCheck)))
  6577. failedOpName = "explicit conversion from '";
  6578. }
  6579. else
  6580. {
  6581. BfExprEvaluator exprEvaluator(this);
  6582. exprEvaluator.mResult = rightValue;
  6583. exprEvaluator.PerformUnaryOperation(NULL, checkOpConstraint.mUnaryOp, NULL, BfUnaryOpFlag_IsConstraintCheck);
  6584. if ((!exprEvaluator.mResult) ||
  6585. (!CanCast(exprEvaluator.mResult, origCheckArgType)))
  6586. {
  6587. failedOpName += "unary operation '";
  6588. failedOpName += BfGetOpName(checkOpConstraint.mUnaryOp);
  6589. }
  6590. }
  6591. }
  6592. if (!failedOpName.IsEmpty())
  6593. {
  6594. if (!ignoreErrors)
  6595. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must result from %s%s'", genericParamInst->GetName().c_str(),
  6596. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(),
  6597. failedOpName.c_str(), TypeToString(rightType).c_str()
  6598. ), checkArgTypeRef);
  6599. return false;
  6600. }
  6601. }
  6602. }
  6603. return true;
  6604. }
  6605. BfGenericParamType* BfModule::GetGenericParamType(BfGenericParamKind paramKind, int paramIdx)
  6606. {
  6607. if (paramIdx < (int)mContext->mGenericParamTypes[paramKind].size())
  6608. {
  6609. auto genericParamType = mContext->mGenericParamTypes[paramKind][paramIdx];
  6610. return genericParamType;
  6611. }
  6612. auto genericParamType = new BfGenericParamType();
  6613. genericParamType->mContext = mContext;
  6614. genericParamType->mGenericParamKind = paramKind;
  6615. genericParamType->mGenericParamIdx = paramIdx;
  6616. PopulateType(genericParamType);
  6617. BF_ASSERT(paramIdx == (int)mContext->mGenericParamTypes[paramKind].size());
  6618. mContext->mGenericParamTypes[paramKind].push_back(genericParamType);
  6619. BfResolvedTypeSet::LookupContext lookupCtx;
  6620. lookupCtx.mModule = this;
  6621. BfResolvedTypeSet::Entry* typeEntry = NULL;
  6622. auto inserted = mContext->mResolvedTypes.Insert(genericParamType, &lookupCtx, &typeEntry);
  6623. BF_ASSERT(inserted);
  6624. typeEntry->mValue = genericParamType;
  6625. return genericParamType;
  6626. }
  6627. static int sValueFromExprIdx = 0;
  6628. BfTypedValue BfModule::FlushNullConditional(BfTypedValue result, bool ignoreNullable)
  6629. {
  6630. auto pendingNullCond = mCurMethodState->mPendingNullConditional;
  6631. if ((result) && (!ignoreNullable))
  6632. {
  6633. auto notNullBB = mBfIRBuilder->GetInsertBlock();
  6634. //TODO: Make this work, needed for 'void' and such
  6635. BfType* nullableType = NULL;
  6636. if ((result.mType->IsValueType()) && (!result.mType->IsNullable()))
  6637. {
  6638. BfTypeVector typeVec;
  6639. typeVec.push_back(result.mType);
  6640. nullableType = ResolveTypeDef(mCompiler->mNullableTypeDef, typeVec);
  6641. BF_ASSERT(nullableType != NULL);
  6642. }
  6643. // Go back to start and do any setup we need
  6644. mBfIRBuilder->SetInsertPoint(pendingNullCond->mPrevBB);
  6645. BfTypedValue nullableTypedValue;
  6646. if (nullableType != NULL)
  6647. {
  6648. nullableTypedValue = BfTypedValue(CreateAlloca(nullableType, true, "nullCond.nullable"), nullableType, true);
  6649. mBfIRBuilder->CreateMemSet(nullableTypedValue.mValue, GetConstValue(0, GetPrimitiveType(BfTypeCode_Int8)),
  6650. GetConstValue(nullableType->mSize), nullableType->mAlign);
  6651. }
  6652. mBfIRBuilder->CreateBr(pendingNullCond->mCheckBB);
  6653. // Now that we have the nullableTypedValue we can set that, or just jump if we didn't need it
  6654. mBfIRBuilder->SetInsertPoint(notNullBB);
  6655. result = LoadValue(result);
  6656. if (nullableTypedValue)
  6657. {
  6658. auto elementType = nullableType->GetUnderlyingType();
  6659. if (elementType->IsVar())
  6660. {
  6661. // Do nothing
  6662. }
  6663. else if (elementType->IsValuelessType())
  6664. {
  6665. BfIRValue ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 1); // mHasValue
  6666. mBfIRBuilder->CreateStore(GetConstValue(1, GetPrimitiveType(BfTypeCode_Boolean)), ptrValue);
  6667. }
  6668. else
  6669. {
  6670. BfIRValue ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 1); // mValue
  6671. mBfIRBuilder->CreateStore(result.mValue, ptrValue);
  6672. ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 2); // mHasValue
  6673. mBfIRBuilder->CreateStore(GetConstValue(1, GetPrimitiveType(BfTypeCode_Boolean)), ptrValue);
  6674. }
  6675. result = nullableTypedValue;
  6676. }
  6677. mBfIRBuilder->CreateBr(pendingNullCond->mDoneBB);
  6678. AddBasicBlock(pendingNullCond->mDoneBB);
  6679. if (nullableType == NULL)
  6680. {
  6681. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapType(result.mType), 1 + (int)pendingNullCond->mNotNullBBs.size());
  6682. mBfIRBuilder->AddPhiIncoming(phi, result.mValue, notNullBB);
  6683. mBfIRBuilder->AddPhiIncoming(phi, GetDefaultValue(result.mType), pendingNullCond->mCheckBB);
  6684. for (int notNullIdx = 0; notNullIdx < (int)pendingNullCond->mNotNullBBs.size() - 1; notNullIdx++)
  6685. {
  6686. auto prevNotNullBB = pendingNullCond->mNotNullBBs[notNullIdx];
  6687. mBfIRBuilder->AddPhiIncoming(phi, GetDefaultValue(result.mType), prevNotNullBB);
  6688. }
  6689. result.mValue = phi;
  6690. }
  6691. }
  6692. else
  6693. {
  6694. mBfIRBuilder->CreateBr(pendingNullCond->mDoneBB);
  6695. mBfIRBuilder->SetInsertPoint(pendingNullCond->mPrevBB);
  6696. mBfIRBuilder->CreateBr(pendingNullCond->mCheckBB);
  6697. AddBasicBlock(pendingNullCond->mDoneBB);
  6698. }
  6699. delete mCurMethodState->mPendingNullConditional;
  6700. mCurMethodState->mPendingNullConditional = NULL;
  6701. return result;
  6702. }
  6703. BF_NOINLINE void BfModule::EvaluateWithNewScope(BfExprEvaluator& exprEvaluator, BfExpression* expr, BfEvalExprFlags flags)
  6704. {
  6705. BfScopeData newScope;
  6706. newScope.mOuterIsConditional = true;
  6707. newScope.mAllowTargeting = false;
  6708. mCurMethodState->AddScope(&newScope);
  6709. NewScopeState();
  6710. exprEvaluator.mBfEvalExprFlags = flags;
  6711. exprEvaluator.Evaluate(expr, (flags & BfEvalExprFlags_PropogateNullConditional) != 0, (flags & BfEvalExprFlags_IgnoreNullConditional) != 0, (flags & BfEvalExprFlags_AllowSplat) != 0);
  6712. RestoreScopeState();
  6713. }
  6714. BfTypedValue BfModule::CreateValueFromExpression(BfExprEvaluator& exprEvaluator, BfExpression* expr, BfType* wantTypeRef, BfEvalExprFlags flags, BfType** outOrigType)
  6715. {
  6716. //
  6717. {
  6718. BP_ZONE("CreateValueFromExpression:CheckStack");
  6719. StackHelper stackHelper;
  6720. if (!stackHelper.CanStackExpand(64 * 1024))
  6721. {
  6722. BfTypedValue result;
  6723. if (!stackHelper.Execute([&]()
  6724. {
  6725. result = CreateValueFromExpression(exprEvaluator, expr, wantTypeRef, flags, outOrigType);
  6726. }))
  6727. {
  6728. Fail("Expression too complex to compile", expr);
  6729. }
  6730. return result;
  6731. }
  6732. }
  6733. BP_ZONE("BfModule::CreateValueFromExpression");
  6734. if (outOrigType != NULL)
  6735. *outOrigType = NULL;
  6736. exprEvaluator.mExpectingType = wantTypeRef;
  6737. exprEvaluator.mBfEvalExprFlags = flags;
  6738. exprEvaluator.mExplicitCast = (flags & BfEvalExprFlags_ExplicitCast) != 0;
  6739. if ((flags & BfEvalExprFlags_CreateConditionalScope) != 0)
  6740. {
  6741. EvaluateWithNewScope(exprEvaluator, expr, flags);
  6742. }
  6743. else
  6744. exprEvaluator.Evaluate(expr, (flags & BfEvalExprFlags_PropogateNullConditional) != 0, (flags & BfEvalExprFlags_IgnoreNullConditional) != 0, true);
  6745. if (!exprEvaluator.mResult)
  6746. {
  6747. if (!mCompiler->mPassInstance->HasFailed())
  6748. Fail("INTERNAL ERROR: No expression result returned but no error caught in expression evaluator", expr);
  6749. return BfTypedValue();
  6750. }
  6751. auto typedVal = exprEvaluator.mResult;
  6752. if (typedVal.mKind == BfTypedValueKind_GenericConstValue)
  6753. {
  6754. BF_ASSERT(typedVal.mType->IsGenericParam());
  6755. auto genericParamDef = GetGenericParamInstance((BfGenericParamType*)typedVal.mType);
  6756. bool handled = false;
  6757. if ((genericParamDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  6758. {
  6759. auto genericTypeConstraint = genericParamDef->mTypeConstraint;
  6760. if (genericTypeConstraint != NULL)
  6761. {
  6762. auto primType = genericTypeConstraint->ToPrimitiveType();
  6763. if (primType != NULL)
  6764. {
  6765. BfTypedValue result;
  6766. result.mKind = BfTypedValueKind_Value;
  6767. result.mType = genericTypeConstraint;
  6768. result.mValue = mBfIRBuilder->GetUndefConstValue(primType->mTypeDef->mTypeCode);
  6769. typedVal = result;
  6770. handled = true;
  6771. }
  6772. }
  6773. }
  6774. if (!handled)
  6775. {
  6776. //Fail("Only const generic parameters can be used as values", expr);
  6777. AssertErrorState();
  6778. return BfTypedValue();
  6779. }
  6780. }
  6781. if ((flags & BfEvalExprFlags_AllowIntUnknown) == 0)
  6782. FixIntUnknown(typedVal);
  6783. exprEvaluator.CheckResultForReading(typedVal);
  6784. if ((wantTypeRef == NULL) || (!wantTypeRef->IsRef()))
  6785. {
  6786. if ((flags & BfEvalExprFlags_NoCast) == 0)
  6787. {
  6788. // Only allow a 'ref' type if we have an explicit 'ref' operator
  6789. bool allowRef = false;
  6790. BfExpression* checkExpr = expr;
  6791. while (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(checkExpr))
  6792. checkExpr = parenExpr->mExpression;
  6793. if (auto unaryOp = BfNodeDynCast<BfUnaryOperatorExpression>(checkExpr))
  6794. {
  6795. if ((unaryOp->mOp == BfUnaryOp_Ref) || (unaryOp->mOp == BfUnaryOp_Mut))
  6796. allowRef = true;
  6797. }
  6798. if (!allowRef)
  6799. typedVal = RemoveRef(typedVal);
  6800. }
  6801. }
  6802. if ((!typedVal.mType->IsComposite()) && (!typedVal.mType->IsGenericParam())) // Load non-structs by default
  6803. {
  6804. if ((!mBfIRBuilder->mIgnoreWrites) && (!typedVal.mType->IsValuelessType()) && (!typedVal.mType->IsVar()))
  6805. {
  6806. BF_ASSERT(!typedVal.mValue.IsFake());
  6807. }
  6808. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  6809. }
  6810. if (wantTypeRef != NULL)
  6811. {
  6812. if (outOrigType != NULL)
  6813. *outOrigType = typedVal.mType;
  6814. if ((flags & BfEvalExprFlags_NoCast) == 0)
  6815. {
  6816. BfCastFlags castFlags = ((flags & BfEvalExprFlags_ExplicitCast) != 0) ? BfCastFlags_Explicit : BfCastFlags_None;
  6817. if ((flags & BfEvalExprFlags_FieldInitializer) != 0)
  6818. castFlags = (BfCastFlags)(castFlags | BfCastFlags_WarnOnBox);
  6819. typedVal = Cast(expr, typedVal, wantTypeRef, castFlags);
  6820. if (!typedVal)
  6821. return typedVal;
  6822. }
  6823. //WTF- why did we have this?
  6824. /*if ((flags & BfEvalExprFlags_ExplicitCast) == 0)
  6825. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);*/
  6826. if (exprEvaluator.mIsVolatileReference)
  6827. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  6828. }
  6829. if ((typedVal.mType->IsValueType()) && ((flags & BfEvalExprFlags_NoValueAddr) != 0))
  6830. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  6831. return typedVal;
  6832. }
  6833. BfTypedValue BfModule::CreateValueFromExpression(BfExpression* expr, BfType* wantTypeRef, BfEvalExprFlags flags, BfType** outOrigType)
  6834. {
  6835. BfExprEvaluator exprEvaluator(this);
  6836. return CreateValueFromExpression(exprEvaluator, expr, wantTypeRef, flags, outOrigType);
  6837. }
  6838. BfTypedValue BfModule::GetOrCreateVarAddr(BfExpression* expr)
  6839. {
  6840. BfExprEvaluator exprEvaluator(this);
  6841. exprEvaluator.Evaluate(expr);
  6842. if (!exprEvaluator.mResult)
  6843. {
  6844. Fail("Invalid expression type", expr);
  6845. return BfTypedValue();
  6846. }
  6847. if (!exprEvaluator.mResult.IsAddr())
  6848. {
  6849. Fail("Cannot assign to value", expr);
  6850. return BfTypedValue();
  6851. }
  6852. return exprEvaluator.mResult;
  6853. }
  6854. // Clear memory, set classVData, call init. Actual ctor is called elsewhere.
  6855. void BfModule::InitTypeInst(BfTypedValue typedValue, BfScopeData* scopeData, bool zeroMemory, BfIRValue sizeValue)
  6856. {
  6857. auto typeInstance = typedValue.mType->ToTypeInstance();
  6858. if (zeroMemory)
  6859. {
  6860. int zeroAlign = typedValue.mType->mAlign;
  6861. if (typeInstance != NULL)
  6862. zeroAlign = typeInstance->mInstAlign;
  6863. mBfIRBuilder->CreateMemSet(typedValue.mValue, GetConstValue8(0), sizeValue, zeroAlign);
  6864. }
  6865. if (!typedValue.mType->IsObject())
  6866. {
  6867. return;
  6868. }
  6869. if ((scopeData == NULL) && (mCurMethodState != NULL))
  6870. return; // Handled in heap alloc funcs
  6871. auto typeDef = typeInstance->mTypeDef;
  6872. mBfIRBuilder->PopulateType(typedValue.mType);
  6873. auto vObjectAddr = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, 0);
  6874. bool isAutocomplete = mCompiler->IsAutocomplete();
  6875. BfIRValue vDataRef;
  6876. if (!isAutocomplete)
  6877. {
  6878. vDataRef = GetClassVDataPtr(typeInstance);
  6879. }
  6880. auto i8Type = GetPrimitiveType(BfTypeCode_Int8);
  6881. auto ptrType = CreatePointerType(i8Type);
  6882. auto ptrPtrType = CreatePointerType(ptrType);
  6883. PopulateType(ptrPtrType, BfPopulateType_Declaration);
  6884. PopulateType(ptrType, BfPopulateType_Declaration);
  6885. auto destAddr = mBfIRBuilder->CreateBitCast(vObjectAddr, mBfIRBuilder->MapType(ptrPtrType));
  6886. if (!isAutocomplete)
  6887. {
  6888. if (mCompiler->mOptions.mObjectHasDebugFlags)
  6889. {
  6890. auto objectPtr = mBfIRBuilder->CreateBitCast(destAddr, mBfIRBuilder->MapType(mContext->mBfObjectType));
  6891. SizedArray<BfIRValue, 4> llvmArgs;
  6892. llvmArgs.push_back(objectPtr);
  6893. llvmArgs.push_back(vDataRef);
  6894. auto objectStackInitMethod = GetInternalMethod("Dbg_ObjectStackInit");
  6895. if (objectStackInitMethod)
  6896. mBfIRBuilder->CreateCall(objectStackInitMethod.mFunc, llvmArgs);
  6897. }
  6898. else
  6899. {
  6900. auto srcVal = mBfIRBuilder->CreateBitCast(vDataRef, mBfIRBuilder->MapType(ptrType));
  6901. auto objectPtr = mBfIRBuilder->CreateBitCast(destAddr, mBfIRBuilder->MapType(ptrType));
  6902. mBfIRBuilder->CreateStore(srcVal, destAddr);
  6903. }
  6904. }
  6905. }
  6906. BfIRValue BfModule::AllocBytes(BfAstNode* refNode, const BfAllocTarget& allocTarget, BfType* type, BfIRValue sizeValue, BfIRValue alignValue, BfAllocFlags allocFlags/*, bool zeroMemory, bool defaultToMalloc*/)
  6907. {
  6908. BfIRValue result;
  6909. BfType* ptrType;
  6910. if ((type->IsObject()) && ((allocFlags & BfAllocFlags_RawArray) == 0))
  6911. ptrType = type;
  6912. else
  6913. ptrType = CreatePointerType(type);
  6914. if ((allocTarget.mScopedInvocationTarget != NULL) || (allocTarget.mCustomAllocator))
  6915. {
  6916. auto intType = GetPrimitiveType(BfTypeCode_IntPtr);
  6917. SizedArray<BfExpression*, 2> argExprs;
  6918. BfTypedValueExpression typedValueExpr;
  6919. typedValueExpr.Init(BfTypedValue(sizeValue, intType));
  6920. typedValueExpr.mRefNode = refNode;
  6921. argExprs.push_back(&typedValueExpr);
  6922. BfTypedValueExpression appendSizeValueExpr;
  6923. appendSizeValueExpr.Init(BfTypedValue(alignValue, intType));
  6924. appendSizeValueExpr.mRefNode = refNode;
  6925. argExprs.push_back(&appendSizeValueExpr);
  6926. BfExprEvaluator exprEvaluator(this);
  6927. BfTypedValue allocResult;
  6928. if (allocTarget.mScopedInvocationTarget != NULL)
  6929. {
  6930. SizedArray<BfTypeReference*, 2> genericArgs;
  6931. exprEvaluator.DoInvocation(allocTarget.mScopedInvocationTarget, NULL, argExprs, NULL);
  6932. allocResult = LoadValue(exprEvaluator.mResult);
  6933. }
  6934. else if (allocTarget.mCustomAllocator)
  6935. {
  6936. auto customTypeInst = allocTarget.mCustomAllocator.mType->ToTypeInstance();
  6937. if (customTypeInst != NULL)
  6938. {
  6939. BfTypedValueExpression typeValueExpr;
  6940. String allocMethodName = "Alloc";
  6941. if (GetRawMethodByName(customTypeInst, "AllocTyped", -1, true, true))
  6942. {
  6943. allocMethodName = "AllocTyped";
  6944. auto typeType = ResolveTypeDef(mCompiler->mTypeTypeDef);
  6945. auto typeRefVal = CreateTypeDataRef(type);
  6946. typeValueExpr.Init(BfTypedValue(typeRefVal, typeType));
  6947. typeValueExpr.mRefNode = refNode;
  6948. argExprs.Insert(0, &typeValueExpr);
  6949. }
  6950. if (HasMixin(customTypeInst, allocMethodName, 2))
  6951. {
  6952. BfSizedArray<BfExpression*> argExprArr;
  6953. argExprArr.mSize = (int)argExprs.size();
  6954. argExprArr.mVals = &argExprs[0];
  6955. exprEvaluator.InjectMixin(refNode, allocTarget.mCustomAllocator, false, allocMethodName, argExprs, {});
  6956. allocResult = exprEvaluator.GetResult();
  6957. }
  6958. else
  6959. {
  6960. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  6961. BfResolvedArgs argValues(&sizedArgExprs);
  6962. exprEvaluator.ResolveArgValues(argValues);
  6963. SetAndRestoreValue<bool> prevNoBind(mCurMethodState->mNoBind, true);
  6964. allocResult = exprEvaluator.MatchMethod(refNode, NULL, allocTarget.mCustomAllocator, false, false, allocMethodName, argValues, NULL);
  6965. }
  6966. }
  6967. }
  6968. if (allocResult)
  6969. {
  6970. if (allocResult.mType->IsVoidPtr())
  6971. result = mBfIRBuilder->CreateBitCast(allocResult.mValue, mBfIRBuilder->MapType(ptrType));
  6972. else
  6973. result = CastToValue(refNode, allocResult, ptrType, BfCastFlags_Explicit);
  6974. return result;
  6975. }
  6976. }
  6977. if ((allocFlags & BfAllocFlags_NoDefaultToMalloc) != 0)
  6978. return result;
  6979. if (mCompiler->mOptions.mDebugAlloc)
  6980. {
  6981. BfIRValue allocData = GetDbgRawAllocData(type);
  6982. BfModuleMethodInstance allocMethod = GetInternalMethod("Dbg_RawAlloc", 2);
  6983. SizedArray<BfIRValue, 2> llvmArgs;
  6984. llvmArgs.push_back(sizeValue);
  6985. llvmArgs.push_back(allocData);
  6986. BfIRValue bitData = mBfIRBuilder->CreateCall(allocMethod.mFunc, llvmArgs);
  6987. return mBfIRBuilder->CreateBitCast(bitData, mBfIRBuilder->MapType(ptrType));
  6988. }
  6989. BfModuleMethodInstance moduleMethodInstance;
  6990. moduleMethodInstance = GetInternalMethod("Malloc");
  6991. SizedArray<BfIRValue, 1> llvmArgs;
  6992. llvmArgs.push_back(sizeValue);
  6993. auto func = moduleMethodInstance.mFunc;
  6994. if ((!func) || (func.IsFake()))
  6995. {
  6996. BF_ASSERT((mCompiler->mIsResolveOnly) || (mBfIRBuilder->mIgnoreWrites));
  6997. return mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(ptrType));
  6998. }
  6999. BfIRValue bitData = mBfIRBuilder->CreateCall(func, llvmArgs);
  7000. if ((allocFlags & BfAllocFlags_ZeroMemory) != 0)
  7001. mBfIRBuilder->CreateMemSet(bitData, GetConstValue8(0), sizeValue, alignValue);
  7002. result = mBfIRBuilder->CreateBitCast(bitData, mBfIRBuilder->MapType(ptrType));
  7003. return result;
  7004. }
  7005. BfIRValue BfModule::GetMarkFuncPtr(BfType* type)
  7006. {
  7007. if (type->IsStruct())
  7008. {
  7009. auto typeInstance = type->ToTypeInstance();
  7010. BfModuleMethodInstance moduleMethodInst = GetMethodByName(typeInstance, BF_METHODNAME_MARKMEMBERS, 0, true);
  7011. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  7012. }
  7013. else if (type->IsObjectOrInterface())
  7014. {
  7015. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  7016. BfModuleMethodInstance moduleMethodInst = GetMethodByName(gcType, "MarkDerefedObject");
  7017. BF_ASSERT(moduleMethodInst.mFunc);
  7018. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  7019. }
  7020. else
  7021. {
  7022. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  7023. BfExprEvaluator exprEvaluator(this);
  7024. SizedArray<BfResolvedArg, 1> resolvedArgs;
  7025. BfResolvedArg resolvedArg;
  7026. resolvedArg.mTypedValue = BfTypedValue(mBfIRBuilder->GetFakeVal(), type, type->IsComposite());
  7027. resolvedArgs.Add(resolvedArg);
  7028. BfMethodMatcher methodMatcher(NULL, this, "Mark", resolvedArgs, NULL);
  7029. methodMatcher.CheckType(gcType, BfTypedValue(), false);
  7030. BfModuleMethodInstance moduleMethodInst = exprEvaluator.GetSelectedMethod(NULL, methodMatcher.mBestMethodTypeInstance, methodMatcher.mBestMethodDef, methodMatcher);
  7031. BF_ASSERT(moduleMethodInst.mFunc);
  7032. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  7033. }
  7034. return BfIRValue();
  7035. }
  7036. BfIRValue BfModule::GetDbgRawAllocData(BfType* type)
  7037. {
  7038. BfIRValue allocDataValue;
  7039. if (mDbgRawAllocDataRefs.TryGetValue(type, &allocDataValue))
  7040. return allocDataValue;
  7041. BfIRValue markFuncPtr;
  7042. if (type->WantsGCMarking())
  7043. markFuncPtr = GetMarkFuncPtr(type);
  7044. else
  7045. markFuncPtr = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  7046. BfIRValue typeDataRef = CreateTypeDataRef(type);
  7047. auto dbgRawAllocDataType = ResolveTypeDef(mCompiler->mDbgRawAllocDataTypeDef)->ToTypeInstance();
  7048. BfTypeInstance* typeInstance = type->ToTypeInstance();
  7049. if (typeInstance == NULL)
  7050. {
  7051. typeInstance = GetWrappedStructType(type);
  7052. if (typeInstance != NULL)
  7053. AddDependency(typeInstance, mCurTypeInstance, BfDependencyMap::DependencyFlag_Allocates);
  7054. }
  7055. if (typeInstance != NULL)
  7056. PopulateType(typeInstance);
  7057. int stackCount = mCompiler->mOptions.mAllocStackCount;
  7058. if ((typeInstance != NULL) && (typeInstance->mTypeOptionsIdx != -1))
  7059. {
  7060. auto typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  7061. stackCount = BfTypeOptions::Apply(stackCount, typeOptions->mAllocStackTraceDepth);
  7062. }
  7063. SizedArray<BfIRValue, 2> dataValues;
  7064. dataValues.Add(mBfIRBuilder->CreateConstStructZero(mBfIRBuilder->MapType(dbgRawAllocDataType->mBaseType, BfIRPopulateType_Full)));
  7065. dataValues.Add(typeDataRef);
  7066. dataValues.Add(markFuncPtr);
  7067. dataValues.Add(mBfIRBuilder->CreateConst(BfTypeCode_Int32, stackCount));
  7068. BfIRValue dataStruct = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapType(dbgRawAllocDataType, BfIRPopulateType_Full), dataValues);
  7069. allocDataValue = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(dbgRawAllocDataType), true, BfIRLinkageType_Internal, dataStruct, "__allocData_" + BfSafeMangler::Mangle(type));
  7070. mDbgRawAllocDataRefs.TryAdd(type, allocDataValue);
  7071. return allocDataValue;
  7072. }
  7073. BfIRValue BfModule::AllocFromType(BfType* type, const BfAllocTarget& allocTarget, BfIRValue appendSizeValue, BfIRValue arraySize, int arrayDim, BfAllocFlags allocFlags, int alignOverride)
  7074. {
  7075. BP_ZONE("AllocFromType");
  7076. BfScopeData* scopeData = allocTarget.mScopeData;
  7077. BF_ASSERT(!type->IsVar());
  7078. auto typeInstance = type->ToTypeInstance();
  7079. if ((typeInstance == NULL) && (type->IsGenericParam()))
  7080. typeInstance = mContext->mBfObjectType;
  7081. bool isHeapAlloc = scopeData == NULL;
  7082. bool isScopeAlloc = scopeData != NULL;
  7083. bool isLoopedAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsLooped(scopeData));
  7084. bool isDynAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsDyn(scopeData));
  7085. bool isRawArrayAlloc = (allocFlags & BfAllocFlags_RawArray) != 0;
  7086. bool zeroMemory = (allocFlags & BfAllocFlags_ZeroMemory) != 0;
  7087. bool noDtorCall = (allocFlags & BfAllocFlags_NoDtorCall) != 0;
  7088. if ((type->IsValuelessType()) && ((!arraySize) || (isRawArrayAlloc)))
  7089. {
  7090. BfPointerType* ptrType = CreatePointerType(type);
  7091. auto val = mBfIRBuilder->CreateIntToPtr(mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1), mBfIRBuilder->MapType(ptrType));
  7092. return val;
  7093. }
  7094. if (typeInstance != NULL)
  7095. mBfIRBuilder->PopulateType(typeInstance);
  7096. bool hasCustomAllocator = (allocTarget.mCustomAllocator) || (allocTarget.mScopedInvocationTarget != NULL);
  7097. if ((!hasCustomAllocator) && (mBfIRBuilder->mIgnoreWrites))
  7098. {
  7099. if (arraySize)
  7100. {
  7101. if (isRawArrayAlloc)
  7102. {
  7103. BfPointerType* ptrType = CreatePointerType(type);
  7104. return GetDefaultValue(ptrType);
  7105. }
  7106. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  7107. return GetDefaultValue(arrayType);
  7108. }
  7109. if (type->IsValueType())
  7110. {
  7111. BfPointerType* ptrType = CreatePointerType(type);
  7112. return GetDefaultValue(ptrType);
  7113. }
  7114. return mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type));
  7115. }
  7116. AddDependency(type, mCurTypeInstance, BfDependencyMap::DependencyFlag_Allocates);
  7117. BfIRValue sizeValue;
  7118. BfIRType allocType = mBfIRBuilder->MapType(type);
  7119. int allocSize = type->mSize;
  7120. int allocAlign = type->mAlign;
  7121. if (typeInstance != NULL)
  7122. {
  7123. if (!mBfIRBuilder->mIgnoreWrites)
  7124. typeInstance->mHasBeenInstantiated = true;
  7125. allocSize = typeInstance->mInstSize;
  7126. allocAlign = typeInstance->mInstAlign;
  7127. //if (typeInstance->IsEnum())
  7128. //allocType = typeInstance->mIRType;
  7129. allocType = mBfIRBuilder->MapTypeInst(typeInstance);
  7130. }
  7131. if (alignOverride != -1)
  7132. allocAlign = alignOverride;
  7133. // The "dynSize" cases:
  7134. // If we are not dyn, but we are a variable size and could be looped over multiple times then we attempt to reuse
  7135. // the last stack space. We won't use StackSave and StackRestore because a scoped alloc that occurs after this but
  7136. // needs to be retained after the current scopeData (ie: scopeData::), then it would cause these allocs to accumulate even
  7137. // though we'd expect their stack space to be released
  7138. auto _CreateDynAlloc = [&](const BfIRValue& sizeValue, int align)
  7139. {
  7140. MarkDynStack(scopeData);
  7141. BfType* intType = GetPrimitiveType(BfTypeCode_IntPtr);
  7142. // For dynamically sized scoped allocs, we need to check the previous size to see if we need to realloc
  7143. BfType* voidType = GetPrimitiveType(BfTypeCode_None);
  7144. BfType* voidPtrType = CreatePointerType(voidType);
  7145. if (!mCurMethodState->mDynStackRevIdx)
  7146. {
  7147. mCurMethodState->mDynStackRevIdx = CreateAlloca(intType, false, "curDynStackRevIdx");
  7148. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  7149. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  7150. auto storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), mCurMethodState->mDynStackRevIdx);
  7151. mBfIRBuilder->ClearDebugLocation(storeInst);
  7152. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  7153. }
  7154. auto byteType = GetPrimitiveType(BfTypeCode_Int8);
  7155. auto bytePtrType = CreatePointerType(byteType);
  7156. auto dynSizeAllocaInst = CreateAlloca(intType, false, "dynSize");
  7157. auto dynStackRevIdx = CreateAlloca(intType, false, "dynStackRevIdx");
  7158. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  7159. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  7160. auto storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), dynSizeAllocaInst);
  7161. mBfIRBuilder->ClearDebugLocation(storeInst);
  7162. storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), dynStackRevIdx);
  7163. mBfIRBuilder->ClearDebugLocation(storeInst);
  7164. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  7165. auto dynPtrAllocaInst = CreateAlloca(bytePtrType, false, "dynPtr");
  7166. if (IsTargetingBeefBackend())
  7167. {
  7168. // Since we don't allocate a debug variable for this, with LifetimeExtends, the easiest way
  7169. // to ensure there isn't any register collision during looping is just to not allow it to
  7170. // bind to a register at all
  7171. mBfIRBuilder->SetAllocaForceMem(dynSizeAllocaInst);
  7172. mBfIRBuilder->SetAllocaForceMem(dynPtrAllocaInst);
  7173. }
  7174. auto resizeBB = mBfIRBuilder->CreateBlock("dynAlloc.resize");
  7175. auto endBB = mBfIRBuilder->CreateBlock("dynAlloc.end");
  7176. auto verCheckBB = mBfIRBuilder->CreateBlock("dynAlloc.verCheck");
  7177. auto curDynStackRevIdx = mBfIRBuilder->CreateLoad(mCurMethodState->mDynStackRevIdx);
  7178. auto prevSize = mBfIRBuilder->CreateLoad(dynSizeAllocaInst);
  7179. auto isGreater = mBfIRBuilder->CreateCmpGT(sizeValue, prevSize, true);
  7180. mBfIRBuilder->CreateCondBr(isGreater, resizeBB, verCheckBB);
  7181. mBfIRBuilder->AddBlock(verCheckBB);
  7182. mBfIRBuilder->SetInsertPoint(verCheckBB);
  7183. auto prevDynStackRevIdx = mBfIRBuilder->CreateLoad(dynStackRevIdx);
  7184. auto dynStackChanged = mBfIRBuilder->CreateCmpNE(prevDynStackRevIdx, curDynStackRevIdx);
  7185. mBfIRBuilder->CreateCondBr(dynStackChanged, resizeBB, endBB);
  7186. mBfIRBuilder->AddBlock(resizeBB);
  7187. mBfIRBuilder->SetInsertPoint(resizeBB);
  7188. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  7189. mBfIRBuilder->SetAllocaAlignment(allocaInst, align);
  7190. mBfIRBuilder->CreateStore(allocaInst, dynPtrAllocaInst);
  7191. mBfIRBuilder->CreateStore(sizeValue, dynSizeAllocaInst);
  7192. mBfIRBuilder->CreateStore(curDynStackRevIdx, dynStackRevIdx);
  7193. mBfIRBuilder->CreateBr(endBB);
  7194. mBfIRBuilder->AddBlock(endBB);
  7195. mBfIRBuilder->SetInsertPoint(endBB);
  7196. return mBfIRBuilder->CreateLoad(dynPtrAllocaInst);
  7197. };
  7198. if (isScopeAlloc)
  7199. {
  7200. if (arraySize)
  7201. {
  7202. bool isConstantArraySize = arraySize.IsConst();
  7203. if (isRawArrayAlloc)
  7204. {
  7205. BfPointerType* ptrType = CreatePointerType(type);
  7206. if ((!isDynAlloc) && (!isConstantArraySize) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  7207. {
  7208. BfIRValue sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  7209. auto loadedPtr = _CreateDynAlloc(sizeValue, type->mAlign);
  7210. InitTypeInst(BfTypedValue(loadedPtr, ptrType), scopeData, zeroMemory, sizeValue);
  7211. return mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(type)));
  7212. }
  7213. else
  7214. {
  7215. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  7216. isDynAlloc = (isDynAlloc) || (!arraySize.IsConst());
  7217. if (!isDynAlloc)
  7218. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  7219. else
  7220. {
  7221. MarkDynStack(scopeData);
  7222. SaveStackState(scopeData);
  7223. }
  7224. int typeSize = type->GetStride();
  7225. BfIRValue allocaInst;
  7226. BfIRValue result;
  7227. if ((typeInstance == NULL) || (typeInstance->mIsCRepr))
  7228. {
  7229. sizeValue = mBfIRBuilder->CreateMul(GetConstValue(typeSize), arraySize);
  7230. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type), arraySize);
  7231. result = allocaInst;
  7232. }
  7233. else
  7234. {
  7235. if (typeInstance->IsStruct())
  7236. typeSize = typeInstance->GetInstStride();
  7237. auto byteType = GetPrimitiveStructType(BfTypeCode_Int8);
  7238. sizeValue = mBfIRBuilder->CreateMul(GetConstValue(typeSize), arraySize);
  7239. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  7240. auto ptrType = CreatePointerType(typeInstance);
  7241. result = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(ptrType));
  7242. if (!isDynAlloc)
  7243. mBfIRBuilder->ClearDebugLocation(result);
  7244. }
  7245. if (!isDynAlloc)
  7246. mBfIRBuilder->ClearDebugLocation(allocaInst);
  7247. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  7248. if (!isDynAlloc)
  7249. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  7250. auto typedVal = BfTypedValue(result, type, BfTypedValueKind_Addr);
  7251. if (arraySize.IsConst())
  7252. {
  7253. auto constant = mBfIRBuilder->GetConstant(arraySize);
  7254. if (constant->mInt64 == 0)
  7255. noDtorCall = true;
  7256. }
  7257. if (!noDtorCall)
  7258. {
  7259. bool isConstSize = arraySize.IsConst();
  7260. BfIRBlock clearBlock;
  7261. BfIRBlock contBlock;
  7262. if (!isConstSize)
  7263. {
  7264. clearBlock = mBfIRBuilder->CreateBlock("clear");
  7265. contBlock = mBfIRBuilder->CreateBlock("clearCont");
  7266. mBfIRBuilder->CreateCondBr(mBfIRBuilder->CreateCmpNE(arraySize, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0)), clearBlock, contBlock);
  7267. mBfIRBuilder->AddBlock(clearBlock);
  7268. mBfIRBuilder->SetInsertPoint(clearBlock);
  7269. }
  7270. AddStackAlloc(typedVal, arraySize, NULL, scopeData, false, true);
  7271. if (!isConstSize)
  7272. {
  7273. mBfIRBuilder->CreateBr(contBlock);
  7274. mBfIRBuilder->AddBlock(contBlock);
  7275. mBfIRBuilder->SetInsertPoint(contBlock);
  7276. }
  7277. }
  7278. //InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  7279. return result;
  7280. }
  7281. }
  7282. else
  7283. {
  7284. if ((!isDynAlloc) && (!arraySize.IsConst()) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  7285. {
  7286. // Generate and check new size
  7287. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  7288. auto firstElementField = &arrayType->mFieldInstances.back();
  7289. int arrayClassSize = firstElementField->mDataOffset;
  7290. sizeValue = GetConstValue(arrayClassSize);
  7291. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  7292. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  7293. auto loadedPtr = _CreateDynAlloc(sizeValue, arrayType->mAlign);
  7294. auto typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->MapType(arrayType)), arrayType);
  7295. if (!noDtorCall)
  7296. AddStackAlloc(typedVal, arraySize, NULL, scopeData, false, true);
  7297. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  7298. return typedVal.mValue;
  7299. }
  7300. else
  7301. {
  7302. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  7303. auto firstElementField = &arrayType->mFieldInstances.back();
  7304. if (!type->IsValuelessType())
  7305. {
  7306. int arrayClassSize = firstElementField->mDataOffset;
  7307. sizeValue = GetConstValue(arrayClassSize);
  7308. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  7309. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  7310. }
  7311. else
  7312. sizeValue = GetConstValue(arrayType->mInstSize);
  7313. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  7314. isDynAlloc = (isDynAlloc) || (!sizeValue.IsConst());
  7315. if (!isDynAlloc)
  7316. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  7317. else
  7318. {
  7319. MarkDynStack(scopeData);
  7320. SaveStackState(scopeData);
  7321. }
  7322. BfType* byteType = GetPrimitiveType(BfTypeCode_Int8);
  7323. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  7324. if (!isDynAlloc)
  7325. mBfIRBuilder->ClearDebugLocation(allocaInst);
  7326. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  7327. if (!isDynAlloc)
  7328. mBfIRBuilder->SetInsertPoint(prevBlock);
  7329. auto typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(arrayType)), arrayType);
  7330. mBfIRBuilder->ClearDebugLocation_Last();
  7331. if (!noDtorCall)
  7332. AddStackAlloc(typedVal, arraySize, NULL, scopeData, false, true);
  7333. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  7334. return typedVal.mValue;
  7335. }
  7336. }
  7337. }
  7338. else if (appendSizeValue)
  7339. {
  7340. // It may seem that we should check IsLooped against only the requested scope, BUT- if later on we perform
  7341. // a scoped alloc that crosses our boundary then we won't be able to reclaim the stack space, so we always
  7342. // use the "dynSize" version conservatively
  7343. if ((!isDynAlloc) && (!appendSizeValue.IsConst()) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  7344. {
  7345. // Generate and check new size
  7346. sizeValue = GetConstValue(typeInstance->mInstSize);
  7347. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  7348. auto loadedPtr = _CreateDynAlloc(sizeValue, typeInstance->mAlign);
  7349. auto typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->MapTypeInstPtr(typeInstance)), typeInstance);
  7350. if (!noDtorCall)
  7351. AddStackAlloc(typedVal, arraySize, NULL, scopeData, mCurMethodState->mInConditionalBlock, true);
  7352. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  7353. return typedVal.mValue;
  7354. }
  7355. else // stack alloc, unlooped, with append
  7356. {
  7357. sizeValue = GetConstValue(typeInstance->mInstSize);
  7358. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  7359. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  7360. bool wasDynAlloc = isDynAlloc;
  7361. isDynAlloc = (isDynAlloc) || (!sizeValue.IsConst());
  7362. if (!isDynAlloc)
  7363. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  7364. else
  7365. {
  7366. MarkDynStack(scopeData);
  7367. SaveStackState(scopeData);
  7368. }
  7369. auto sbyteType = GetPrimitiveType(BfTypeCode_Int8);
  7370. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(sbyteType), sizeValue);
  7371. if (!isDynAlloc)
  7372. {
  7373. mBfIRBuilder->ClearDebugLocation(allocaInst);
  7374. }
  7375. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  7376. bool mayBeLarge = false;
  7377. if (sizeValue.IsConst())
  7378. {
  7379. auto constantInt = mBfIRBuilder->GetConstant(sizeValue);
  7380. if (constantInt->mInt64 >= 4096)
  7381. mayBeLarge = true;
  7382. }
  7383. else
  7384. mayBeLarge = true;
  7385. if (((type->IsObject() && (!mayBeLarge))) ||
  7386. // If we create a memset that can fill in backwards (or at least 4k chunked backward) then we can remove the '!mayBeLarge' cond
  7387. ((zeroMemory) && (!mayBeLarge)))
  7388. {
  7389. mBfIRBuilder->SetAllocaNoChkStkHint(allocaInst);
  7390. }
  7391. BfIRValue castedVal;
  7392. if (!isDynAlloc)
  7393. {
  7394. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  7395. castedVal = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapTypeInstPtr(typeInstance));
  7396. mBfIRBuilder->ClearDebugLocation(castedVal);
  7397. mBfIRBuilder->SetInsertPoint(prevBlock);
  7398. if (WantsLifetimes())
  7399. {
  7400. mBfIRBuilder->CreateLifetimeStart(allocaInst);
  7401. scopeData->mDeferredLifetimeEnds.push_back(allocaInst);
  7402. }
  7403. }
  7404. else
  7405. {
  7406. castedVal = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapTypeInstPtr(typeInstance));
  7407. }
  7408. auto typedVal = BfTypedValue(castedVal, typeInstance);
  7409. if (!noDtorCall)
  7410. {
  7411. bool doCondAlloca = false;
  7412. if (!IsTargetingBeefBackend())
  7413. doCondAlloca = !wasDynAlloc && isDynAlloc && mCurMethodState->mInConditionalBlock;
  7414. AddStackAlloc(typedVal, arraySize, NULL, scopeData, doCondAlloca, true);
  7415. }
  7416. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  7417. return typedVal.mValue;
  7418. }
  7419. }
  7420. else // "Normal" stack alloc
  7421. {
  7422. BF_ASSERT(!sizeValue);
  7423. //TODO: If sizeValue is a constant then do this in the head IR builder
  7424. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  7425. if (!isLoopedAlloc)
  7426. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  7427. else
  7428. {
  7429. MarkDynStack(scopeData);
  7430. SaveStackState(scopeData);
  7431. }
  7432. auto allocaInst = mBfIRBuilder->CreateAlloca(allocType);
  7433. if (!isLoopedAlloc)
  7434. mBfIRBuilder->ClearDebugLocation(allocaInst);
  7435. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  7436. bool mayBeLarge = allocSize >= 4096;
  7437. if (((typeInstance != NULL) && (typeInstance->IsObject()) && (!mayBeLarge)) ||
  7438. // If we create a memset that can fill in backwards (or at least 4k chunked backward) then we can remove the '!mayBeLarge' cond
  7439. ((zeroMemory) && (!mayBeLarge)))
  7440. {
  7441. // With an object, we know we will at least set the vdata pointer which will probe the start of the new address,
  7442. // and memset is always safe
  7443. mBfIRBuilder->SetAllocaNoChkStkHint(allocaInst);
  7444. }
  7445. auto typedVal = BfTypedValue(allocaInst, type);
  7446. if (!isLoopedAlloc)
  7447. {
  7448. mBfIRBuilder->ClearDebugLocation(allocaInst);
  7449. mBfIRBuilder->SetInsertPoint(prevBlock);
  7450. if (WantsLifetimes())
  7451. {
  7452. mBfIRBuilder->CreateLifetimeStart(allocaInst);
  7453. scopeData->mDeferredLifetimeEnds.push_back(allocaInst);
  7454. }
  7455. }
  7456. if (!noDtorCall)
  7457. AddStackAlloc(typedVal, BfIRValue(), NULL, scopeData, false, true);
  7458. if (typeInstance != NULL)
  7459. {
  7460. InitTypeInst(typedVal, scopeData, zeroMemory, GetConstValue(typeInstance->mInstSize));
  7461. }
  7462. else
  7463. {
  7464. mBfIRBuilder->CreateMemSet(allocaInst, GetConstValue8(0), GetConstValue(allocSize), allocAlign);
  7465. }
  7466. return allocaInst;
  7467. }
  7468. }
  7469. else if (arraySize)
  7470. {
  7471. if (isRawArrayAlloc)
  7472. {
  7473. sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  7474. return AllocBytes(allocTarget.mRefNode, allocTarget, type, sizeValue, GetConstValue(allocAlign), allocFlags);
  7475. }
  7476. else
  7477. {
  7478. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  7479. typeInstance = arrayType;
  7480. BfIRValue arraySizeMinusOne = mBfIRBuilder->CreateSub(arraySize, GetConstValue(1));
  7481. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySizeMinusOne);
  7482. appendSizeValue = elementDataSize;
  7483. if (!type->IsSizeAligned())
  7484. {
  7485. appendSizeValue = mBfIRBuilder->CreateAdd(appendSizeValue, GetConstValue(type->GetStride() - type->mSize));
  7486. }
  7487. }
  7488. }
  7489. if ((typeInstance != NULL) && (typeInstance->IsObject()))
  7490. {
  7491. auto vDataRef = GetClassVDataPtr(typeInstance);
  7492. BfIRValue result;
  7493. bool isResultInitialized = false;
  7494. int stackCount = mCompiler->mOptions.mAllocStackCount;
  7495. if (typeInstance->mTypeOptionsIdx != -1)
  7496. {
  7497. auto typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  7498. stackCount = BfTypeOptions::Apply(stackCount, typeOptions->mAllocStackTraceDepth);
  7499. }
  7500. if (!sizeValue)
  7501. sizeValue = GetConstValue(typeInstance->mInstSize);
  7502. if (appendSizeValue)
  7503. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  7504. BfIRValue origSizeValue = sizeValue;
  7505. bool isAllocEx = hasCustomAllocator && (stackCount > 1);
  7506. if (isAllocEx)
  7507. {
  7508. auto prepareStackTraceMethod = GetInternalMethod("Dbg_PrepareStackTrace");
  7509. if (prepareStackTraceMethod)
  7510. {
  7511. SizedArray<BfIRValue, 2> irArgs;
  7512. irArgs.Add(sizeValue);
  7513. irArgs.Add(GetConstValue(stackCount));
  7514. auto addlBytes = mBfIRBuilder->CreateCall(prepareStackTraceMethod.mFunc, irArgs);
  7515. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, addlBytes);
  7516. }
  7517. }
  7518. if (allocTarget.mCustomAllocator)
  7519. {
  7520. auto customAlloc = allocTarget.mCustomAllocator.mType->ToTypeInstance();
  7521. // Use AllocObject if we have it, otherwise we just use AllocBytes further down
  7522. if ((customAlloc != NULL) && (GetRawMethodByName(customAlloc, "AllocObject", -1, true, true) != NULL))
  7523. {
  7524. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  7525. mBfIRBuilder->PopulateType(classVDataType);
  7526. auto typeInstType = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef)->ToTypeInstance();
  7527. mBfIRBuilder->PopulateType(typeInstType);
  7528. auto typePtrPtr = mBfIRBuilder->CreateInBoundsGEP(vDataRef, 0, 1); // mType
  7529. auto typePtr = mBfIRBuilder->CreateLoad(typePtrPtr);
  7530. auto typeInstPtr = mBfIRBuilder->CreateBitCast(typePtr, mBfIRBuilder->MapTypeInstPtr(typeInstType));
  7531. BfTypedValueExpression typedValueExpr;
  7532. typedValueExpr.Init(BfTypedValue(typeInstPtr, typeInstType));
  7533. typedValueExpr.mRefNode = allocTarget.mRefNode;
  7534. BfExprEvaluator exprEvaluator(this);
  7535. SizedArray<BfExpression*, 2> argExprs;
  7536. argExprs.push_back(&typedValueExpr);
  7537. BfTypedValueExpression sizeValueExpr;
  7538. sizeValueExpr.Init(BfTypedValue(sizeValue, GetPrimitiveType(BfTypeCode_IntPtr)));
  7539. sizeValueExpr.mRefNode = allocTarget.mRefNode;
  7540. argExprs.push_back(&sizeValueExpr);
  7541. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  7542. BfResolvedArgs argValues(&sizedArgExprs);
  7543. exprEvaluator.ResolveArgValues(argValues);
  7544. exprEvaluator.mNoBind = true;
  7545. BfTypedValue allocResult = exprEvaluator.MatchMethod(allocTarget.mRefNode, NULL, allocTarget.mCustomAllocator, false, false, "AllocObject", argValues, NULL);
  7546. if (allocResult)
  7547. {
  7548. if ((allocResult.mType->IsVoidPtr()) || (allocResult.mType == mContext->mBfObjectType))
  7549. result = mBfIRBuilder->CreateBitCast(allocResult.mValue, mBfIRBuilder->MapType(typeInstance));
  7550. else
  7551. result = CastToValue(allocTarget.mRefNode, allocResult, typeInstance, BfCastFlags_Explicit);
  7552. isResultInitialized = true;
  7553. }
  7554. }
  7555. }
  7556. bool wasAllocated = false;
  7557. if (!result)
  7558. {
  7559. if (hasCustomAllocator)
  7560. result = AllocBytes(allocTarget.mRefNode, allocTarget, typeInstance, sizeValue, GetConstValue(typeInstance->mInstAlign), (BfAllocFlags)(BfAllocFlags_ZeroMemory | BfAllocFlags_NoDefaultToMalloc));
  7561. else if ((mCompiler->mOptions.mObjectHasDebugFlags) && (!mCompiler->mOptions.mDebugAlloc))
  7562. {
  7563. SizedArray<BfIRValue, 4> llvmArgs;
  7564. llvmArgs.push_back(sizeValue);
  7565. auto irFunc = GetBuiltInFunc(BfBuiltInFuncType_Malloc);
  7566. result = mBfIRBuilder->CreateCall(irFunc, llvmArgs);
  7567. result = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapTypeInstPtr(typeInstance));
  7568. wasAllocated = true;
  7569. }
  7570. }
  7571. if (result)
  7572. {
  7573. if (mCompiler->mOptions.mObjectHasDebugFlags)
  7574. {
  7575. auto objectPtr = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapTypeInstPtr(mContext->mBfObjectType));
  7576. SizedArray<BfIRValue, 4> llvmArgs;
  7577. llvmArgs.push_back(objectPtr);
  7578. llvmArgs.push_back(origSizeValue);
  7579. llvmArgs.push_back(vDataRef);
  7580. auto objectCreatedMethod = GetInternalMethod(isAllocEx ?
  7581. (isResultInitialized ? "Dbg_ObjectCreatedEx" : "Dbg_ObjectAllocatedEx") :
  7582. (isResultInitialized ? "Dbg_ObjectCreated" : "Dbg_ObjectAllocated"));
  7583. mBfIRBuilder->CreateCall(objectCreatedMethod.mFunc, llvmArgs);
  7584. if (wasAllocated)
  7585. {
  7586. auto byteType = GetPrimitiveType(BfTypeCode_UInt8);
  7587. auto bytePtrType = CreatePointerType(byteType);
  7588. auto flagsPtr = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapType(bytePtrType));
  7589. auto flagsVal = mBfIRBuilder->CreateLoad(flagsPtr);
  7590. auto modifiedFlagsVal = mBfIRBuilder->CreateOr(flagsVal, mBfIRBuilder->CreateConst(BfTypeCode_UInt8, /*BF_OBJECTFLAG_ALLOCATED*/4));
  7591. mBfIRBuilder->CreateStore(modifiedFlagsVal, flagsPtr);
  7592. }
  7593. }
  7594. else
  7595. {
  7596. auto ptrType = mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr);
  7597. auto vDataPtr = mBfIRBuilder->CreateBitCast(vDataRef, ptrType);
  7598. auto vDataMemberPtr = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->GetPointerTo(ptrType));
  7599. mBfIRBuilder->CreateStore(vDataPtr, vDataMemberPtr);
  7600. }
  7601. }
  7602. else
  7603. {
  7604. if ((mBfIRBuilder->mIgnoreWrites) || (mCompiler->mIsResolveOnly))
  7605. return GetDefaultValue(typeInstance);
  7606. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  7607. auto vData = mBfIRBuilder->CreateBitCast(vDataRef, mBfIRBuilder->MapTypeInstPtr(classVDataType->ToTypeInstance()));
  7608. if (mCompiler->mOptions.mObjectHasDebugFlags)
  7609. {
  7610. SizedArray<BfIRValue, 4> llvmArgs;
  7611. llvmArgs.push_back(vData);
  7612. llvmArgs.push_back(sizeValue);
  7613. llvmArgs.push_back(GetConstValue(typeInstance->mAlign));
  7614. llvmArgs.push_back(GetConstValue(stackCount));
  7615. auto moduleMethodInstance = GetInternalMethod("Dbg_ObjectAlloc", 4);
  7616. BfIRValue objectVal = mBfIRBuilder->CreateCall(moduleMethodInstance.mFunc, llvmArgs);
  7617. result = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(typeInstance));
  7618. }
  7619. else
  7620. {
  7621. SizedArray<BfIRValue, 4> llvmArgs;
  7622. llvmArgs.push_back(sizeValue);
  7623. BfIRFunction irFunc;
  7624. if (mCompiler->mOptions.mDebugAlloc)
  7625. {
  7626. auto moduleMethodInstance = GetInternalMethod("Dbg_RawObjectAlloc", 1);
  7627. irFunc = moduleMethodInstance.mFunc;
  7628. }
  7629. if (!irFunc)
  7630. irFunc = GetBuiltInFunc(BfBuiltInFuncType_Malloc);
  7631. BfIRValue objectVal = mBfIRBuilder->CreateCall(irFunc, llvmArgs);
  7632. auto objResult = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(mContext->mBfObjectType, BfIRPopulateType_Full));
  7633. auto vdataPtr = mBfIRBuilder->CreateInBoundsGEP(objResult, 0, 0);
  7634. mBfIRBuilder->CreateStore(vData, vdataPtr);
  7635. result = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(typeInstance));
  7636. }
  7637. }
  7638. if ((zeroMemory) && (arraySize))
  7639. {
  7640. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  7641. typeInstance = arrayType;
  7642. auto firstElementField = &arrayType->mFieldInstances.back();
  7643. int arrayClassSize = firstElementField->mDataOffset;
  7644. BfIRValue elementDataSize;
  7645. bool skipZero = false;
  7646. if (arraySize.IsConst())
  7647. {
  7648. BfIRValue arraySizeMinusOne = mBfIRBuilder->CreateSub(arraySize, GetConstValue(1));
  7649. elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySizeMinusOne);
  7650. elementDataSize = mBfIRBuilder->CreateAdd(elementDataSize, GetConstValue(type->mSize));
  7651. auto constVal = mBfIRBuilder->GetConstant(elementDataSize);
  7652. if (constVal->mInt64 <= 0)
  7653. skipZero = true;
  7654. }
  7655. else
  7656. {
  7657. // For non const, don't use an unpadded last element - saves us checking against negative numbers going into memset for the zero-length case
  7658. elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  7659. }
  7660. if (!skipZero)
  7661. {
  7662. auto i8Type = GetPrimitiveType(BfTypeCode_Int8);
  7663. auto ptrType = CreatePointerType(i8Type);
  7664. auto ptrVal = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapType(ptrType));
  7665. ptrVal = mBfIRBuilder->CreateInBoundsGEP(ptrVal, arrayClassSize);
  7666. mBfIRBuilder->CreateMemSet(ptrVal, GetConstValue8(0), elementDataSize, type->mAlign);
  7667. appendSizeValue = elementDataSize;
  7668. }
  7669. }
  7670. return result;
  7671. }
  7672. else
  7673. {
  7674. if (!sizeValue)
  7675. sizeValue = GetConstValue(allocSize);
  7676. return AllocBytes(allocTarget.mRefNode, allocTarget, type, sizeValue, GetConstValue(allocAlign), zeroMemory ? BfAllocFlags_ZeroMemory : BfAllocFlags_None);
  7677. }
  7678. }
  7679. void BfModule::ValidateAllocation(BfType* type, BfAstNode* refNode)
  7680. {
  7681. if ((type == NULL) || (refNode == NULL))
  7682. return;
  7683. auto typeInstance = type->ToTypeInstance();
  7684. if ((typeInstance != NULL) && (typeInstance->mTypeDef->mIsOpaque))
  7685. Fail(StrFormat("Unable to allocate opaque type '%s'", TypeToString(type).c_str()), refNode);
  7686. }
  7687. void BfModule::EmitAlign(BfIRValue& appendCurIdx, int align)
  7688. {
  7689. appendCurIdx = mBfIRBuilder->CreateAdd(appendCurIdx, GetConstValue(align - 1));
  7690. appendCurIdx = mBfIRBuilder->CreateAnd(appendCurIdx, GetConstValue(~(align - 1)));
  7691. }
  7692. void BfModule::EmitAppendAlign(int align, int sizeMultiple)
  7693. {
  7694. if (sizeMultiple == 0)
  7695. sizeMultiple = align;
  7696. if ((mCurMethodState->mCurAppendAlign != 0) && (mCurMethodState->mCurAppendAlign % align != 0))
  7697. {
  7698. if (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Ctor)
  7699. {
  7700. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  7701. BF_ASSERT(localVar->mName == "appendIdx");
  7702. auto appendIdxVal = BfTypedValue(localVar->mValue, localVar->mResolvedType, true);
  7703. BfIRValue appendCurIdx = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  7704. if (align > 1)
  7705. {
  7706. appendCurIdx = mBfIRBuilder->CreateAdd(appendCurIdx, GetConstValue(align - 1));
  7707. appendCurIdx = mBfIRBuilder->CreateAnd(appendCurIdx, GetConstValue(~(align - 1)));
  7708. }
  7709. mBfIRBuilder->CreateStore(appendCurIdx, appendIdxVal.mValue);
  7710. }
  7711. else
  7712. {
  7713. BF_ASSERT(mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend);
  7714. BfIRValue appendCurIdxPtr = mCurMethodState->mRetVal.mValue;
  7715. BfIRValue appendCurIdx = mBfIRBuilder->CreateLoad(appendCurIdxPtr);
  7716. appendCurIdx = mBfIRBuilder->CreateAdd(appendCurIdx, GetConstValue(align - 1));
  7717. appendCurIdx = mBfIRBuilder->CreateAnd(appendCurIdx, GetConstValue(~(align - 1)));
  7718. mBfIRBuilder->CreateStore(appendCurIdx, appendCurIdxPtr);
  7719. }
  7720. }
  7721. if (mCurMethodState->mCurAppendAlign == 0)
  7722. mCurMethodState->mCurAppendAlign = sizeMultiple;
  7723. else
  7724. {
  7725. if (sizeMultiple % align == 0)
  7726. mCurMethodState->mCurAppendAlign = align;
  7727. else
  7728. mCurMethodState->mCurAppendAlign = sizeMultiple % align;
  7729. }
  7730. }
  7731. BfIRValue BfModule::AppendAllocFromType(BfType* type, BfIRValue appendSizeValue, int appendAllocAlign, BfIRValue arraySize, int arrayDim, bool isRawArrayAlloc, bool zeroMemory)
  7732. {
  7733. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  7734. BF_ASSERT(localVar->mName == "appendIdx");
  7735. BfTypedValue appendIdxVal(localVar->mValue, localVar->mResolvedType, true);
  7736. BfIRValue retValue;
  7737. BfTypeInstance* retTypeInstance = NULL;
  7738. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  7739. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  7740. if (arraySize)
  7741. {
  7742. if (isRawArrayAlloc)
  7743. {
  7744. EmitAppendAlign(type->mAlign);
  7745. BfPointerType* ptrType = CreatePointerType(type);
  7746. BfIRValue sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->mSize), arraySize);
  7747. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  7748. if (mSystem->mPtrSize != 4)
  7749. sizeValue = mBfIRBuilder->CreateNumericCast(sizeValue, true, (intPtrType->mSize == 4) ? BfTypeCode_Int32 : BfTypeCode_Int64);
  7750. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  7751. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  7752. if (zeroMemory)
  7753. {
  7754. auto ptr = mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(voidPtrType));
  7755. mBfIRBuilder->CreateMemSet(ptr, GetConstValue8(0), sizeValue, type->mAlign);
  7756. }
  7757. return mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(ptrType));
  7758. }
  7759. else
  7760. {
  7761. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  7762. EmitAppendAlign(arrayType->mAlign, type->mSize);
  7763. auto firstElementField = &arrayType->mFieldInstances.back();
  7764. int arrayClassSize = arrayType->mInstSize - firstElementField->mDataSize;
  7765. BfIRValue sizeValue = GetConstValue(arrayClassSize);
  7766. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->mSize), arraySize);
  7767. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  7768. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  7769. if (mSystem->mPtrSize != 4)
  7770. sizeValue = mBfIRBuilder->CreateNumericCast(sizeValue, true, (intPtrType->mSize == 4) ? BfTypeCode_Int32 : BfTypeCode_Int64);
  7771. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  7772. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  7773. if (zeroMemory)
  7774. {
  7775. // Only zero out the actual elements
  7776. int dataOffset = arrayType->mFieldInstances.back().mDataOffset;
  7777. auto newOffset = mBfIRBuilder->CreateAdd(curIdxVal, GetConstValue(dataOffset));
  7778. auto newSize = mBfIRBuilder->CreateSub(sizeValue, GetConstValue(dataOffset));
  7779. auto ptr = mBfIRBuilder->CreateIntToPtr(newOffset, mBfIRBuilder->MapType(voidPtrType));
  7780. mBfIRBuilder->CreateMemSet(ptr, GetConstValue8(0), newSize, type->mAlign);
  7781. }
  7782. retTypeInstance = arrayType;
  7783. retValue = mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(arrayType));
  7784. }
  7785. }
  7786. else
  7787. {
  7788. auto typeInst = type->ToTypeInstance();
  7789. BfIRValue sizeValue;
  7790. BfIRType toType;
  7791. if (typeInst != NULL)
  7792. {
  7793. EmitAppendAlign(typeInst->mInstAlign, typeInst->mInstSize);
  7794. sizeValue = GetConstValue(typeInst->mInstSize);
  7795. toType = mBfIRBuilder->MapTypeInstPtr(typeInst);
  7796. }
  7797. else
  7798. {
  7799. EmitAppendAlign(type->mAlign, type->mSize);
  7800. sizeValue = GetConstValue(type->mSize);
  7801. auto toPtrType = CreatePointerType(type);
  7802. toType = mBfIRBuilder->MapType(toPtrType);
  7803. }
  7804. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  7805. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  7806. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  7807. retTypeInstance = typeInst;
  7808. retValue = mBfIRBuilder->CreateIntToPtr(curIdxVal, toType);
  7809. }
  7810. if ((retTypeInstance != NULL) && (retTypeInstance->IsObject()))
  7811. {
  7812. mBfIRBuilder->PopulateType(retTypeInstance);
  7813. auto int8Type = mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8);
  7814. auto ptrType = mBfIRBuilder->GetPointerTo(int8Type);
  7815. auto ptrPtrType = mBfIRBuilder->GetPointerTo(ptrType);
  7816. auto curThis = GetThis();
  7817. BfIRValue newFlags;
  7818. if (mCompiler->mOptions.mObjectHasDebugFlags)
  7819. {
  7820. auto thisFlagsPtr = mBfIRBuilder->CreateBitCast(curThis.mValue, ptrType);
  7821. auto thisFlags = mBfIRBuilder->CreateLoad(thisFlagsPtr);
  7822. auto maskedThisFlags = mBfIRBuilder->CreateAnd(thisFlags, GetConstValue8(BfObjectFlag_StackAlloc)); // Take 'stack' flag from 'this'
  7823. newFlags = mBfIRBuilder->CreateOr(maskedThisFlags, GetConstValue8(BfObjectFlag_AppendAlloc));
  7824. }
  7825. auto vObjectAddr = mBfIRBuilder->CreateInBoundsGEP(retValue, 0, 0);
  7826. auto vDataRef = CreateClassVDataGlobal(retTypeInstance);
  7827. auto destAddr = mBfIRBuilder->CreateBitCast(vObjectAddr, ptrPtrType);
  7828. auto srcVal = mBfIRBuilder->CreateBitCast(vDataRef, ptrType);
  7829. mBfIRBuilder->CreateStore(srcVal, destAddr);
  7830. if (mCompiler->mOptions.mObjectHasDebugFlags)
  7831. {
  7832. auto flagsPtr = mBfIRBuilder->CreateBitCast(destAddr, ptrType);
  7833. mBfIRBuilder->CreateStore(newFlags, flagsPtr);
  7834. }
  7835. }
  7836. if (appendSizeValue)
  7837. {
  7838. EmitAppendAlign(appendAllocAlign);
  7839. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  7840. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, appendSizeValue);
  7841. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  7842. }
  7843. return retValue;
  7844. }
  7845. bool BfModule::IsOptimized()
  7846. {
  7847. if (mProject == NULL)
  7848. return false;
  7849. int optLevel = GetModuleOptions().mOptLevel;
  7850. return (optLevel >= BfOptLevel_O1) && (optLevel <= BfOptLevel_O3);
  7851. }
  7852. bool BfModule::IsTargetingBeefBackend()
  7853. {
  7854. if (mProject == NULL)
  7855. return false;
  7856. return GetModuleOptions().mOptLevel == BfOptLevel_OgPlus;
  7857. }
  7858. bool BfModule::WantsLifetimes()
  7859. {
  7860. if (mProject == NULL)
  7861. return false;
  7862. return GetModuleOptions().mOptLevel == BfOptLevel_OgPlus;
  7863. }
  7864. bool BfModule::HasCompiledOutput()
  7865. {
  7866. return (!mSystem->mIsResolveOnly) && (mIsReified);
  7867. }
  7868. // We will skip the object access check for any occurances of this value
  7869. void BfModule::SkipObjectAccessCheck(BfTypedValue typedVal)
  7870. {
  7871. if ((mBfIRBuilder->mIgnoreWrites) || (!typedVal.mType->IsObjectOrInterface()) || (mCurMethodState == NULL) || (mCurMethodState->mIgnoreObjectAccessCheck))
  7872. return;
  7873. if (!mCompiler->mOptions.mObjectHasDebugFlags)
  7874. return;
  7875. if ((typedVal.mValue.mFlags & BfIRValueFlags_Value) == 0)
  7876. return;
  7877. mCurMethodState->mSkipObjectAccessChecks.Add(typedVal.mValue.mId);
  7878. }
  7879. void BfModule::EmitObjectAccessCheck(BfTypedValue typedVal)
  7880. {
  7881. if ((mBfIRBuilder->mIgnoreWrites) || (!typedVal.mType->IsObjectOrInterface()) || (mCurMethodState == NULL) || (mCurMethodState->mIgnoreObjectAccessCheck))
  7882. return;
  7883. if (!mCompiler->mOptions.mObjectHasDebugFlags)
  7884. return;
  7885. bool emitObjectAccessCheck = mCompiler->mOptions.mEmitObjectAccessCheck;
  7886. auto typeOptions = GetTypeOptions();
  7887. if (typeOptions != NULL)
  7888. emitObjectAccessCheck = typeOptions->Apply(emitObjectAccessCheck, BfOptionFlags_EmitObjectAccessCheck);
  7889. if (!emitObjectAccessCheck)
  7890. return;
  7891. if ((typedVal.mValue.mFlags & BfIRValueFlags_Value) != 0)
  7892. {
  7893. if (mCurMethodState->mSkipObjectAccessChecks.Contains(typedVal.mValue.mId))
  7894. return;
  7895. }
  7896. if (typedVal.IsAddr())
  7897. typedVal = LoadValue(typedVal);
  7898. mBfIRBuilder->CreateObjectAccessCheck(typedVal.mValue, !IsOptimized());
  7899. }
  7900. void BfModule::EmitEnsureInstructionAt()
  7901. {
  7902. if (mProject == NULL)
  7903. return;
  7904. if ((mBfIRBuilder->mIgnoreWrites) || (!mHasFullDebugInfo) || (IsOptimized()) || (mCompiler->mOptions.mOmitDebugHelpers))
  7905. return;
  7906. mBfIRBuilder->CreateEnsureInstructionAt();
  7907. }
  7908. void BfModule::EmitDynamicCastCheck(const BfTypedValue& targetValue, BfType* targetType, BfIRBlock trueBlock, BfIRBlock falseBlock, bool nullSucceeds)
  7909. {
  7910. if (mBfIRBuilder->mIgnoreWrites)
  7911. return; // Nothing needed here
  7912. auto irb = mBfIRBuilder;
  7913. auto checkBB = irb->CreateBlock("as.check");
  7914. auto isNull = irb->CreateIsNull(targetValue.mValue);
  7915. mBfIRBuilder->CreateCondBr(isNull, nullSucceeds ? trueBlock : falseBlock, checkBB);
  7916. auto intType = GetPrimitiveType(BfTypeCode_IntPtr);
  7917. auto intPtrType = CreatePointerType(intType);
  7918. auto intPtrPtrType = CreatePointerType(intPtrType);
  7919. auto int32Type = GetPrimitiveType(BfTypeCode_Int32);
  7920. auto int32PtrType = CreatePointerType(int32Type);
  7921. auto typeTypeInstance = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef)->ToTypeInstance();
  7922. if (mCompiler->mOptions.mAllowHotSwapping)
  7923. {
  7924. BfExprEvaluator exprEvaluator(this);
  7925. AddBasicBlock(checkBB);
  7926. auto objectParam = mBfIRBuilder->CreateBitCast(targetValue.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType));
  7927. auto moduleMethodInstance = GetMethodByName(mContext->mBfObjectType, targetType->IsInterface() ? "DynamicCastToInterface" : "DynamicCastToTypeId");
  7928. SizedArray<BfIRValue, 4> irArgs;
  7929. irArgs.push_back(objectParam);
  7930. irArgs.push_back(GetConstValue32(targetType->mTypeId));
  7931. auto callResult = exprEvaluator.CreateCall(moduleMethodInstance.mMethodInstance, moduleMethodInstance.mFunc, false, irArgs);
  7932. auto resultType = ResolveTypeDef(mSystem->mTypeBool);
  7933. auto cmpResult = mBfIRBuilder->CreateCmpNE(callResult.mValue, GetDefaultValue(callResult.mType));
  7934. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  7935. }
  7936. else
  7937. {
  7938. AddBasicBlock(checkBB);
  7939. BfIRValue vDataPtr = irb->CreateBitCast(targetValue.mValue, irb->MapType(intPtrType));
  7940. vDataPtr = irb->CreateLoad(vDataPtr);
  7941. if (mCompiler->mOptions.mObjectHasDebugFlags)
  7942. vDataPtr = irb->CreateAnd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, (uint64)~0xFFULL));
  7943. if (targetType->IsInterface())
  7944. {
  7945. auto targetTypeInst = targetType->ToTypeInstance();
  7946. AddDependency(targetType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  7947. // Skip past mType, but since a 'GetDynCastVDataCount()' data is included in the sSlotOfs, we need to remove that
  7948. //int inheritanceIdOfs = mSystem->mPtrSize - (mCompiler->GetDynCastVDataCount())*4;
  7949. //vDataPtr = irb->CreateAdd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, inheritanceIdOfs));
  7950. vDataPtr = irb->CreateAdd(vDataPtr, irb->GetConfigConst(BfIRConfigConst_DynSlotOfs, BfTypeCode_IntPtr));
  7951. BfIRValue slotOfs = GetInterfaceSlotNum(targetType->ToTypeInstance());
  7952. BfIRValue slotByteOfs = irb->CreateMul(slotOfs, irb->CreateConst(BfTypeCode_Int32, 4));
  7953. slotByteOfs = irb->CreateNumericCast(slotByteOfs, false, BfTypeCode_IntPtr);
  7954. vDataPtr = irb->CreateAdd(vDataPtr, slotByteOfs);
  7955. vDataPtr = irb->CreateIntToPtr(vDataPtr, irb->MapType(int32PtrType));
  7956. BfIRValue typeId = irb->CreateLoad(vDataPtr);
  7957. BfIRValue cmpResult = irb->CreateCmpEQ(typeId, irb->CreateConst(BfTypeCode_Int32, targetType->mTypeId));
  7958. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  7959. }
  7960. else
  7961. {
  7962. if (!targetType->IsTypeInstance())
  7963. targetType = GetWrappedStructType(targetType);
  7964. AddDependency(targetType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  7965. int inheritanceIdOfs = mSystem->mPtrSize;
  7966. vDataPtr = irb->CreateAdd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, inheritanceIdOfs));
  7967. vDataPtr = irb->CreateIntToPtr(vDataPtr, irb->MapType(int32PtrType));
  7968. BfIRValue objInheritanceId = irb->CreateLoad(vDataPtr);
  7969. BfIRValue typeDataRef = CreateTypeDataRef(targetType);
  7970. BfIRValue typeInstDataRef = irb->CreateBitCast(typeDataRef, irb->MapType(typeTypeInstance, BfIRPopulateType_Full));
  7971. auto fieldInst = &typeTypeInstance->mFieldInstances[9];
  7972. BF_ASSERT(fieldInst->GetFieldDef()->mName == "mInheritanceId");
  7973. BfIRValue gepValue = irb->CreateInBoundsGEP(typeInstDataRef, 0, fieldInst->mDataIdx);
  7974. BfIRValue wantInheritanceId = irb->CreateLoad(gepValue);
  7975. fieldInst = &typeTypeInstance->mFieldInstances[10];
  7976. BF_ASSERT(fieldInst->GetFieldDef()->mName == "mInheritanceCount");
  7977. gepValue = irb->CreateInBoundsGEP(typeInstDataRef, 0, fieldInst->mDataIdx);
  7978. BfIRValue inheritanceCount = irb->CreateLoad(gepValue);
  7979. BfIRValue idDiff = irb->CreateSub(objInheritanceId, wantInheritanceId);
  7980. BfIRValue cmpResult = irb->CreateCmpLTE(idDiff, inheritanceCount, false);
  7981. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  7982. }
  7983. }
  7984. }
  7985. void BfModule::EmitDynamicCastCheck(BfTypedValue typedVal, BfType* type, bool allowNull)
  7986. {
  7987. if (mBfIRBuilder->mIgnoreWrites)
  7988. return;
  7989. bool emitDynamicCastCheck = mCompiler->mOptions.mEmitDynamicCastCheck;
  7990. auto typeOptions = GetTypeOptions();
  7991. if (typeOptions != NULL)
  7992. emitDynamicCastCheck = typeOptions->Apply(emitDynamicCastCheck, BfOptionFlags_EmitDynamicCastCheck);
  7993. if (emitDynamicCastCheck)
  7994. {
  7995. int wantTypeId = 0;
  7996. if (!type->IsGenericParam())
  7997. wantTypeId = type->mTypeId;
  7998. BfIRBlock failBlock = mBfIRBuilder->CreateBlock("dynFail");
  7999. BfIRBlock endBlock = mBfIRBuilder->CreateBlock("dynEnd");
  8000. EmitDynamicCastCheck(typedVal, type, endBlock, failBlock, allowNull ? true : false);
  8001. AddBasicBlock(failBlock);
  8002. SizedArray<BfIRValue, 8> llvmArgs;
  8003. auto bitAddr = mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType));
  8004. llvmArgs.push_back(bitAddr);
  8005. llvmArgs.push_back(GetConstValue32(wantTypeId));
  8006. auto objDynCheck = GetInternalMethod("ObjectDynCheckFailed");
  8007. BF_ASSERT(objDynCheck);
  8008. if (objDynCheck)
  8009. {
  8010. auto callInst = mBfIRBuilder->CreateCall(objDynCheck.mFunc, llvmArgs);
  8011. }
  8012. mBfIRBuilder->CreateBr(endBlock);
  8013. AddBasicBlock(endBlock);
  8014. }
  8015. }
  8016. BfTypedValue BfModule::BoxValue(BfAstNode* srcNode, BfTypedValue typedVal, BfType* toType, const BfAllocTarget& allocTarget, bool callDtor)
  8017. {
  8018. if (mBfIRBuilder->mIgnoreWrites)
  8019. {
  8020. if (toType == mContext->mBfObjectType)
  8021. return BfTypedValue(mBfIRBuilder->GetFakeVal(), toType);
  8022. if (toType->IsBoxed())
  8023. {
  8024. BfBoxedType* boxedType = (BfBoxedType*)toType;
  8025. if (boxedType->mElementType->IsGenericParam())
  8026. {
  8027. if (typedVal.mType == boxedType->mElementType)
  8028. return BfTypedValue(mBfIRBuilder->GetFakeVal(), toType);
  8029. else
  8030. return BfTypedValue();
  8031. }
  8032. }
  8033. }
  8034. BP_ZONE("BoxValue");
  8035. BfTypeInstance* fromStructTypeInstance = typedVal.mType->ToTypeInstance();
  8036. if (typedVal.mType->IsNullable())
  8037. {
  8038. typedVal = MakeAddressable(typedVal);
  8039. auto innerType = typedVal.mType->GetUnderlyingType();
  8040. if (!innerType->IsValueType())
  8041. {
  8042. if (!mIgnoreErrors)
  8043. Fail("Only value types can be boxed", srcNode);
  8044. return BfTypedValue();
  8045. }
  8046. auto boxedType = CreateBoxedType(innerType);
  8047. auto resultType = toType;
  8048. if (resultType == NULL)
  8049. resultType = boxedType;
  8050. if (mBfIRBuilder->mIgnoreWrites)
  8051. return BfTypedValue(mBfIRBuilder->GetFakeVal(), resultType);
  8052. auto prevBB = mBfIRBuilder->GetInsertBlock();
  8053. auto boxBB = mBfIRBuilder->CreateBlock("boxedN.notNull");
  8054. auto endBB = mBfIRBuilder->CreateBlock("boxedN.end");
  8055. mBfIRBuilder->PopulateType(typedVal.mType);
  8056. auto hasValueAddr = mBfIRBuilder->CreateInBoundsGEP(typedVal.mValue, 0, innerType->IsValuelessType() ? 1 : 2); // has_value
  8057. auto hasValue = mBfIRBuilder->CreateLoad(hasValueAddr);
  8058. mBfIRBuilder->CreateCondBr(hasValue, boxBB, endBB);
  8059. AddDependency(boxedType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  8060. mBfIRBuilder->AddBlock(boxBB);
  8061. mBfIRBuilder->SetInsertPoint(boxBB);
  8062. BfScopeData newScope;
  8063. newScope.mOuterIsConditional = true;
  8064. mCurMethodState->AddScope(&newScope);
  8065. NewScopeState();
  8066. BfIRValue nullableValueAddr;
  8067. BfIRValue loadedVal;
  8068. if (innerType->IsValuelessType())
  8069. {
  8070. loadedVal = mBfIRBuilder->GetFakeVal();
  8071. }
  8072. else
  8073. {
  8074. nullableValueAddr = mBfIRBuilder->CreateInBoundsGEP(typedVal.mValue, 0, 1); // value
  8075. loadedVal = mBfIRBuilder->CreateLoad(nullableValueAddr);
  8076. }
  8077. auto boxedVal = BoxValue(srcNode, BfTypedValue(loadedVal, fromStructTypeInstance->GetUnderlyingType()), resultType, allocTarget, callDtor);
  8078. RestoreScopeState();
  8079. if (!boxedVal)
  8080. return BfTypedValue();
  8081. mBfIRBuilder->CreateBr(endBB);
  8082. auto boxBBEnd = mBfIRBuilder->GetInsertBlock();
  8083. mBfIRBuilder->AddBlock(endBB);
  8084. mBfIRBuilder->SetInsertPoint(endBB);
  8085. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapType(resultType), 2);
  8086. mBfIRBuilder->AddPhiIncoming(phi, boxedVal.mValue, boxBBEnd);
  8087. mBfIRBuilder->AddPhiIncoming(phi, GetDefaultValue(resultType), prevBB);
  8088. return BfTypedValue(phi, resultType);
  8089. }
  8090. bool alreadyCheckedCast = false;
  8091. BfTypeInstance* toTypeInstance = NULL;
  8092. if (toType != NULL)
  8093. toTypeInstance = toType->ToTypeInstance();
  8094. bool isStructPtr = typedVal.mType->IsStructPtr();
  8095. if (fromStructTypeInstance == NULL)
  8096. {
  8097. auto primType = (BfPrimitiveType*)typedVal.mType;
  8098. if ((typedVal.mType->IsPointer()) && (toTypeInstance->IsInstanceOf(mCompiler->mIHashableTypeDef)))
  8099. {
  8100. // Can always do IHashable
  8101. alreadyCheckedCast = true;
  8102. }
  8103. if ((!typedVal.mType->IsPointer()) || (toTypeInstance == mContext->mBfObjectType))
  8104. fromStructTypeInstance = GetWrappedStructType(typedVal.mType);
  8105. if (isStructPtr)
  8106. {
  8107. if ((toTypeInstance != NULL) && (fromStructTypeInstance != NULL) && (TypeIsSubTypeOf(fromStructTypeInstance, toTypeInstance)))
  8108. alreadyCheckedCast = true;
  8109. fromStructTypeInstance = typedVal.mType->GetUnderlyingType()->ToTypeInstance();
  8110. }
  8111. if ((fromStructTypeInstance == NULL) && (alreadyCheckedCast))
  8112. fromStructTypeInstance = GetWrappedStructType(typedVal.mType);
  8113. }
  8114. if (fromStructTypeInstance == NULL)
  8115. return BfTypedValue();
  8116. // Need to box it
  8117. bool isBoxedType = (fromStructTypeInstance != NULL) && (toType->IsBoxed());
  8118. if ((toType == NULL) || (toType == mContext->mBfObjectType) || (isBoxedType) || (alreadyCheckedCast) || (TypeIsSubTypeOf(fromStructTypeInstance, toTypeInstance)))
  8119. {
  8120. if (mBfIRBuilder->mIgnoreWrites)
  8121. return BfTypedValue(mBfIRBuilder->GetFakeVal(), (toType != NULL) ? toType : CreateBoxedType(typedVal.mType));
  8122. auto boxedType = CreateBoxedType(typedVal.mType);
  8123. mBfIRBuilder->PopulateType(boxedType);
  8124. AddDependency(boxedType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  8125. auto allocaInst = AllocFromType(boxedType, allocTarget, BfIRValue(), BfIRValue(), 0, callDtor ? BfAllocFlags_None : BfAllocFlags_NoDtorCall);
  8126. BfTypedValue boxedTypedValue(allocaInst, boxedType);
  8127. mBfIRBuilder->SetName(allocaInst, "boxed." + fromStructTypeInstance->mTypeDef->mName->ToString());
  8128. if (boxedType->IsUnspecializedType())
  8129. {
  8130. BF_ASSERT((srcNode == NULL) || (mCurMethodInstance->mIsUnspecialized));
  8131. }
  8132. else
  8133. {
  8134. PopulateType(fromStructTypeInstance);
  8135. if (!fromStructTypeInstance->IsValuelessType())
  8136. {
  8137. typedVal = LoadValue(typedVal);
  8138. auto valPtr = mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 1);
  8139. if ((typedVal.mType != fromStructTypeInstance) && (!isStructPtr))
  8140. {
  8141. auto ptrType = CreatePointerType(typedVal.mType);
  8142. valPtr = mBfIRBuilder->CreateBitCast(valPtr, mBfIRBuilder->MapType(ptrType));
  8143. }
  8144. if (typedVal.IsSplat())
  8145. {
  8146. AggregateSplatIntoAddr(typedVal, valPtr);
  8147. }
  8148. else
  8149. mBfIRBuilder->CreateStore(typedVal.mValue, valPtr);
  8150. }
  8151. }
  8152. if (toType == NULL)
  8153. {
  8154. return BfTypedValue(allocaInst, boxedType);
  8155. }
  8156. else
  8157. {
  8158. auto castedValue = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(toType));
  8159. return BfTypedValue(castedValue, toType);
  8160. }
  8161. }
  8162. return BfTypedValue();
  8163. }
  8164. bool BfModule::GetBasePropertyDef(BfPropertyDef*& propDef, BfTypeInstance*& typeInst)
  8165. {
  8166. BfTypeInstance* checkTypeInst = typeInst;
  8167. while (checkTypeInst != NULL)
  8168. {
  8169. for (auto checkProp : checkTypeInst->mTypeDef->mProperties)
  8170. {
  8171. if (checkProp->mName == propDef->mName)
  8172. {
  8173. auto checkPropDeclaration = BfNodeDynCast<BfPropertyDeclaration>(checkProp->mFieldDeclaration);
  8174. if ((checkPropDeclaration == NULL) || (checkPropDeclaration->mVirtualSpecifier == NULL) || (checkPropDeclaration->mVirtualSpecifier->GetToken() == BfToken_Virtual))
  8175. {
  8176. propDef = checkProp;
  8177. typeInst = checkTypeInst;
  8178. return true;
  8179. }
  8180. }
  8181. }
  8182. checkTypeInst = checkTypeInst->mBaseType;
  8183. }
  8184. return false;
  8185. }
  8186. BfMethodInstance* BfModule::GetRawMethodInstanceAtIdx(BfTypeInstance* typeInstance, int methodIdx, const char* assertName)
  8187. {
  8188. if (!typeInstance->mResolvingVarField)
  8189. {
  8190. if (typeInstance->IsIncomplete())
  8191. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  8192. }
  8193. else
  8194. {
  8195. if (methodIdx >= (int)typeInstance->mMethodInstanceGroups.size())
  8196. {
  8197. AssertErrorState();
  8198. return NULL;
  8199. }
  8200. }
  8201. if (assertName != NULL)
  8202. {
  8203. BF_ASSERT(typeInstance->mTypeDef->mMethods[methodIdx]->mName == assertName);
  8204. }
  8205. auto& methodGroup = typeInstance->mMethodInstanceGroups[methodIdx];
  8206. if (methodGroup.mDefault == NULL)
  8207. {
  8208. if (!mCompiler->mIsResolveOnly)
  8209. {
  8210. // Get it from the owning module so we don't create a reference prematurely...
  8211. auto declModule = typeInstance->mModule;
  8212. if ((typeInstance->mGenericTypeInfo != NULL) && (typeInstance->mGenericTypeInfo->mFinishedGenericParams) && (methodGroup.mOnDemandKind == BfMethodOnDemandKind_NotSet))
  8213. {
  8214. methodGroup.mOnDemandKind = BfMethodOnDemandKind_NoDecl_AwaitingReference;
  8215. declModule->mOnDemandMethodCount++;
  8216. }
  8217. BF_ASSERT((methodGroup.mOnDemandKind == BfMethodOnDemandKind_AlwaysInclude) || (methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) || (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl) || (typeInstance->mTypeFailed));
  8218. if ((methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) || (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl))
  8219. methodGroup.mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingDecl;
  8220. return declModule->GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector(), (BfGetMethodInstanceFlags)(BfGetMethodInstanceFlag_UnspecializedPass | BfGetMethodInstanceFlag_Unreified)).mMethodInstance;
  8221. }
  8222. else
  8223. {
  8224. auto declModule = typeInstance->mModule;
  8225. return declModule->GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector(), (BfGetMethodInstanceFlags)(BfGetMethodInstanceFlag_UnspecializedPass)).mMethodInstance;
  8226. }
  8227. }
  8228. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  8229. //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
  8230. // be from a call to the NON-raw version
  8231. // if (!methodInstance->mMethodInstanceGroup->IsImplemented())
  8232. // {
  8233. // methodInstance->mIsReified = mIsReified;
  8234. // if (methodInstance->mMethodProcessRequest == NULL)
  8235. // typeInstance->mModule->AddMethodToWorkList(methodInstance);
  8236. // }
  8237. return methodInstance;
  8238. }
  8239. BfMethodInstance* BfModule::GetRawMethodInstance(BfTypeInstance* typeInstance, BfMethodDef* methodDef)
  8240. {
  8241. if (methodDef->mIsLocalMethod)
  8242. {
  8243. return GetMethodInstance(typeInstance, methodDef, BfTypeVector()).mMethodInstance;
  8244. }
  8245. return GetRawMethodInstanceAtIdx(typeInstance, methodDef->mIdx);
  8246. }
  8247. BfMethodInstance* BfModule::GetRawMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase, bool allowMixin)
  8248. {
  8249. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  8250. while (typeInstance != NULL)
  8251. {
  8252. typeInstance->mTypeDef->PopulateMemberSets();
  8253. BfMemberSetEntry* entry = NULL;
  8254. BfMethodDef* methodDef = NULL;
  8255. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  8256. methodDef = (BfMethodDef*)entry->mMemberDef;
  8257. while (methodDef != NULL)
  8258. {
  8259. if (((allowMixin) || (methodDef->mMethodType != BfMethodType_Mixin)) &&
  8260. (methodDef->mGenericParams.size() == 0) &&
  8261. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  8262. return GetRawMethodInstance(typeInstance, methodDef);
  8263. methodDef = methodDef->mNextWithSameName;
  8264. }
  8265. if (!checkBase)
  8266. break;
  8267. typeInstance = typeInstance->mBaseType;
  8268. }
  8269. return NULL;
  8270. }
  8271. BfMethodInstance* BfModule::GetUnspecializedMethodInstance(BfMethodInstance* methodInstance, bool useUnspecializedType)
  8272. {
  8273. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mMethodGenericArguments.size() != 0))
  8274. methodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  8275. auto owner = methodInstance->mMethodInstanceGroup->mOwner;
  8276. if (!useUnspecializedType)
  8277. return methodInstance;
  8278. if (!owner->IsGenericTypeInstance())
  8279. return methodInstance;
  8280. BF_ASSERT(!owner->IsDelegateFromTypeRef());
  8281. BF_ASSERT(!owner->IsTuple());
  8282. auto genericType = (BfTypeInstance*)owner;
  8283. if (genericType->IsUnspecializedType())
  8284. return methodInstance;
  8285. auto unspecializedType = ResolveTypeDef(genericType->mTypeDef);
  8286. if (unspecializedType == NULL)
  8287. {
  8288. AssertErrorState();
  8289. return methodInstance;
  8290. }
  8291. if (unspecializedType == NULL)
  8292. return methodInstance;
  8293. auto unspecializedTypeInst = unspecializedType->ToTypeInstance();
  8294. return GetRawMethodInstanceAtIdx(unspecializedTypeInst, methodInstance->mMethodDef->mIdx);
  8295. }
  8296. int BfModule::GetGenericParamAndReturnCount(BfMethodInstance* methodInstance)
  8297. {
  8298. int genericCount = 0;
  8299. auto unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance);
  8300. for (int paramIdx = 0; paramIdx < unspecializedMethodInstance->GetParamCount(); paramIdx++)
  8301. {
  8302. auto param = unspecializedMethodInstance->GetParamType(paramIdx);
  8303. if (param->IsGenericParam())
  8304. genericCount++;
  8305. }
  8306. if (unspecializedMethodInstance->mReturnType->IsGenericParam())
  8307. genericCount++;
  8308. return genericCount;
  8309. }
  8310. BfModule* BfModule::GetSpecializedMethodModule(const SizedArrayImpl<BfProject*>& projectList)
  8311. {
  8312. BF_ASSERT(!mIsScratchModule);
  8313. BF_ASSERT(mIsReified);
  8314. BfModule* mainModule = this;
  8315. if (mParentModule != NULL)
  8316. mainModule = mParentModule;
  8317. BfModule* specModule = NULL;
  8318. BfModule** specModulePtr = NULL;
  8319. if (mainModule->mSpecializedMethodModules.TryGetValueWith(projectList, &specModulePtr))
  8320. {
  8321. return *specModulePtr;
  8322. }
  8323. else
  8324. {
  8325. String specModuleName = mModuleName;
  8326. for (auto bfProject : projectList)
  8327. specModuleName += StrFormat("@%s", bfProject->mName.c_str());
  8328. specModule = new BfModule(mContext, specModuleName);
  8329. specModule->mProject = mainModule->mProject;
  8330. specModule->mParentModule = mainModule;
  8331. specModule->mIsSpecializedMethodModuleRoot = true;
  8332. specModule->Init();
  8333. Array<BfProject*> projList;
  8334. for (auto project : projectList)
  8335. projList.Add(project);
  8336. mainModule->mSpecializedMethodModules[projList] = specModule;
  8337. }
  8338. return specModule;
  8339. }
  8340. BfIRValue BfModule::CreateFunctionFrom(BfMethodInstance* methodInstance, bool tryExisting, bool isInlined)
  8341. {
  8342. if (mCompiler->IsSkippingExtraResolveChecks())
  8343. return BfIRValue();
  8344. if (methodInstance->mMethodInstanceGroup->mOwner->IsInterface())
  8345. {
  8346. //BF_ASSERT(!methodInstance->mIRFunction);
  8347. return BfIRValue();
  8348. }
  8349. auto methodDef = methodInstance->mMethodDef;
  8350. StringT<128> methodName;
  8351. BfMangler::Mangle(methodName, mCompiler->GetMangleKind(), methodInstance);
  8352. if (isInlined != methodInstance->mAlwaysInline)
  8353. {
  8354. if (isInlined)
  8355. methodName += "__INLINE";
  8356. else
  8357. methodName += "__NOINLINE";
  8358. }
  8359. if (tryExisting)
  8360. {
  8361. auto func = mBfIRBuilder->GetFunction(methodName);
  8362. if (func)
  8363. return func;
  8364. }
  8365. auto intrinsic = GetIntrinsic(methodInstance);
  8366. if (intrinsic)
  8367. return intrinsic;
  8368. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  8369. {
  8370. return CreateDllImportGlobalVar(methodInstance, false);
  8371. }
  8372. BfIRType returnType;
  8373. SizedArray<BfIRType, 8> paramTypes;
  8374. methodInstance->GetIRFunctionInfo(this, returnType, paramTypes);
  8375. auto funcType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes, methodInstance->IsVarArgs());
  8376. auto func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, methodName);
  8377. auto callingConv = GetIRCallingConvention(methodInstance);
  8378. if (callingConv != BfIRCallingConv_CDecl)
  8379. mBfIRBuilder->SetFuncCallingConv(func, callingConv);
  8380. SetupIRMethod(methodInstance, func, isInlined);
  8381. // auto srcModule = methodInstance->GetOwner()->GetModule();
  8382. // if ((srcModule != NULL) && (srcModule->mProject != mProject))
  8383. // {
  8384. // if (srcModule->mProject->mTargetType == BfTargetType_BeefDynLib)
  8385. // {
  8386. // mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_DllImport);
  8387. // }
  8388. // }
  8389. return func;
  8390. }
  8391. BfModuleMethodInstance BfModule::GetMethodInstanceAtIdx(BfTypeInstance* typeInstance, int methodIdx, const char* assertName, BfGetMethodInstanceFlags flags)
  8392. {
  8393. if (assertName != NULL)
  8394. {
  8395. BF_ASSERT(typeInstance->mTypeDef->mMethods[methodIdx]->mName == assertName);
  8396. }
  8397. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  8398. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  8399. if ((methodInstance != NULL) && (mIsReified) && (!methodInstance->mIsReified))
  8400. {
  8401. // Can't use it, not reified
  8402. methodInstance = NULL;
  8403. }
  8404. if ((methodInstance != NULL) && (mBfIRBuilder != NULL) && (mBfIRBuilder->mIgnoreWrites) &&
  8405. (methodInstance->mMethodInstanceGroup->IsImplemented()))
  8406. {
  8407. BfIRFunction func(mBfIRBuilder->GetFakeVal());
  8408. return BfModuleMethodInstance(methodInstance, func);
  8409. }
  8410. return GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector(), flags);
  8411. }
  8412. BfModuleMethodInstance BfModule::GetMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  8413. {
  8414. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  8415. while (typeInstance != NULL)
  8416. {
  8417. typeInstance->mTypeDef->PopulateMemberSets();
  8418. BfMemberSetEntry* entry = NULL;
  8419. BfMethodDef* methodDef = NULL;
  8420. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  8421. methodDef = (BfMethodDef*)entry->mMemberDef;
  8422. while (methodDef != NULL)
  8423. {
  8424. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  8425. (methodDef->mGenericParams.size() == 0) &&
  8426. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  8427. return GetMethodInstanceAtIdx(typeInstance, methodDef->mIdx);
  8428. methodDef = methodDef->mNextWithSameName;
  8429. }
  8430. if (!checkBase)
  8431. break;
  8432. typeInstance = typeInstance->mBaseType;
  8433. }
  8434. return BfModuleMethodInstance();
  8435. }
  8436. BfModuleMethodInstance BfModule::GetMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, const Array<BfType*>& paramTypes, bool checkBase)
  8437. {
  8438. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  8439. while (typeInstance != NULL)
  8440. {
  8441. typeInstance->mTypeDef->PopulateMemberSets();
  8442. BfMemberSetEntry* entry = NULL;
  8443. BfMethodDef* methodDef = NULL;
  8444. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  8445. methodDef = (BfMethodDef*)entry->mMemberDef;
  8446. while (methodDef != NULL)
  8447. {
  8448. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  8449. (methodDef->mGenericParams.size() == 0) &&
  8450. (paramTypes.size() == methodDef->mParams.size()))
  8451. {
  8452. auto moduleMethodInstance = GetMethodInstanceAtIdx(typeInstance, methodDef->mIdx);
  8453. if (moduleMethodInstance.mMethodInstance != NULL)
  8454. {
  8455. bool matches = true;
  8456. for (int paramIdx = 0; paramIdx < (int)paramTypes.size(); paramIdx++)
  8457. {
  8458. if (moduleMethodInstance.mMethodInstance->GetParamType(paramIdx) != paramTypes[paramIdx])
  8459. matches = false;
  8460. }
  8461. if (matches)
  8462. return moduleMethodInstance;
  8463. }
  8464. }
  8465. methodDef = methodDef->mNextWithSameName;
  8466. }
  8467. if (!checkBase)
  8468. break;
  8469. typeInstance = typeInstance->mBaseType;
  8470. }
  8471. return BfModuleMethodInstance();
  8472. }
  8473. BfModuleMethodInstance BfModule::GetInternalMethod(const StringImpl& methodName, int paramCount)
  8474. {
  8475. auto internalType = ResolveTypeDef(mCompiler->mInternalTypeDef);
  8476. PopulateType(internalType);
  8477. auto moduleMethodInstance = GetMethodByName(internalType->ToTypeInstance(), methodName, paramCount);
  8478. if (!moduleMethodInstance)
  8479. {
  8480. Fail(StrFormat("Failed to find System.Internal method '%s'", methodName.c_str()));
  8481. }
  8482. return moduleMethodInstance;
  8483. }
  8484. BfOperatorInfo* BfModule::GetOperatorInfo(BfTypeInstance* typeInstance, BfOperatorDef* operatorDef)
  8485. {
  8486. while (operatorDef->mIdx >= typeInstance->mOperatorInfo.size())
  8487. typeInstance->mOperatorInfo.Add(NULL);
  8488. if (typeInstance->mOperatorInfo[operatorDef->mIdx] == NULL)
  8489. {
  8490. SetAndRestoreValue<bool> ignoreErrors(mIgnoreErrors, true);
  8491. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  8492. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL);
  8493. BfOperatorInfo* operatorInfo = new BfOperatorInfo();
  8494. if (operatorDef->mReturnTypeRef != NULL)
  8495. operatorInfo->mReturnType = ResolveTypeRef(operatorDef->mReturnTypeRef, BfPopulateType_Identity);
  8496. if (operatorDef->mParams.size() >= 1)
  8497. operatorInfo->mLHSType = ResolveTypeRef(operatorDef->mParams[0]->mTypeRef, BfPopulateType_Identity);
  8498. if (operatorDef->mParams.size() >= 2)
  8499. operatorInfo->mRHSType = ResolveTypeRef(operatorDef->mParams[1]->mTypeRef, BfPopulateType_Identity);
  8500. typeInstance->mOperatorInfo[operatorDef->mIdx] = operatorInfo;
  8501. }
  8502. return typeInstance->mOperatorInfo[operatorDef->mIdx];
  8503. }
  8504. BfType* BfModule::CheckOperator(BfTypeInstance* typeInstance, BfOperatorDef* operatorDef, const BfTypedValue& lhs, const BfTypedValue& rhs)
  8505. {
  8506. auto operatorInfo = GetOperatorInfo(typeInstance, operatorDef);
  8507. if (operatorInfo == NULL)
  8508. return NULL;
  8509. if (operatorInfo->mReturnType == NULL)
  8510. return NULL;
  8511. if (lhs)
  8512. {
  8513. if (operatorInfo->mLHSType == NULL)
  8514. return NULL;
  8515. if (!CanCast(lhs, operatorInfo->mLHSType, BfCastFlags_IsConstraintCheck))
  8516. return NULL;
  8517. }
  8518. if (rhs)
  8519. {
  8520. if (operatorInfo->mRHSType == NULL)
  8521. return NULL;
  8522. if (!CanCast(rhs, operatorInfo->mRHSType, BfCastFlags_IsConstraintCheck))
  8523. return NULL;
  8524. }
  8525. return operatorInfo->mReturnType;
  8526. }
  8527. bool BfModule::IsMethodImplementedAndReified(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  8528. {
  8529. while (typeInstance != NULL)
  8530. {
  8531. typeInstance->mTypeDef->PopulateMemberSets();
  8532. BfMemberSetEntry* entry = NULL;
  8533. BfMethodDef* methodDef = NULL;
  8534. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  8535. methodDef = (BfMethodDef*)entry->mMemberDef;
  8536. while (methodDef != NULL)
  8537. {
  8538. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  8539. (methodDef->mGenericParams.size() == 0) &&
  8540. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  8541. {
  8542. auto& methodInstanceGroup = typeInstance->mMethodInstanceGroups[methodDef->mIdx];
  8543. if (!methodInstanceGroup.IsImplemented())
  8544. return false;
  8545. if (methodInstanceGroup.mDefault == NULL)
  8546. return false;
  8547. return methodInstanceGroup.mDefault->mIsReified;
  8548. }
  8549. methodDef = methodDef->mNextWithSameName;
  8550. }
  8551. if (!checkBase)
  8552. break;
  8553. typeInstance = typeInstance->mBaseType;
  8554. }
  8555. return false;
  8556. }
  8557. bool BfModule::HasMixin(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  8558. {
  8559. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  8560. while (typeInstance != NULL)
  8561. {
  8562. typeInstance->mTypeDef->PopulateMemberSets();
  8563. BfMemberSetEntry* entry = NULL;
  8564. BfMethodDef* methodDef = NULL;
  8565. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  8566. methodDef = (BfMethodDef*)entry->mMemberDef;
  8567. while (methodDef != NULL)
  8568. {
  8569. if ((methodDef->mMethodType == BfMethodType_Mixin) &&
  8570. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  8571. return true;
  8572. methodDef = methodDef->mNextWithSameName;
  8573. }
  8574. if (!checkBase)
  8575. break;
  8576. typeInstance = typeInstance->mBaseType;
  8577. }
  8578. return BfModuleMethodInstance();
  8579. }
  8580. StringT<128> BfModule::MethodToString(BfMethodInstance* methodInst, BfMethodNameFlags methodNameFlags, BfTypeVector* methodGenericArgs)
  8581. {
  8582. auto methodDef = methodInst->mMethodDef;
  8583. bool allowResolveGenericParamNames = ((methodNameFlags & BfMethodNameFlag_ResolveGenericParamNames) != 0);
  8584. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  8585. BfType* type = methodInst->mMethodInstanceGroup->mOwner;
  8586. if ((methodGenericArgs != NULL) && (type->IsUnspecializedType()))
  8587. type = ResolveGenericType(type, NULL, methodGenericArgs);
  8588. if ((type == NULL) || (!type->IsUnspecializedTypeVariation()))
  8589. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  8590. if (allowResolveGenericParamNames)
  8591. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  8592. StringT<128> methodName;
  8593. auto _AddTypeName = [&](BfType* type)
  8594. {
  8595. auto typeNameFlags = BfTypeNameFlags_None;
  8596. if (allowResolveGenericParamNames)
  8597. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  8598. if ((methodGenericArgs != NULL) && (type->IsUnspecializedType()))
  8599. type = ResolveGenericType(type, NULL, methodGenericArgs);
  8600. methodName += TypeToString(type, typeNameFlags);
  8601. };
  8602. if ((methodNameFlags & BfMethodNameFlag_IncludeReturnType) != 0)
  8603. {
  8604. _AddTypeName(methodInst->mReturnType);
  8605. methodName += " ";
  8606. }
  8607. if ((methodNameFlags & BfMethodNameFlag_OmitTypeName) == 0)
  8608. {
  8609. methodName += TypeToString(type, typeNameFlags);
  8610. if (methodName == "$")
  8611. methodName = "";
  8612. else if (!methodName.IsEmpty())
  8613. methodName += ".";
  8614. }
  8615. String accessorString;
  8616. StringT<64> methodDefName = methodInst->mMethodDef->mName;
  8617. if (methodInst->mMethodDef->mIsLocalMethod)
  8618. {
  8619. int atPos = (int)methodDefName.IndexOf('$');
  8620. methodDefName.RemoveToEnd(atPos);
  8621. methodDefName.Replace("@", ".");
  8622. }
  8623. else
  8624. {
  8625. int atPos = (int)methodDefName.IndexOf('$');
  8626. if (atPos != -1)
  8627. {
  8628. accessorString = methodDefName.Substring(0, atPos);
  8629. if ((accessorString == "get") || (accessorString == "set"))
  8630. {
  8631. methodDefName = methodDefName.Substring(atPos + 1);
  8632. }
  8633. else
  8634. accessorString = "";
  8635. }
  8636. }
  8637. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mForeignType != NULL))
  8638. {
  8639. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  8640. if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  8641. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  8642. methodName += TypeToString(methodInst->mMethodInfoEx->mForeignType, typeNameFlags);
  8643. methodName += ".";
  8644. }
  8645. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mExplicitInterface != NULL))
  8646. {
  8647. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  8648. if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  8649. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  8650. methodName += "[";
  8651. methodName += TypeToString(methodInst->mMethodInfoEx->mExplicitInterface, typeNameFlags);
  8652. methodName += "].";
  8653. }
  8654. if (methodDef->mMethodType == BfMethodType_Operator)
  8655. {
  8656. BfOperatorDef* operatorDef = (BfOperatorDef*)methodDef;
  8657. if (operatorDef->mOperatorDeclaration->mIsConvOperator)
  8658. {
  8659. // Don't add explicit/implicit part, since that's not available in GCC mangling
  8660. /*if (operatorDef->mOperatorDeclaration->mExplicitToken != NULL)
  8661. {
  8662. if (operatorDef->mOperatorDeclaration->mExplicitToken->GetToken() == BfToken_Explicit)
  8663. methodName += "explicit ";
  8664. else if (operatorDef->mOperatorDeclaration->mExplicitToken->GetToken() == BfToken_Explicit)
  8665. methodName += "explicit ";
  8666. }*/
  8667. methodName += "operator ";
  8668. if (methodInst->mReturnType != NULL)
  8669. methodName += TypeToString(methodInst->mReturnType);
  8670. }
  8671. else
  8672. {
  8673. methodName += "operator";
  8674. if (operatorDef->mOperatorDeclaration->mOpTypeToken != NULL)
  8675. methodName += BfTokenToString(operatorDef->mOperatorDeclaration->mOpTypeToken->GetToken());
  8676. }
  8677. }
  8678. else if (methodDef->mMethodType == BfMethodType_Ctor)
  8679. {
  8680. if (methodDef->mIsStatic)
  8681. methodName += "__BfStaticCtor";
  8682. else
  8683. methodName += "this";
  8684. accessorString = "";
  8685. }
  8686. else if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  8687. {
  8688. auto propertyDecl = methodDef->GetPropertyDeclaration();
  8689. if (auto indexerProperty = BfNodeDynCast<BfIndexerDeclaration>(propertyDecl))
  8690. {
  8691. methodName += "get indexer";
  8692. }
  8693. else
  8694. {
  8695. if ((propertyDecl != NULL) && (propertyDecl->mNameNode != NULL))
  8696. propertyDecl->mNameNode->ToString(methodName);
  8697. methodName += " get accessor";
  8698. return methodName;
  8699. }
  8700. }
  8701. else if (methodDef->mMethodType == BfMethodType_PropertySetter)
  8702. {
  8703. auto propertyDecl = methodDef->GetPropertyDeclaration();
  8704. if (auto indexerProperty = BfNodeDynCast<BfIndexerDeclaration>(propertyDecl))
  8705. {
  8706. methodName += "set indexer";
  8707. }
  8708. else
  8709. {
  8710. if ((propertyDecl != NULL) && (propertyDecl->mNameNode != NULL))
  8711. propertyDecl->mNameNode->ToString(methodName);
  8712. methodName += " set accessor";
  8713. return methodName;
  8714. }
  8715. }
  8716. else
  8717. methodName += methodDefName;
  8718. if (methodDef->mMethodType == BfMethodType_Mixin)
  8719. methodName += "!";
  8720. BfTypeVector newMethodGenericArgs;
  8721. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mMethodGenericArguments.size() != 0))
  8722. {
  8723. methodName += "<";
  8724. for (int i = 0; i < (int)methodInst->mMethodInfoEx->mMethodGenericArguments.size(); i++)
  8725. {
  8726. if (i > 0)
  8727. methodName += ", ";
  8728. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  8729. //Why did we have this methodInst->mIsUnspecializedVariation check? Sometimes we do need to show errors calling methods that refer back to our types
  8730. //if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  8731. if (allowResolveGenericParamNames)
  8732. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  8733. BfType* type = methodInst->mMethodInfoEx->mMethodGenericArguments[i];
  8734. if ((methodGenericArgs != NULL) && (type->IsUnspecializedType()))
  8735. {
  8736. bool hasEmpty = false;
  8737. for (auto arg : *methodGenericArgs)
  8738. {
  8739. if (arg == NULL)
  8740. hasEmpty = true;
  8741. }
  8742. if (hasEmpty)
  8743. {
  8744. for (int genericIdx = 0; genericIdx < (int)methodGenericArgs->size(); genericIdx++)
  8745. {
  8746. auto arg = (*methodGenericArgs)[genericIdx];
  8747. if (arg != NULL)
  8748. newMethodGenericArgs.push_back(arg);
  8749. else
  8750. {
  8751. auto genericParamInst = methodInst->mMethodInfoEx->mGenericParams[genericIdx];
  8752. if (genericParamInst->mTypeConstraint != NULL)
  8753. newMethodGenericArgs.push_back(genericParamInst->mTypeConstraint);
  8754. else
  8755. newMethodGenericArgs.push_back(mContext->mBfObjectType); // Default
  8756. }
  8757. }
  8758. methodGenericArgs = &newMethodGenericArgs;
  8759. }
  8760. if (type->IsUnspecializedType())
  8761. type = ResolveGenericType(type, NULL, methodGenericArgs);
  8762. }
  8763. if ((methodGenericArgs == NULL) && (mCurMethodInstance == NULL) && (mCurTypeInstance == NULL))
  8764. {
  8765. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, methodInst->GetOwner());
  8766. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInst);
  8767. methodName += TypeToString(type, typeNameFlags);
  8768. }
  8769. else
  8770. methodName += TypeToString(type, typeNameFlags);
  8771. }
  8772. methodName += ">";
  8773. }
  8774. if (accessorString.length() == 0)
  8775. {
  8776. int dispParamIdx = 0;
  8777. methodName += "(";
  8778. for (int paramIdx = 0; paramIdx < (int)methodInst->GetParamCount(); paramIdx++)
  8779. {
  8780. int paramKind = methodInst->GetParamKind(paramIdx);
  8781. if (paramKind == BfParamKind_ImplicitCapture)
  8782. continue;
  8783. if (dispParamIdx > 0)
  8784. methodName += ", ";
  8785. if (paramKind == BfParamKind_Params)
  8786. methodName += "params ";
  8787. BfType* type = methodInst->GetParamType(paramIdx);
  8788. _AddTypeName(type);
  8789. methodName += " ";
  8790. methodName += methodInst->GetParamName(paramIdx);
  8791. auto paramInitializer = methodInst->GetParamInitializer(paramIdx);
  8792. if (paramInitializer != NULL)
  8793. {
  8794. methodName += " = ";
  8795. methodName += paramInitializer->ToString();
  8796. }
  8797. dispParamIdx++;
  8798. }
  8799. methodName += ")";
  8800. }
  8801. if (accessorString.length() != 0)
  8802. {
  8803. methodName += " " + accessorString;
  8804. }
  8805. return methodName;
  8806. }
  8807. void BfModule::pv(BfType* type)
  8808. {
  8809. OutputDebugStrF("%s\n", TypeToString(type).c_str());
  8810. }
  8811. static void AddAttributeTargetName(BfAttributeTargets& flagsLeft, BfAttributeTargets checkFlag, String& str, String addString)
  8812. {
  8813. if ((flagsLeft & checkFlag) == 0)
  8814. return;
  8815. if (!str.empty())
  8816. {
  8817. if (flagsLeft == checkFlag)
  8818. {
  8819. if ((int)str.IndexOf(',') != -1)
  8820. str += ", and ";
  8821. else
  8822. str += " and ";
  8823. }
  8824. else
  8825. str += ", ";
  8826. }
  8827. str += addString;
  8828. flagsLeft = (BfAttributeTargets)(flagsLeft & ~checkFlag);
  8829. }
  8830. static String GetAttributesTargetListString(BfAttributeTargets attrTarget)
  8831. {
  8832. String resultStr;
  8833. auto flagsLeft = attrTarget;
  8834. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Assembly, resultStr, "assembly declarations");
  8835. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Module, resultStr, "module declarations");
  8836. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Class, resultStr, "class declarations");
  8837. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Struct, resultStr, "struct declarations");
  8838. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Enum, resultStr, "enum declarations");
  8839. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Constructor, resultStr, "constructor declarations");
  8840. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Method, resultStr, "method declarations");
  8841. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Property, resultStr, "property declarations");
  8842. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Field, resultStr, "field declarations");
  8843. AddAttributeTargetName(flagsLeft, BfAttributeTargets_StaticField, resultStr, "static field declarations");
  8844. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Interface, resultStr, "interface declarations");
  8845. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Parameter, resultStr, "parameter declarations");
  8846. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Delegate, resultStr, "delegate declarations");
  8847. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Function, resultStr, "function declarations");
  8848. AddAttributeTargetName(flagsLeft, BfAttributeTargets_ReturnValue, resultStr, "return value");
  8849. AddAttributeTargetName(flagsLeft, BfAttributeTargets_GenericParameter, resultStr, "generic parameters");
  8850. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Invocation, resultStr, "invocations");
  8851. AddAttributeTargetName(flagsLeft, BfAttributeTargets_MemberAccess, resultStr, "member access");
  8852. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Alloc, resultStr, "allocations");
  8853. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Alias, resultStr, "aliases");
  8854. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Block, resultStr, "blocks");
  8855. if (resultStr.IsEmpty())
  8856. return "<nothing>";
  8857. return resultStr;
  8858. }
  8859. void BfModule::CurrentAddToConstHolder(BfIRValue& irVal)
  8860. {
  8861. auto constant = mBfIRBuilder->GetConstant(irVal);
  8862. int stringPoolIdx = GetStringPoolIdx(irVal, mBfIRBuilder);
  8863. if (stringPoolIdx != -1)
  8864. {
  8865. irVal = mCurTypeInstance->GetOrCreateConstHolder()->CreateConst(BfTypeCode_StringId, stringPoolIdx);
  8866. return;
  8867. }
  8868. if (constant->mConstType == BfConstType_Array)
  8869. {
  8870. auto constArray = (BfConstantArray*)constant;
  8871. SizedArray<BfIRValue, 8> newVals;
  8872. for (auto val : constArray->mValues)
  8873. {
  8874. auto newVal = val;
  8875. CurrentAddToConstHolder(newVal);
  8876. newVals.push_back(newVal);
  8877. }
  8878. irVal = mCurTypeInstance->GetOrCreateConstHolder()->CreateConstArray(constArray->mType, newVals);
  8879. return;
  8880. }
  8881. auto origConst = irVal;
  8882. if ((constant->mConstType == BfConstType_BitCast) || (constant->mConstType == BfConstType_BitCastNull))
  8883. {
  8884. auto bitcast = (BfConstantBitCast*)constant;
  8885. constant = mBfIRBuilder->GetConstantById(bitcast->mTarget);
  8886. }
  8887. irVal = mCurTypeInstance->CreateConst(constant, mBfIRBuilder);
  8888. }
  8889. void BfModule::ClearConstData()
  8890. {
  8891. mBfIRBuilder->ClearConstData();
  8892. mStringObjectPool.Clear();
  8893. mStringCharPtrPool.Clear();
  8894. mStringPoolRefs.Clear();
  8895. }
  8896. BfTypedValue BfModule::GetTypedValueFromConstant(BfConstant* constant, BfIRConstHolder* constHolder, BfType* wantType)
  8897. {
  8898. switch (constant->mTypeCode)
  8899. {
  8900. case BfTypeCode_StringId:
  8901. case BfTypeCode_Boolean:
  8902. case BfTypeCode_Int8:
  8903. case BfTypeCode_UInt8:
  8904. case BfTypeCode_Int16:
  8905. case BfTypeCode_UInt16:
  8906. case BfTypeCode_Int32:
  8907. case BfTypeCode_UInt32:
  8908. case BfTypeCode_Int64:
  8909. case BfTypeCode_UInt64:
  8910. case BfTypeCode_IntPtr:
  8911. case BfTypeCode_UIntPtr:
  8912. case BfTypeCode_IntUnknown:
  8913. case BfTypeCode_UIntUnknown:
  8914. case BfTypeCode_Char8:
  8915. case BfTypeCode_Char16:
  8916. case BfTypeCode_Char32:
  8917. case BfTypeCode_Float:
  8918. case BfTypeCode_Double:
  8919. {
  8920. auto constVal = mBfIRBuilder->CreateConst(constant, constHolder);
  8921. BfTypedValue typedValue;
  8922. if (constant->mTypeCode == BfTypeCode_StringId)
  8923. {
  8924. if ((wantType->IsInstanceOf(mCompiler->mStringTypeDef)) ||
  8925. ((wantType->IsPointer()) && (wantType->GetUnderlyingType() == GetPrimitiveType(BfTypeCode_Char8))))
  8926. {
  8927. typedValue = BfTypedValue(ConstantToCurrent(constant, constHolder, wantType), wantType);
  8928. return typedValue;
  8929. }
  8930. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  8931. typedValue = BfTypedValue(ConstantToCurrent(constant, constHolder, stringType), stringType);
  8932. }
  8933. if (!typedValue)
  8934. {
  8935. auto constVal = mBfIRBuilder->CreateConst(constant, constHolder);
  8936. typedValue = BfTypedValue(constVal, GetPrimitiveType(constant->mTypeCode));
  8937. }
  8938. if (typedValue.mType == wantType)
  8939. return typedValue;
  8940. if (wantType->IsTypedPrimitive())
  8941. {
  8942. if (typedValue.mType == wantType->GetUnderlyingType())
  8943. {
  8944. typedValue.mType = wantType;
  8945. return typedValue;
  8946. }
  8947. }
  8948. auto castedTypedValue = Cast(NULL, typedValue, wantType, (BfCastFlags)(BfCastFlags_SilentFail | BfCastFlags_Explicit));
  8949. if (!castedTypedValue)
  8950. return BfTypedValue();
  8951. return castedTypedValue;
  8952. }
  8953. break;
  8954. default: break;
  8955. }
  8956. BfIRValue irValue = ConstantToCurrent(constant, constHolder, wantType);
  8957. BF_ASSERT(irValue);
  8958. if (!irValue)
  8959. return BfTypedValue();
  8960. if (constant->mConstType == BfConstType_GlobalVar)
  8961. {
  8962. auto result = BfTypedValue(irValue, wantType, true);
  8963. if (!wantType->IsComposite())
  8964. result = LoadValue(result);
  8965. return result;
  8966. }
  8967. return BfTypedValue(irValue, wantType, false);
  8968. }
  8969. BfIRValue BfModule::ConstantToCurrent(BfConstant* constant, BfIRConstHolder* constHolder, BfType* wantType)
  8970. {
  8971. if (constant->mTypeCode == BfTypeCode_NullPtr)
  8972. {
  8973. return GetDefaultValue(wantType);
  8974. }
  8975. if (constant->mTypeCode == BfTypeCode_StringId)
  8976. {
  8977. if ((wantType->IsInstanceOf(mCompiler->mStringTypeDef)) ||
  8978. ((wantType->IsPointer()) && (wantType->GetUnderlyingType() == GetPrimitiveType(BfTypeCode_Char8))))
  8979. {
  8980. const StringImpl& str = mContext->mStringObjectIdMap[constant->mInt32].mString;
  8981. BfIRValue stringObjConst = GetStringObjectValue(str);
  8982. if (wantType->IsPointer())
  8983. return GetStringCharPtr(stringObjConst);
  8984. return stringObjConst;
  8985. }
  8986. }
  8987. if (constant->mConstType == BfConstType_Array)
  8988. {
  8989. auto elementType = wantType->GetUnderlyingType();
  8990. auto constArray = (BfConstantArray*)constant;
  8991. SizedArray<BfIRValue, 8> newVals;
  8992. for (auto val : constArray->mValues)
  8993. {
  8994. newVals.push_back(ConstantToCurrent(constHolder->GetConstant(val), constHolder, elementType));
  8995. }
  8996. return mBfIRBuilder->CreateConstArray(mBfIRBuilder->MapType(wantType), newVals);
  8997. }
  8998. return mBfIRBuilder->CreateConst(constant, constHolder);
  8999. }
  9000. void BfModule::ValidateCustomAttributes(BfCustomAttributes* customAttributes, BfAttributeTargets attrTarget)
  9001. {
  9002. if (attrTarget == BfAttributeTargets_SkipValidate)
  9003. return;
  9004. for (auto& customAttribute : customAttributes->mAttributes)
  9005. {
  9006. if (!customAttribute.mAwaitingValidation)
  9007. continue;
  9008. if ((customAttribute.mType->mAttributeData->mAttributeTargets & attrTarget) == 0)
  9009. {
  9010. Fail(StrFormat("Attribute '%s' is not valid on this declaration type. It is only valid on %s.",
  9011. customAttribute.GetRefNode()->ToString().c_str(), GetAttributesTargetListString(customAttribute.mType->mAttributeData->mAttributeTargets).c_str()), customAttribute.mRef->mAttributeTypeRef); // CS0592
  9012. }
  9013. customAttribute.mAwaitingValidation = false;
  9014. }
  9015. }
  9016. void BfModule::GetCustomAttributes(BfCustomAttributes* customAttributes, BfAttributeDirective* attributesDirective, BfAttributeTargets attrTarget, bool allowNonConstArgs, BfCaptureInfo* captureInfo)
  9017. {
  9018. if ((attributesDirective != NULL) && (mCompiler->mResolvePassData != NULL) &&
  9019. (attributesDirective->IsFromParser(mCompiler->mResolvePassData->mParser)) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  9020. {
  9021. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(attributesDirective);
  9022. }
  9023. SetAndRestoreValue<bool> prevIsCapturingMethodMatchInfo;
  9024. if (mCompiler->IsAutocomplete())
  9025. prevIsCapturingMethodMatchInfo.Init(mCompiler->mResolvePassData->mAutoComplete->mIsCapturingMethodMatchInfo, false);
  9026. BfTypeInstance* baseAttrTypeInst = mContext->mUnreifiedModule->ResolveTypeDef(mCompiler->mAttributeTypeDef)->ToTypeInstance();
  9027. BfAttributeTargets targetOverride = (BfAttributeTargets)0;
  9028. BfAutoComplete* autoComplete = NULL;
  9029. if (mCompiler->mResolvePassData != NULL)
  9030. autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  9031. for (; attributesDirective != NULL; attributesDirective = attributesDirective->mNextAttribute)
  9032. {
  9033. if (auto tokenNode = BfNodeDynCast<BfTokenNode>(attributesDirective->mAttributeTargetSpecifier))
  9034. {
  9035. if (captureInfo == NULL)
  9036. {
  9037. Fail("Capture specifiers can only be used in lambda allocations", attributesDirective);
  9038. continue;
  9039. }
  9040. BfCaptureInfo::Entry captureEntry;
  9041. captureEntry.mCaptureType = (tokenNode->mToken == BfToken_Ampersand) ? BfCaptureType_Reference : BfCaptureType_Copy;
  9042. if (!attributesDirective->mArguments.IsEmpty())
  9043. {
  9044. captureEntry.mNameNode = BfNodeDynCast<BfIdentifierNode>(attributesDirective->mArguments[0]);
  9045. if ((captureEntry.mNameNode != NULL) && (autoComplete != NULL))
  9046. autoComplete->CheckIdentifier(captureEntry.mNameNode);
  9047. }
  9048. captureInfo->mCaptures.Add(captureEntry);
  9049. continue;
  9050. }
  9051. BfAutoParentNodeEntry autoParentNodeEntry(this, attributesDirective);
  9052. BfCustomAttribute customAttribute;
  9053. customAttribute.mAwaitingValidation = true;
  9054. customAttribute.mRef = attributesDirective;
  9055. if (attributesDirective->mAttrOpenToken != NULL)
  9056. targetOverride = (BfAttributeTargets)0;
  9057. if (attributesDirective->mAttributeTypeRef == NULL)
  9058. {
  9059. AssertErrorState();
  9060. continue;
  9061. }
  9062. BfType* attrType = ResolveTypeRef(attributesDirective->mAttributeTypeRef, BfPopulateType_Identity, (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_Attribute | BfResolveTypeRefFlag_NoReify));
  9063. BfTypeDef* attrTypeDef = NULL;
  9064. if ((attrType != NULL) && (attrType->IsTypeInstance()))
  9065. attrTypeDef = attrType->ToTypeInstance()->mTypeDef;
  9066. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  9067. {
  9068. mCompiler->mResolvePassData->mAutoComplete->CheckAttributeTypeRef(attributesDirective->mAttributeTypeRef);
  9069. if (attrTypeDef != NULL)
  9070. mCompiler->mResolvePassData->HandleTypeReference(attributesDirective->mAttributeTypeRef, attrTypeDef);
  9071. }
  9072. bool isBypassedAttr = false;
  9073. if (attrTypeDef != NULL)
  9074. {
  9075. // 'Object' has some dependencies on some attributes, but those attributes are classes so we have a circular dependency issue
  9076. // We solve it by having a 'bypass' for known attributes that Object depends on
  9077. if ((attributesDirective->mArguments.empty()) && (autoComplete == NULL) && (attrType != NULL) && (attrType->IsTypeInstance()))
  9078. {
  9079. //if (attrTypeDef == mCompiler->mCReprAttributeTypeDef)
  9080. if (attrType->IsInstanceOf(mCompiler->mCReprAttributeTypeDef))
  9081. {
  9082. for (auto methodDef : attrTypeDef->mMethods)
  9083. {
  9084. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mProtection == BfProtection_Public))
  9085. {
  9086. customAttribute.mType = attrType->ToTypeInstance();
  9087. customAttribute.mCtor = methodDef;
  9088. isBypassedAttr = true;
  9089. break;
  9090. }
  9091. }
  9092. }
  9093. }
  9094. if (isBypassedAttr)
  9095. {
  9096. customAttribute.mAwaitingValidation = false;
  9097. customAttributes->mAttributes.push_back(customAttribute);
  9098. continue;
  9099. }
  9100. if (mContext->mCurTypeState != NULL)
  9101. {
  9102. SetAndRestoreValue<BfTypeReference*> prevTypeRef(mContext->mCurTypeState->mCurAttributeTypeRef, attributesDirective->mAttributeTypeRef);
  9103. mContext->mUnreifiedModule->ResolveTypeResult(attributesDirective->mAttributeTypeRef, attrType, BfPopulateType_BaseType, (BfResolveTypeRefFlags)0);
  9104. }
  9105. else
  9106. {
  9107. mContext->mUnreifiedModule->ResolveTypeResult(attributesDirective->mAttributeTypeRef, attrType, BfPopulateType_BaseType, (BfResolveTypeRefFlags)0);
  9108. }
  9109. }
  9110. BfTypeInstance* attrTypeInst = NULL;
  9111. if (attrType == NULL)
  9112. continue;
  9113. mContext->mUnreifiedModule->PopulateType(attrType, BfPopulateType_DataAndMethods);
  9114. attrTypeInst = attrType->ToTypeInstance();
  9115. if ((attrTypeInst == NULL) || (!TypeIsSubTypeOf(attrTypeInst, baseAttrTypeInst)) || (attrTypeInst->mAttributeData == NULL))
  9116. {
  9117. Fail(StrFormat("'%s' is not an attribute class", TypeToString(attrType).c_str()), attributesDirective->mAttributeTypeRef); //CS0616
  9118. continue;
  9119. }
  9120. if (mCurTypeInstance != NULL)
  9121. AddDependency(attrTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  9122. customAttribute.mType = attrTypeInst;
  9123. BfConstResolver constResolver(this);
  9124. if (allowNonConstArgs)
  9125. constResolver.mBfEvalExprFlags = (BfEvalExprFlags)(constResolver.mBfEvalExprFlags | BfEvalExprFlags_AllowNonConst);
  9126. bool inPropSet = false;
  9127. SizedArray<BfResolvedArg, 2> argValues;
  9128. for (BfExpression* arg : attributesDirective->mArguments)
  9129. {
  9130. if (arg == NULL)
  9131. {
  9132. continue;
  9133. }
  9134. if (autoComplete != NULL)
  9135. autoComplete->mShowAttributeProperties = attrTypeInst;
  9136. if (auto assignExpr = BfNodeDynCast<BfAssignmentExpression>(arg))
  9137. {
  9138. inPropSet = true;
  9139. if (autoComplete != NULL)
  9140. autoComplete->CheckNode(assignExpr->mLeft);
  9141. String findName = assignExpr->mLeft->ToString();
  9142. BfPropertyDef* bestProp = NULL;
  9143. BfTypeInstance* bestPropTypeInst = NULL;
  9144. BfFieldDef* bestField = NULL;
  9145. BfTypeInstance* bestFieldTypeInst = NULL;
  9146. auto checkTypeInst = attrTypeInst;
  9147. while (checkTypeInst != NULL)
  9148. {
  9149. mContext->mUnreifiedModule->PopulateType(checkTypeInst, BfPopulateType_Data);
  9150. for (auto prop : checkTypeInst->mTypeDef->mProperties)
  9151. {
  9152. if (prop->mName == findName)
  9153. {
  9154. if ((bestProp == NULL) || (bestProp->mProtection != BfProtection_Public))
  9155. {
  9156. bestProp = prop;
  9157. bestPropTypeInst = checkTypeInst;
  9158. }
  9159. }
  9160. }
  9161. for (auto field : checkTypeInst->mTypeDef->mFields)
  9162. {
  9163. if (field->mName == findName)
  9164. {
  9165. if ((bestField == NULL) || (bestField->mProtection != BfProtection_Public))
  9166. {
  9167. bestField = field;
  9168. bestFieldTypeInst = checkTypeInst;
  9169. }
  9170. }
  9171. }
  9172. if ((bestProp != NULL) || (bestField != NULL))
  9173. break;
  9174. checkTypeInst = checkTypeInst->mBaseType;
  9175. }
  9176. bool handledExpr = false;
  9177. if (bestField != NULL)
  9178. {
  9179. handledExpr = true;
  9180. if (mCompiler->mResolvePassData != NULL)
  9181. {
  9182. mCompiler->mResolvePassData->HandleFieldReference(assignExpr->mLeft, attrTypeDef, bestField);
  9183. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(assignExpr->mLeft)))
  9184. {
  9185. autoComplete->mDefField = bestField;
  9186. autoComplete->mDefType = attrTypeDef;
  9187. }
  9188. }
  9189. if (bestField->mProtection != BfProtection_Public)
  9190. Fail(StrFormat("'%s.%s' is inaccessible due to its protection level", TypeToString(bestFieldTypeInst).c_str(), findName.c_str()), assignExpr->mLeft); // CS0122
  9191. AddDependency(bestFieldTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  9192. BfCustomAttributeSetField setField;
  9193. setField.mFieldRef = BfFieldRef(bestFieldTypeInst, bestField);
  9194. auto& fieldTypeInst = checkTypeInst->mFieldInstances[bestField->mIdx];
  9195. if (assignExpr->mRight != NULL)
  9196. {
  9197. BfTypedValue result = constResolver.Resolve(assignExpr->mRight, fieldTypeInst.mResolvedType);
  9198. if (result)
  9199. {
  9200. CurrentAddToConstHolder(result.mValue);
  9201. setField.mParam = result;
  9202. customAttribute.mSetField.push_back(setField);
  9203. }
  9204. }
  9205. }
  9206. else if (bestProp == NULL)
  9207. {
  9208. Fail(StrFormat("'%s' does not contain a field or property named '%s'", TypeToString(attrTypeInst).c_str(), findName.c_str()), assignExpr->mLeft);
  9209. }
  9210. else
  9211. {
  9212. BfMethodDef* setMethod = NULL;
  9213. for (auto methodDef : bestProp->mMethods)
  9214. {
  9215. if (methodDef->mMethodType == BfMethodType_PropertySetter)
  9216. {
  9217. setMethod = methodDef;
  9218. break;
  9219. }
  9220. }
  9221. if (setMethod == NULL)
  9222. {
  9223. Fail("Property has no setter", assignExpr->mLeft);
  9224. }
  9225. else
  9226. {
  9227. if (mCompiler->mResolvePassData != NULL)
  9228. {
  9229. mCompiler->mResolvePassData->HandlePropertyReference(assignExpr->mLeft, attrTypeDef, bestProp);
  9230. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(assignExpr->mLeft)))
  9231. {
  9232. autoComplete->mDefProp = bestProp;
  9233. autoComplete->mDefType = attrTypeDef;
  9234. }
  9235. }
  9236. handledExpr = true;
  9237. if (bestProp->mProtection != BfProtection_Public)
  9238. Fail(StrFormat("'%s.%s' is inaccessible due to its protection level", TypeToString(bestPropTypeInst).c_str(), findName.c_str()), assignExpr->mLeft); // CS0122
  9239. BfResolvedArg resolvedArg;
  9240. AddDependency(bestPropTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  9241. BfCustomAttributeSetProperty setProperty;
  9242. setProperty.mPropertyRef = BfPropertyRef(bestPropTypeInst, bestProp);
  9243. // We don't actually need the mFunc, so get the ModuleMethodInstance from the native module
  9244. auto methodInstance = bestPropTypeInst->mModule->GetMethodInstance(bestPropTypeInst, setMethod, BfTypeVector());
  9245. if (methodInstance.mMethodInstance != NULL)
  9246. {
  9247. auto propType = methodInstance.mMethodInstance->GetParamType(0);
  9248. if (assignExpr->mRight != NULL)
  9249. {
  9250. BfTypedValue result = constResolver.Resolve(assignExpr->mRight, propType);
  9251. if (result)
  9252. {
  9253. BF_ASSERT(result.mType == propType);
  9254. CurrentAddToConstHolder(result.mValue);
  9255. setProperty.mParam = result;
  9256. customAttribute.mSetProperties.push_back(setProperty);
  9257. }
  9258. }
  9259. }
  9260. }
  9261. }
  9262. if ((!handledExpr) && (assignExpr->mRight != NULL))
  9263. constResolver.Resolve(assignExpr->mRight);
  9264. }
  9265. else
  9266. {
  9267. if (inPropSet)
  9268. {
  9269. Fail("Named attribute argument expected", arg); // CS1016
  9270. }
  9271. BfDeferEvalChecker deferEvalChecker;
  9272. arg->Accept(&deferEvalChecker);
  9273. bool deferParamEval = deferEvalChecker.mNeedsDeferEval;
  9274. BfResolvedArg resolvedArg;
  9275. resolvedArg.mExpression = arg;
  9276. if (deferParamEval)
  9277. {
  9278. resolvedArg.mArgFlags = BfArgFlag_DeferredEval;
  9279. }
  9280. else
  9281. resolvedArg.mTypedValue = constResolver.Resolve(arg);
  9282. if (!inPropSet)
  9283. {
  9284. argValues.push_back(resolvedArg);
  9285. }
  9286. }
  9287. if (autoComplete != NULL)
  9288. autoComplete->mShowAttributeProperties = NULL;
  9289. }
  9290. auto wasCapturingMethodInfo = false;
  9291. if (autoComplete != NULL)
  9292. {
  9293. wasCapturingMethodInfo = autoComplete->mIsCapturingMethodMatchInfo;
  9294. if (attributesDirective->mCtorOpenParen != NULL)
  9295. autoComplete->CheckInvocation(attributesDirective, attributesDirective->mCtorOpenParen, attributesDirective->mCtorCloseParen, attributesDirective->mCommas);
  9296. }
  9297. BfMethodMatcher methodMatcher(attributesDirective, this, "", argValues, NULL);
  9298. attrTypeDef = attrTypeInst->mTypeDef;
  9299. bool success = true;
  9300. bool isFailurePass = false;
  9301. for (int pass = 0; pass < 2; pass++)
  9302. {
  9303. bool isFailurePass = pass == 1;
  9304. for (auto checkMethod : attrTypeDef->mMethods)
  9305. {
  9306. if ((isFailurePass) && (checkMethod->mMethodDeclaration == NULL))
  9307. continue; // Don't match private default ctor if there's a user-defined one
  9308. if ((checkMethod->mIsStatic) || (checkMethod->mMethodType != BfMethodType_Ctor))
  9309. continue;
  9310. if ((!isFailurePass) && (!CheckProtection(checkMethod->mProtection, attrTypeInst->mTypeDef, false, false)))
  9311. continue;
  9312. methodMatcher.CheckMethod(NULL, attrTypeInst, checkMethod, isFailurePass);
  9313. }
  9314. if ((methodMatcher.mBestMethodDef != NULL) || (methodMatcher.mBackupMethodDef != NULL))
  9315. break;
  9316. }
  9317. if (autoComplete != NULL)
  9318. {
  9319. if ((wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo))
  9320. {
  9321. autoComplete->mIsCapturingMethodMatchInfo = true;
  9322. BF_ASSERT(autoComplete->mMethodMatchInfo != NULL);
  9323. }
  9324. else
  9325. autoComplete->mIsCapturingMethodMatchInfo = false;
  9326. }
  9327. if (methodMatcher.mBestMethodDef == NULL)
  9328. methodMatcher.mBestMethodDef = methodMatcher.mBackupMethodDef;
  9329. BF_ASSERT(methodMatcher.mBestMethodDef != NULL);
  9330. customAttribute.mCtor = methodMatcher.mBestMethodDef;
  9331. if (methodMatcher.mBestMethodTypeInstance == mCurTypeInstance)
  9332. {
  9333. Fail("Custom attribute circular reference", attributesDirective);
  9334. }
  9335. if (mCurTypeInstance != NULL)
  9336. AddDependency(methodMatcher.mBestMethodTypeInstance, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  9337. if (!constResolver.PrepareMethodArguments(attributesDirective->mAttributeTypeRef, &methodMatcher, customAttribute.mCtorArgs))
  9338. success = false;
  9339. for (auto& arg : argValues)
  9340. {
  9341. if ((arg.mArgFlags & BfArgFlag_DeferredEval) != 0)
  9342. {
  9343. if (auto expr = BfNodeDynCast<BfExpression>(arg.mExpression))
  9344. constResolver.Resolve(expr);
  9345. }
  9346. }
  9347. // Move all those to the constHolder
  9348. for (auto& ctorArg : customAttribute.mCtorArgs)
  9349. {
  9350. if (ctorArg.IsConst())
  9351. CurrentAddToConstHolder(ctorArg);
  9352. }
  9353. if (attributesDirective->mAttributeTargetSpecifier != NULL)
  9354. {
  9355. targetOverride = BfAttributeTargets_ReturnValue;
  9356. if (attrTarget != BfAttributeTargets_Method)
  9357. {
  9358. 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.",
  9359. GetAttributesTargetListString(targetOverride).c_str(), GetAttributesTargetListString(attrTarget).c_str()), attributesDirective->mAttributeTargetSpecifier); // CS0657
  9360. }
  9361. success = false;
  9362. }
  9363. if ((success) && (targetOverride != (BfAttributeTargets)0))
  9364. {
  9365. if ((targetOverride == BfAttributeTargets_ReturnValue) && (attrTarget == BfAttributeTargets_Method))
  9366. {
  9367. auto methodInfoEx = mCurMethodInstance->GetMethodInfoEx();
  9368. if (methodInfoEx->mMethodCustomAttributes == NULL)
  9369. methodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  9370. if (success)
  9371. {
  9372. if (methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes == NULL)
  9373. methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes = new BfCustomAttributes();
  9374. methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes->mAttributes.push_back(customAttribute);
  9375. }
  9376. }
  9377. else
  9378. {
  9379. // Failed - ignore
  9380. success = false;
  9381. }
  9382. }
  9383. if (success)
  9384. {
  9385. if (!attrTypeInst->mAttributeData->mAllowMultiple)
  9386. {
  9387. for (auto& prevCustomAttribute : customAttributes->mAttributes)
  9388. {
  9389. if (prevCustomAttribute.mType == attrTypeInst)
  9390. {
  9391. Fail(StrFormat("Duplicate '%s' attribute", attributesDirective->mAttributeTypeRef->ToString().c_str()), attributesDirective->mAttributeTypeRef); // CS0579
  9392. }
  9393. }
  9394. }
  9395. }
  9396. if (success)
  9397. {
  9398. customAttributes->mAttributes.push_back(customAttribute);
  9399. }
  9400. }
  9401. ValidateCustomAttributes(customAttributes, attrTarget);
  9402. }
  9403. BfCustomAttributes* BfModule::GetCustomAttributes(BfAttributeDirective* attributesDirective, BfAttributeTargets attrType, bool allowNonConstArgs, BfCaptureInfo* captureInfo)
  9404. {
  9405. BfCustomAttributes* customAttributes = new BfCustomAttributes();
  9406. GetCustomAttributes(customAttributes, attributesDirective, attrType, allowNonConstArgs, captureInfo);
  9407. return customAttributes;
  9408. }
  9409. void BfModule::FinishAttributeState(BfAttributeState* attributeState)
  9410. {
  9411. if ((!attributeState->mUsed) && (attributeState->mSrc != NULL))
  9412. Warn(0, "Unused attributes", attributeState->mSrc);
  9413. }
  9414. void BfModule::ProcessTypeInstCustomAttributes(bool& isPacked, bool& isUnion, bool& isCRepr, bool& isOrdered, int& alignOverride, BfType*& underlyingArrayType, int& underlyingArraySize)
  9415. {
  9416. if (mCurTypeInstance->mCustomAttributes != NULL)
  9417. {
  9418. for (auto& customAttribute : mCurTypeInstance->mCustomAttributes->mAttributes)
  9419. {
  9420. String typeName = TypeToString(customAttribute.mType);
  9421. if (typeName == "System.PackedAttribute")
  9422. {
  9423. isPacked = true;
  9424. }
  9425. else if (typeName == "System.UnionAttribute")
  9426. {
  9427. isUnion = true;
  9428. }
  9429. else if (typeName == "System.CReprAttribute")
  9430. {
  9431. isCRepr = true;
  9432. isOrdered = true;
  9433. }
  9434. else if (typeName == "System.OrderedAttribute")
  9435. {
  9436. isOrdered = true;
  9437. }
  9438. else if (typeName == "System.AlwaysIncludeAttribute")
  9439. {
  9440. for (auto setProp : customAttribute.mSetProperties)
  9441. {
  9442. BfPropertyDef* propertyDef = setProp.mPropertyRef;
  9443. if (propertyDef->mName == "AssumeInstantiated")
  9444. {
  9445. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  9446. if ((constant != NULL) && (constant->mBool))
  9447. mCurTypeInstance->mHasBeenInstantiated = true;
  9448. }
  9449. else if (propertyDef->mName == "IncludeAllMethods")
  9450. {
  9451. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  9452. if ((constant != NULL) && (constant->mBool))
  9453. mCurTypeInstance->mIncludeAllMethods = true;
  9454. }
  9455. }
  9456. }
  9457. else if (typeName == "System.AlignAttribute")
  9458. {
  9459. if (customAttribute.mCtorArgs.size() >= 1)
  9460. {
  9461. auto alignConstant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  9462. alignOverride = alignConstant->mInt32;
  9463. }
  9464. }
  9465. else if (typeName == "System.UnderlyingArrayAttribute")
  9466. {
  9467. if (customAttribute.mCtorArgs.size() >= 2)
  9468. {
  9469. auto typeConstant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  9470. auto sizeConstant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[1]);
  9471. if ((typeConstant != NULL) && (sizeConstant != NULL) && (typeConstant->mConstType == BfConstType_TypeOf))
  9472. {
  9473. underlyingArrayType = (BfType*)(intptr)typeConstant->mInt64;
  9474. underlyingArraySize = sizeConstant->mInt32;
  9475. }
  9476. }
  9477. }
  9478. }
  9479. }
  9480. }
  9481. // Checking to see if we're an attribute or not
  9482. void BfModule::ProcessCustomAttributeData()
  9483. {
  9484. bool isAttribute = false;
  9485. auto checkTypeInst = mCurTypeInstance->mBaseType;
  9486. while (checkTypeInst != NULL)
  9487. {
  9488. if (checkTypeInst->mTypeDef == mCompiler->mAttributeTypeDef)
  9489. isAttribute = true;
  9490. checkTypeInst = checkTypeInst->mBaseType;
  9491. }
  9492. if (!isAttribute)
  9493. return;
  9494. auto attributeData = new BfAttributeData();
  9495. bool hasCustomAttribute = false;
  9496. if (mCurTypeInstance->mCustomAttributes != NULL)
  9497. {
  9498. for (auto& customAttribute : mCurTypeInstance->mCustomAttributes->mAttributes)
  9499. {
  9500. if (customAttribute.mType->mTypeDef == mCompiler->mAttributeUsageAttributeTypeDef)
  9501. {
  9502. if (customAttribute.mCtorArgs.size() > 0)
  9503. {
  9504. auto constant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  9505. if ((constant != NULL) && (mBfIRBuilder->IsInt(constant->mTypeCode)))
  9506. attributeData->mAttributeTargets = (BfAttributeTargets)constant->mInt32;
  9507. }
  9508. for (auto& setProp : customAttribute.mSetProperties)
  9509. {
  9510. BfPropertyDef* propDef = setProp.mPropertyRef;
  9511. if (propDef->mName == "AllowMultiple")
  9512. {
  9513. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  9514. if (constant != NULL)
  9515. attributeData->mAllowMultiple = constant->mBool;
  9516. }
  9517. else if (propDef->mName == "Inherited")
  9518. {
  9519. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  9520. if (constant != NULL)
  9521. attributeData->mInherited = constant->mBool;
  9522. }
  9523. else if (propDef->mName == "ValidOn")
  9524. {
  9525. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  9526. if (constant != NULL)
  9527. attributeData->mAttributeTargets = (BfAttributeTargets)constant->mInt32;
  9528. }
  9529. }
  9530. hasCustomAttribute = true;
  9531. }
  9532. }
  9533. }
  9534. if ((!hasCustomAttribute) && (mCurTypeInstance->mBaseType->mAttributeData != NULL))
  9535. {
  9536. attributeData->mAttributeTargets = mCurTypeInstance->mBaseType->mAttributeData->mAttributeTargets;
  9537. attributeData->mInherited = mCurTypeInstance->mBaseType->mAttributeData->mInherited;
  9538. attributeData->mAllowMultiple = mCurTypeInstance->mBaseType->mAttributeData->mAllowMultiple;
  9539. }
  9540. mCurTypeInstance->mAttributeData = attributeData;
  9541. }
  9542. bool BfModule::TryGetConstString(BfIRConstHolder* constHolder, BfIRValue irValue, StringImpl& str)
  9543. {
  9544. auto constant = constHolder->GetConstant(irValue);
  9545. if (constant == NULL)
  9546. return false;
  9547. if (constant->mTypeCode != BfTypeCode_StringId)
  9548. return false;
  9549. int stringId = constant->mInt32;
  9550. BfStringPoolEntry* entry = NULL;
  9551. if (mContext->mStringObjectIdMap.TryGetValue(stringId, &entry))
  9552. {
  9553. str = entry->mString;
  9554. }
  9555. else
  9556. {
  9557. BF_DBG_FATAL("Failed to find string by id");
  9558. }
  9559. return true;
  9560. }
  9561. BfVariant BfModule::TypedValueToVariant(BfAstNode* refNode, const BfTypedValue& value, bool allowUndef)
  9562. {
  9563. BfVariant variant;
  9564. variant.mTypeCode = BfTypeCode_None;
  9565. BfType* primType = NULL;
  9566. if (value.mType->IsPrimitiveType())
  9567. primType = (BfPrimitiveType*)value.mType;
  9568. else if (value.mType->IsTypedPrimitive())
  9569. primType = value.mType->GetUnderlyingType();
  9570. if (primType)
  9571. {
  9572. auto constant = mBfIRBuilder->GetConstant(value.mValue);
  9573. if (constant != NULL)
  9574. {
  9575. if ((allowUndef) && (constant->mConstType == BfConstType_Undef))
  9576. {
  9577. variant.mUInt64 = 0;
  9578. variant.mTypeCode = BfTypeCode_Let;
  9579. return variant;
  9580. }
  9581. switch (constant->mTypeCode)
  9582. {
  9583. case BfTypeCode_Int8:
  9584. case BfTypeCode_UInt8:
  9585. case BfTypeCode_Int16:
  9586. case BfTypeCode_UInt16:
  9587. case BfTypeCode_Int32:
  9588. case BfTypeCode_UInt32:
  9589. case BfTypeCode_Int64:
  9590. case BfTypeCode_UInt64:
  9591. case BfTypeCode_IntPtr:
  9592. case BfTypeCode_UIntPtr:
  9593. case BfTypeCode_IntUnknown:
  9594. case BfTypeCode_UIntUnknown:
  9595. case BfTypeCode_Float:
  9596. case BfTypeCode_Double:
  9597. case BfTypeCode_Char8:
  9598. case BfTypeCode_Char16:
  9599. case BfTypeCode_Char32:
  9600. variant.mTypeCode = constant->mTypeCode;
  9601. variant.mInt64 = constant->mInt64;
  9602. break;
  9603. default:
  9604. if (refNode != NULL)
  9605. Fail("Invalid const expression type", refNode);
  9606. break;
  9607. }
  9608. }
  9609. }
  9610. return variant;
  9611. }
  9612. BfTypedValue BfModule::RemoveRef(BfTypedValue typedValue)
  9613. {
  9614. if ((typedValue.mType != NULL) && (typedValue.mType->IsRef()))
  9615. {
  9616. auto elementType = typedValue.mType->GetUnderlyingType();
  9617. if (typedValue.IsAddr())
  9618. {
  9619. if (elementType->IsValuelessType())
  9620. {
  9621. BF_ASSERT(!typedValue.mValue);
  9622. typedValue = BfTypedValue(typedValue.mValue, elementType, true);
  9623. }
  9624. else
  9625. typedValue = BfTypedValue(mBfIRBuilder->CreateLoad(typedValue.mValue), elementType, true);
  9626. }
  9627. else
  9628. typedValue = BfTypedValue(typedValue.mValue, elementType, true);
  9629. if (typedValue.mType->IsValuelessType())
  9630. {
  9631. BF_ASSERT(typedValue.mValue.IsFake());
  9632. }
  9633. }
  9634. return typedValue;
  9635. }
  9636. BfTypedValue BfModule::LoadValue(BfTypedValue typedValue, BfAstNode* refNode, bool isVolatile)
  9637. {
  9638. if (!typedValue.IsAddr())
  9639. return typedValue;
  9640. PopulateType(typedValue.mType);
  9641. if ((typedValue.mType->IsValuelessType()) || (typedValue.mType->IsVar()))
  9642. return BfTypedValue(mBfIRBuilder->GetFakeVal(), typedValue.mType, false);
  9643. if (typedValue.mValue.IsConst())
  9644. {
  9645. auto constantValue = mBfIRBuilder->GetConstant(typedValue.mValue);
  9646. if (constantValue != NULL)
  9647. {
  9648. if (constantValue->mConstType == BfConstType_GlobalVar)
  9649. {
  9650. auto globalVar = (BfGlobalVar*)constantValue;
  9651. if (globalVar->mName[0] == '#')
  9652. {
  9653. BfTypedValue result = GetCompilerFieldValue(globalVar->mName);
  9654. if (result)
  9655. return result;
  9656. return GetDefaultTypedValue(typedValue.mType);
  9657. }
  9658. }
  9659. }
  9660. }
  9661. BfIRValue loadedVal = typedValue.mValue;
  9662. if (loadedVal)
  9663. {
  9664. if (typedValue.mType->IsVar())
  9665. {
  9666. return BfTypedValue(loadedVal, typedValue.mType, false);
  9667. }
  9668. /*if (isVolatile)
  9669. mBfIRBuilder->CreateFence(BfIRFenceType_AcquireRelease);*/
  9670. PopulateType(typedValue.mType, BfPopulateType_Data);
  9671. loadedVal = mBfIRBuilder->CreateAlignedLoad(loadedVal, std::max(1, (int)typedValue.mType->mAlign), isVolatile);
  9672. }
  9673. return BfTypedValue(loadedVal, typedValue.mType, false);
  9674. }
  9675. BfTypedValue BfModule::LoadOrAggregateValue(BfTypedValue typedValue)
  9676. {
  9677. if (typedValue.IsSplat())
  9678. return AggregateSplat(typedValue);
  9679. if (typedValue.IsAddr())
  9680. return LoadValue(typedValue);
  9681. return typedValue;
  9682. }
  9683. BfTypedValue BfModule::AggregateSplat(BfTypedValue typedValue, BfIRValue* valueArrPtr)
  9684. {
  9685. if (!typedValue.IsSplat())
  9686. return typedValue;
  9687. if (typedValue.mType->IsValuelessType())
  9688. return typedValue;
  9689. int elementIdx = 0;
  9690. auto _ExtractValue = [&](BfType* checkType)
  9691. {
  9692. if (valueArrPtr != NULL)
  9693. return valueArrPtr[elementIdx++];
  9694. return ExtractSplatValue(typedValue, elementIdx++, checkType);
  9695. };
  9696. std::function<BfIRValue(BfType*)> checkTypeLambda = [&](BfType* checkType)
  9697. {
  9698. if (checkType->IsStruct())
  9699. {
  9700. BfIRValue curValue = mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(checkType, BfIRPopulateType_Full));
  9701. auto checkTypeInstance = checkType->ToTypeInstance();
  9702. if (checkTypeInstance->mBaseType != NULL)
  9703. {
  9704. mBfIRBuilder->PopulateType(checkTypeInstance->mBaseType, BfIRPopulateType_Full);
  9705. BfIRValue baseValue = checkTypeLambda(checkTypeInstance->mBaseType);
  9706. curValue = mBfIRBuilder->CreateInsertValue(curValue, baseValue, 0);
  9707. }
  9708. if (checkTypeInstance->mIsUnion)
  9709. {
  9710. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  9711. if (!unionInnerType->IsValuelessType())
  9712. {
  9713. BfIRValue fieldValue = checkTypeLambda(unionInnerType);
  9714. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, 1);
  9715. }
  9716. if (checkTypeInstance->IsEnum())
  9717. {
  9718. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  9719. BfIRValue fieldValue = checkTypeLambda(dscrType);
  9720. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, 2);
  9721. }
  9722. }
  9723. else
  9724. {
  9725. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  9726. {
  9727. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  9728. if (fieldInstance->mDataIdx >= 0)
  9729. {
  9730. BfIRValue fieldValue = checkTypeLambda(fieldInstance->GetResolvedType());
  9731. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, fieldInstance->mDataIdx);
  9732. }
  9733. }
  9734. }
  9735. return curValue;
  9736. }
  9737. else if (checkType->IsMethodRef())
  9738. {
  9739. BfMethodRefType* methodRefType = (BfMethodRefType*)checkType;
  9740. BfIRValue curValue = mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(checkType, BfIRPopulateType_Full));
  9741. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  9742. {
  9743. BfIRValue fieldValue;
  9744. auto checkType = methodRefType->GetCaptureType(dataIdx);
  9745. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  9746. {
  9747. fieldValue = checkTypeLambda(checkType);
  9748. }
  9749. else
  9750. {
  9751. fieldValue = _ExtractValue(checkType);
  9752. }
  9753. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, dataIdx);
  9754. }
  9755. return curValue;
  9756. }
  9757. else if (!checkType->IsValuelessType())
  9758. {
  9759. return _ExtractValue(checkType);
  9760. }
  9761. return BfIRValue();
  9762. };
  9763. BfIRValue value = checkTypeLambda(typedValue.mType);
  9764. return BfTypedValue(value, typedValue.mType, typedValue.IsThis() ? BfTypedValueKind_ThisValue : BfTypedValueKind_Value);
  9765. }
  9766. void BfModule::AggregateSplatIntoAddr(BfTypedValue typedValue, BfIRValue addrVal)
  9767. {
  9768. if (!typedValue.IsSplat())
  9769. return;
  9770. if (typedValue.mType->IsValuelessType())
  9771. return;
  9772. /*static int sCallIdx = 0;
  9773. if (!mCompiler->mIsResolveOnly)
  9774. sCallIdx++;
  9775. int callIdx = sCallIdx;*/
  9776. int elementIdx = 0;
  9777. std::function<void(BfType*, BfIRValue)> checkTypeLambda = [&](BfType* checkType, BfIRValue curAddrVal)
  9778. {
  9779. if (checkType->IsStruct())
  9780. {
  9781. auto checkTypeInstance = checkType->ToTypeInstance();
  9782. if (checkTypeInstance->mBaseType != NULL)
  9783. {
  9784. mBfIRBuilder->PopulateType(checkTypeInstance->mBaseType);
  9785. auto baseAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 0);
  9786. checkTypeLambda(checkTypeInstance->mBaseType, baseAddrVal);
  9787. }
  9788. if (checkTypeInstance->mIsUnion)
  9789. {
  9790. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  9791. if (!unionInnerType->IsValuelessType())
  9792. {
  9793. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 1);
  9794. checkTypeLambda(unionInnerType, fieldAddrVal);
  9795. }
  9796. if (checkTypeInstance->IsEnum())
  9797. {
  9798. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  9799. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 2);
  9800. checkTypeLambda(dscrType, fieldAddrVal);
  9801. }
  9802. }
  9803. else
  9804. {
  9805. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  9806. {
  9807. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  9808. if (fieldInstance->mDataIdx >= 0)
  9809. {
  9810. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, fieldInstance->mDataIdx);
  9811. checkTypeLambda(fieldInstance->mResolvedType, fieldAddrVal);
  9812. }
  9813. }
  9814. }
  9815. }
  9816. else if (checkType->IsMethodRef())
  9817. {
  9818. BfMethodRefType* methodRefType = (BfMethodRefType*)checkType;
  9819. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  9820. {
  9821. auto dataType = methodRefType->GetCaptureType(dataIdx);
  9822. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, dataIdx);
  9823. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  9824. {
  9825. checkTypeLambda(methodRefType->GetCaptureType(dataIdx), fieldAddrVal);
  9826. }
  9827. else
  9828. {
  9829. // static int sItrCount = 0;
  9830. // sItrCount++;
  9831. // int curItr = sItrCount;
  9832. // if (curItr == 1)
  9833. // {
  9834. // NOP;
  9835. // }
  9836. auto val = ExtractSplatValue(typedValue, elementIdx++, dataType);
  9837. mBfIRBuilder->CreateStore(val, fieldAddrVal);
  9838. }
  9839. }
  9840. }
  9841. else if (!checkType->IsValuelessType())
  9842. {
  9843. auto val = ExtractSplatValue(typedValue, elementIdx++, checkType);
  9844. mBfIRBuilder->CreateStore(val, curAddrVal);
  9845. }
  9846. };
  9847. checkTypeLambda(typedValue.mType, addrVal);
  9848. }
  9849. BfTypedValue BfModule::MakeAddressable(BfTypedValue typedVal)
  9850. {
  9851. bool wasReadOnly = typedVal.IsReadOnly();
  9852. if ((typedVal.mType->IsValueType()) &&
  9853. (!typedVal.mType->IsValuelessType()))
  9854. {
  9855. wasReadOnly = true; // Any non-addr is implicitly read-only
  9856. //static int gCallIdx = 0;
  9857. if (typedVal.IsAddr())
  9858. return typedVal;
  9859. BfType* type = typedVal.mType;
  9860. PopulateType(type);
  9861. auto tempVar = CreateAlloca(type);
  9862. if (typedVal.IsSplat())
  9863. AggregateSplatIntoAddr(typedVal, tempVar);
  9864. else
  9865. mBfIRBuilder->CreateAlignedStore(typedVal.mValue, tempVar, type->mAlign);
  9866. return BfTypedValue(tempVar, type,
  9867. typedVal.IsThis() ?
  9868. (wasReadOnly ? BfTypedValueKind_ReadOnlyThisAddr : BfTypedValueKind_ThisAddr) :
  9869. (wasReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr));
  9870. }
  9871. return LoadValue(typedVal);
  9872. }
  9873. BfTypedValue BfModule::RemoveReadOnly(BfTypedValue typedValue)
  9874. {
  9875. if (typedValue.mKind == BfTypedValueKind_ReadOnlyAddr)
  9876. typedValue.mKind = BfTypedValueKind_Addr;
  9877. return typedValue;
  9878. }
  9879. BfIRValue BfModule::ExtractSplatValue(BfTypedValue typedValue, int componentIdx, BfType* wantType, bool* isAddr)
  9880. {
  9881. BfIRValue val;
  9882. if (typedValue.mValue.IsArg())
  9883. {
  9884. val = mBfIRBuilder->GetArgument(typedValue.mValue.mId + componentIdx);
  9885. if (isAddr != NULL)
  9886. {
  9887. if (wantType != NULL)
  9888. *isAddr = wantType->IsComposite();
  9889. else
  9890. *isAddr = false;
  9891. }
  9892. else if (wantType->IsComposite())
  9893. val = mBfIRBuilder->CreateLoad(val);
  9894. }
  9895. if (!val)
  9896. {
  9897. auto checkMethodState = mCurMethodState;
  9898. while (checkMethodState != NULL)
  9899. {
  9900. for (int idx = 0; idx < (int)checkMethodState->mSplatDecompAddrs.size(); idx++)
  9901. {
  9902. auto decompAddr = checkMethodState->mSplatDecompAddrs[idx];
  9903. if (decompAddr == typedValue.mValue)
  9904. {
  9905. val = checkMethodState->mSplatDecompAddrs[idx + componentIdx];
  9906. if ((wantType->IsComposite()) && (typedValue.mType->IsMethodRef()))
  9907. {
  9908. // This is really backing for a POINTER to a composite inside a methodRef
  9909. val = mBfIRBuilder->CreateLoad(val);
  9910. }
  9911. if ((isAddr != NULL) && (typedValue.mKind != BfTypedValueKind_SplatHead_NeedsCasting))
  9912. {
  9913. *isAddr = true;
  9914. return val;
  9915. }
  9916. else
  9917. {
  9918. val = mBfIRBuilder->CreateLoad(val);
  9919. break;
  9920. }
  9921. }
  9922. }
  9923. if (val)
  9924. break;
  9925. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mCapturing))
  9926. {
  9927. BF_ASSERT(mBfIRBuilder->mIgnoreWrites);
  9928. return mBfIRBuilder->GetFakeVal();
  9929. }
  9930. checkMethodState = checkMethodState->mPrevMethodState;
  9931. }
  9932. }
  9933. if (val)
  9934. {
  9935. if (typedValue.mKind == BfTypedValueKind_SplatHead_NeedsCasting)
  9936. {
  9937. BF_ASSERT(wantType != NULL);
  9938. if (wantType != NULL)
  9939. return mBfIRBuilder->CreateBitCast(val, mBfIRBuilder->MapType(wantType));
  9940. }
  9941. return val;
  9942. }
  9943. BFMODULE_FATAL(this, "Splat not found");
  9944. return BfIRValue();
  9945. }
  9946. BfTypedValue BfModule::ExtractValue(BfTypedValue typedValue, BfFieldInstance* fieldInstance, int fieldIdx)
  9947. {
  9948. int useFieldIdx = fieldIdx;
  9949. BfType* fieldType = NULL;
  9950. if (fieldInstance != NULL)
  9951. {
  9952. fieldType = fieldInstance->mResolvedType;
  9953. if (typedValue.mType->IsUnion())
  9954. {
  9955. if (fieldIdx == 1)
  9956. {
  9957. if (typedValue.IsSplat())
  9958. {
  9959. BfTypedValue innerVal = typedValue;
  9960. innerVal.mType = fieldType;
  9961. return innerVal;
  9962. }
  9963. }
  9964. }
  9965. }
  9966. else
  9967. {
  9968. if (typedValue.mType->IsPayloadEnum())
  9969. {
  9970. auto typeInst = typedValue.mType->ToTypeInstance();
  9971. if (fieldIdx == 1)
  9972. fieldType = typeInst->GetUnionInnerType();
  9973. else if (fieldIdx == 2)
  9974. {
  9975. fieldType = typeInst->GetDiscriminatorType(&useFieldIdx);
  9976. }
  9977. }
  9978. else if (typedValue.mType->IsUnion())
  9979. {
  9980. if (fieldIdx == 1)
  9981. {
  9982. fieldType = typedValue.mType->ToTypeInstance()->GetUnionInnerType();
  9983. if (typedValue.IsSplat())
  9984. {
  9985. BfTypedValue innerVal = typedValue;
  9986. innerVal.mType = fieldType;
  9987. return innerVal;
  9988. }
  9989. }
  9990. }
  9991. }
  9992. BF_ASSERT(typedValue.mType->IsStruct());
  9993. if (typedValue.IsSplat())
  9994. {
  9995. if (typedValue.mType->IsPayloadEnum())
  9996. {
  9997. if (fieldIdx == 1)
  9998. {
  9999. // Payload
  10000. auto typeInst = typedValue.mType->ToTypeInstance();
  10001. auto unionInnerType = typeInst->GetUnionInnerType();
  10002. bool isAddr = false;
  10003. BfIRValue irVal = ExtractSplatValue(typedValue, 0, unionInnerType, &isAddr);
  10004. return BfTypedValue(irVal, unionInnerType, BfTypedValueKind_SplatHead);
  10005. }
  10006. if (fieldIdx == 2)
  10007. {
  10008. // Discriminator
  10009. auto typeInst = typedValue.mType->ToTypeInstance();
  10010. auto unionInnerType = typeInst->GetUnionInnerType();
  10011. auto dscrType = typeInst->GetDiscriminatorType();
  10012. int argIdx = typedValue.mValue.mId;
  10013. int componentIdx = 0;
  10014. BfTypeUtils::SplatIterate([&](BfType* checkType) { componentIdx++; }, unionInnerType);
  10015. bool isAddr;
  10016. BfIRValue irVal = ExtractSplatValue(typedValue, componentIdx, dscrType, &isAddr);
  10017. return BfTypedValue(irVal, dscrType, isAddr);
  10018. }
  10019. }
  10020. int componentIdx = 0;
  10021. BfTypedValue retVal;
  10022. BfFieldInstance* wantFieldInstance = fieldInstance;
  10023. std::function<void(BfType*)> checkTypeLambda = [&](BfType* checkType)
  10024. {
  10025. if (checkType->IsStruct())
  10026. {
  10027. auto checkTypeInstance = checkType->ToTypeInstance();
  10028. if ((checkType->IsUnion()) || (checkType->IsEnum()))
  10029. {
  10030. //TODO: Why did we have this removed? It messed up an extraction from a nullable splattable
  10031. fieldType = checkTypeInstance->GetUnionInnerType();
  10032. checkTypeLambda(fieldType);
  10033. if (checkType->IsEnum())
  10034. {
  10035. // Past discriminator...
  10036. componentIdx++;
  10037. }
  10038. return;
  10039. }
  10040. if (checkTypeInstance->mBaseType != NULL)
  10041. checkTypeLambda(checkTypeInstance->mBaseType);
  10042. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  10043. {
  10044. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  10045. if (fieldInstance == wantFieldInstance)
  10046. {
  10047. bool isAddr = false;
  10048. BfIRValue val = ExtractSplatValue(typedValue, componentIdx, fieldInstance->mResolvedType, &isAddr);
  10049. retVal = BfTypedValue(val, fieldInstance->mResolvedType,
  10050. fieldInstance->mResolvedType->IsComposite() ? BfTypedValueKind_SplatHead :
  10051. isAddr ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Value);
  10052. if ((retVal.IsAddr()) && (!fieldInstance->mResolvedType->IsValueType()))
  10053. {
  10054. retVal = LoadValue(retVal);
  10055. }
  10056. break;
  10057. }
  10058. if (fieldInstance->mDataIdx >= 0)
  10059. checkTypeLambda(fieldInstance->GetResolvedType());
  10060. }
  10061. }
  10062. else if (!checkType->IsValuelessType())
  10063. {
  10064. componentIdx++;
  10065. //argIdx++;
  10066. }
  10067. };
  10068. checkTypeLambda(typedValue.mType);
  10069. BF_ASSERT(retVal);
  10070. return retVal;
  10071. }
  10072. if (typedValue.IsAddr())
  10073. {
  10074. BF_ASSERT(fieldType != NULL);
  10075. auto valRef = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, useFieldIdx);
  10076. return BfTypedValue(valRef, fieldType, BfTypedValueKind_ReadOnlyAddr);
  10077. }
  10078. else
  10079. {
  10080. BF_ASSERT(fieldType != NULL);
  10081. return BfTypedValue(mBfIRBuilder->CreateExtractValue(typedValue.mValue, useFieldIdx), fieldType, BfTypedValueKind_Value);
  10082. }
  10083. }
  10084. BfIRValue BfModule::ExtractValue(BfTypedValue typedValue, int dataIdx)
  10085. {
  10086. if (typedValue.IsAddr())
  10087. {
  10088. auto addrVal = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, dataIdx);
  10089. return mBfIRBuilder->CreateLoad(addrVal);
  10090. }
  10091. return mBfIRBuilder->CreateExtractValue(typedValue.mValue, dataIdx);
  10092. }
  10093. BfIRValue BfModule::CreateIndexedValue(BfType* elementType, BfIRValue value, BfIRValue indexValue, bool isElementIndex)
  10094. {
  10095. if (elementType->IsSizeAligned())
  10096. {
  10097. if (isElementIndex)
  10098. return mBfIRBuilder->CreateInBoundsGEP(value, GetConstValue(0), indexValue);
  10099. else
  10100. return mBfIRBuilder->CreateInBoundsGEP(value, indexValue);
  10101. }
  10102. auto ptrType = CreatePointerType(elementType);
  10103. auto ofsVal = mBfIRBuilder->CreateNumericCast(indexValue, true, BfTypeCode_IntPtr);
  10104. auto ofsScaledVal = mBfIRBuilder->CreateMul(ofsVal, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, elementType->GetStride()));
  10105. auto i8PtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8));
  10106. BfIRValue origPtrValue = mBfIRBuilder->CreateBitCast(value, i8PtrType);
  10107. BfIRValue newPtrValue = mBfIRBuilder->CreateInBoundsGEP(origPtrValue, ofsScaledVal);
  10108. return mBfIRBuilder->CreateBitCast(newPtrValue, mBfIRBuilder->MapType(ptrType));
  10109. }
  10110. BfIRValue BfModule::CreateIndexedValue(BfType* elementType, BfIRValue value, int indexValue, bool isElementIndex)
  10111. {
  10112. if (elementType->IsSizeAligned())
  10113. {
  10114. if (isElementIndex)
  10115. return mBfIRBuilder->CreateInBoundsGEP(value, 0, indexValue);
  10116. else
  10117. return mBfIRBuilder->CreateInBoundsGEP(value, indexValue);
  10118. }
  10119. return CreateIndexedValue(elementType, value, GetConstValue(indexValue), isElementIndex);
  10120. }
  10121. bool BfModule::CheckModifyValue(BfTypedValue& typedValue, BfAstNode* refNode, const char* modifyType)
  10122. {
  10123. if (modifyType == NULL)
  10124. modifyType = "modify";
  10125. if (typedValue.mType->IsVar())
  10126. return true;
  10127. if (typedValue.IsReadOnly())
  10128. {
  10129. Fail(StrFormat("Cannot %s read-only variable", modifyType), refNode);
  10130. return false;
  10131. }
  10132. if ((!typedValue.IsAddr()) && (!typedValue.mType->IsValuelessType()))
  10133. {
  10134. Fail(StrFormat("Cannot %s value", modifyType), refNode);
  10135. return false;
  10136. }
  10137. if (typedValue.mKind == BfTypedValueKind_RestrictedTempAddr)
  10138. {
  10139. Fail(StrFormat("Cannot %s temporary value", modifyType), refNode);
  10140. return false;
  10141. }
  10142. return true;
  10143. }
  10144. bool BfModule::CompareMethodSignatures(BfMethodInstance* methodA, BfMethodInstance* methodB)
  10145. {
  10146. // If one is an interface and the other is an impl, B is the impl
  10147. auto implOwner = methodB->GetOwner();
  10148. if (methodA->mMethodDef->mIsLocalMethod)
  10149. {
  10150. int sepPosA = (int)BF_MIN(methodA->mMethodDef->mName.IndexOf('@'), methodA->mMethodDef->mName.length());
  10151. int sepPosB = (int)BF_MIN(methodB->mMethodDef->mName.IndexOf('@'), methodB->mMethodDef->mName.length());
  10152. if (sepPosA != sepPosB)
  10153. return false;
  10154. if (strncmp(methodA->mMethodDef->mName.c_str(), methodB->mMethodDef->mName.c_str(), sepPosA) != 0)
  10155. return false;
  10156. }
  10157. else if (methodA->mMethodDef->mName != methodB->mMethodDef->mName)
  10158. return false;
  10159. if (methodA->mMethodDef->mCheckedKind != methodB->mMethodDef->mCheckedKind)
  10160. return false;
  10161. if ((methodA->mMethodDef->mMethodType == BfMethodType_Mixin) != (methodB->mMethodDef->mMethodType == BfMethodType_Mixin))
  10162. return false;
  10163. if (methodA->mMethodDef->mMethodType == BfMethodType_Ctor)
  10164. {
  10165. if (methodA->mMethodDef->mIsStatic != methodB->mMethodDef->mIsStatic)
  10166. return false;
  10167. }
  10168. if (methodA->mMethodDef->mMethodType == BfMethodType_Operator)
  10169. {
  10170. if (methodB->mMethodDef->mMethodType != BfMethodType_Operator)
  10171. return false;
  10172. auto operatorA = (BfOperatorDef*)methodA->mMethodDef;
  10173. auto operatorB = (BfOperatorDef*)methodB->mMethodDef;
  10174. if (operatorA->mOperatorDeclaration->mUnaryOp != operatorB->mOperatorDeclaration->mUnaryOp)
  10175. return false;
  10176. if (operatorA->mOperatorDeclaration->mBinOp != operatorB->mOperatorDeclaration->mBinOp)
  10177. return false;
  10178. if (operatorA->mOperatorDeclaration->mAssignOp != operatorB->mOperatorDeclaration->mAssignOp)
  10179. return false;
  10180. if (operatorA->mOperatorDeclaration->mIsConvOperator)
  10181. {
  10182. if (!BfTypeUtils::TypeEquals(methodA->mReturnType, methodB->mReturnType, implOwner))
  10183. return false;
  10184. }
  10185. }
  10186. int implicitParamCountA = methodA->GetImplicitParamCount();
  10187. int implicitParamCountB = methodB->GetImplicitParamCount();
  10188. if (methodA->GetParamCount() - implicitParamCountA != methodB->GetParamCount() - implicitParamCountB)
  10189. return false;
  10190. if (methodA->mHadGenericDelegateParams != methodB->mHadGenericDelegateParams)
  10191. return false;
  10192. for (int paramIdx = 0; paramIdx < (int)methodA->GetParamCount() - implicitParamCountA; paramIdx++)
  10193. {
  10194. if ((!BfTypeUtils::TypeEquals(methodA->GetParamType(paramIdx + implicitParamCountA), methodB->GetParamType(paramIdx + implicitParamCountB), implOwner)) ||
  10195. (methodA->GetParamKind(paramIdx + implicitParamCountA) != methodB->GetParamKind(paramIdx + implicitParamCountB)))
  10196. return false;
  10197. }
  10198. // Compare generic params. Generic params are part of the method signature here
  10199. if (methodA->GetNumGenericParams() != methodB->GetNumGenericParams())
  10200. return false;
  10201. for (int genericParamIdx = 0; genericParamIdx < (int)methodA->GetNumGenericParams(); genericParamIdx++)
  10202. {
  10203. auto genericParamA = methodA->mMethodInfoEx->mGenericParams[genericParamIdx];
  10204. auto genericParamB = methodB->mMethodInfoEx->mGenericParams[genericParamIdx];
  10205. if (genericParamA->mGenericParamFlags != genericParamB->mGenericParamFlags)
  10206. return false;
  10207. if (genericParamA->mTypeConstraint != genericParamB->mTypeConstraint)
  10208. return false;
  10209. if (genericParamA->mInterfaceConstraints.size() != genericParamB->mInterfaceConstraints.size())
  10210. return false;
  10211. for (int interfaceIdx = 0; interfaceIdx < (int)genericParamA->mInterfaceConstraints.size(); interfaceIdx++)
  10212. if (genericParamA->mInterfaceConstraints[interfaceIdx] != genericParamB->mInterfaceConstraints[interfaceIdx])
  10213. return false;
  10214. }
  10215. return true;
  10216. }
  10217. bool BfModule::StrictCompareMethodSignatures(BfMethodInstance* methodA, BfMethodInstance* methodB)
  10218. {
  10219. if (!CompareMethodSignatures(methodA, methodB))
  10220. return false;
  10221. if (methodA->mReturnType != methodB->mReturnType)
  10222. return false;
  10223. if (methodA->mMethodDef->mIsStatic != methodB->mMethodDef->mIsStatic)
  10224. return false;
  10225. return true;
  10226. }
  10227. bool BfModule::IsCompatibleInterfaceMethod(BfMethodInstance* iMethodInst, BfMethodInstance* methodInstance)
  10228. {
  10229. if (iMethodInst->mMethodDef->mName != methodInstance->mMethodDef->mName)
  10230. return false;
  10231. if (iMethodInst->mMethodDef->mIsOperator != methodInstance->mMethodDef->mIsOperator)
  10232. return false;
  10233. if (iMethodInst->mMethodDef->mIsOperator)
  10234. {
  10235. auto iOperatorDef = (BfOperatorDef*)iMethodInst->mMethodDef;
  10236. auto operatorDef = (BfOperatorDef*)methodInstance->mMethodDef;
  10237. if (iOperatorDef->mOperatorDeclaration->mUnaryOp != operatorDef->mOperatorDeclaration->mUnaryOp)
  10238. return false;
  10239. if (iOperatorDef->mOperatorDeclaration->mBinOp != operatorDef->mOperatorDeclaration->mBinOp)
  10240. return false;
  10241. }
  10242. if (iMethodInst->GetParamCount() != methodInstance->GetParamCount())
  10243. return false;
  10244. for (int paramIdx = 0; paramIdx < (int)iMethodInst->GetParamCount(); paramIdx++)
  10245. {
  10246. if (iMethodInst->GetParamKind(paramIdx) != methodInstance->GetParamKind(paramIdx))
  10247. return false;
  10248. BfType* iParamType = iMethodInst->GetParamType(paramIdx);
  10249. BfType* methodParamType = methodInstance->GetParamType(paramIdx);
  10250. if (iParamType->IsSelf())
  10251. {
  10252. if (methodParamType != methodInstance->GetOwner())
  10253. return false;
  10254. }
  10255. else if (!iParamType->IsGenericParam())
  10256. {
  10257. if (methodParamType != iParamType)
  10258. return false;
  10259. }
  10260. else
  10261. {
  10262. if (!methodParamType->IsGenericParam())
  10263. return false;
  10264. auto genericParamType = (BfGenericParamType*)methodParamType;
  10265. if (genericParamType->mGenericParamKind == BfGenericParamKind_Type)
  10266. return false;
  10267. auto genericParam = methodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  10268. bool hadInterface = false;
  10269. for (auto interfaceConstraint : genericParam->mInterfaceConstraints)
  10270. if (interfaceConstraint == iParamType)
  10271. hadInterface = true;
  10272. if (!hadInterface)
  10273. return false;
  10274. }
  10275. }
  10276. return true;
  10277. }
  10278. void BfModule::AddMethodReference(const BfMethodRef& methodRef, BfGetMethodInstanceFlags flags)
  10279. {
  10280. BfMethodInstance* methodInstance = methodRef;
  10281. if ((mCurTypeInstance != NULL) && (!mCompiler->IsAutocomplete()))
  10282. {
  10283. auto methodInstanceGroup = methodInstance->mMethodInstanceGroup;
  10284. if ((methodInstance->IsSpecializedGenericMethod()) || (methodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_AlwaysInclude))
  10285. {
  10286. BF_ASSERT(!methodRef.mTypeInstance->IsFunction());
  10287. // This ensures we rebuild - there are some cases where we get a method reference but never call it, so this is required here
  10288. AddDependency(methodInstance->GetOwner(), mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  10289. BfMethodRef methodRef = methodInstance;
  10290. BfSpecializedMethodRefInfo* specializedMethodRefInfo = NULL;
  10291. bool isNew = mCurTypeInstance->mSpecializedMethodReferences.TryAdd(methodRef, NULL, &specializedMethodRefInfo);
  10292. if (((flags & BfGetMethodInstanceFlag_Unreified) == 0) &&
  10293. ((flags & BfGetMethodInstanceFlag_NoForceReification) == 0) &&
  10294. (mIsReified))
  10295. {
  10296. specializedMethodRefInfo->mHasReifiedRef = true;
  10297. }
  10298. }
  10299. }
  10300. }
  10301. BfModuleMethodInstance BfModule::ReferenceExternalMethodInstance(BfMethodInstance* methodInstance, BfGetMethodInstanceFlags flags)
  10302. {
  10303. if ((flags & BfGetMethodInstanceFlag_ResultNotUsed) != 0)
  10304. return BfModuleMethodInstance(methodInstance, BfIRValue());
  10305. if (mBfIRBuilder == NULL)
  10306. return BfModuleMethodInstance(methodInstance, BfIRValue());
  10307. if (methodInstance->GetOwner()->IsFunction())
  10308. {
  10309. // No actual ref needed- not an actual generated function
  10310. return BfModuleMethodInstance(methodInstance, BfIRValue());
  10311. }
  10312. bool isGenFunction = methodInstance->mMethodInstanceGroup->mMethodIdx < 0;
  10313. if (!isGenFunction)
  10314. AddMethodReference(methodInstance, flags);
  10315. if ((mBfIRBuilder->mIgnoreWrites) || ((flags & BfGetMethodInstanceFlag_Unreified) != 0))
  10316. return BfModuleMethodInstance(methodInstance, mBfIRBuilder->GetFakeVal());
  10317. if (mCompiler->IsSkippingExtraResolveChecks())
  10318. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  10319. if (methodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)
  10320. {
  10321. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  10322. }
  10323. bool isInlined = (methodInstance->mAlwaysInline) || ((flags & BfGetMethodInstanceFlag_ForceInline) != 0);
  10324. BfMethodRef methodRef = methodInstance;
  10325. if (isInlined)
  10326. methodRef.mMethodRefFlags = (BfMethodRefFlags)(methodRef.mMethodRefFlags | BfMethodRefFlag_AlwaysInclude);
  10327. else
  10328. methodRef.mMethodRefFlags = BfMethodRefFlag_None;
  10329. if (!isGenFunction)
  10330. {
  10331. BfIRValue* irFuncPtr = NULL;
  10332. if (mFuncReferences.TryGetValue(methodRef, &irFuncPtr))
  10333. return BfModuleMethodInstance(methodInstance, *irFuncPtr);
  10334. }
  10335. if (mAwaitingInitFinish)
  10336. FinishInit();
  10337. BfIRValue func = CreateFunctionFrom(methodInstance, isGenFunction, isInlined);
  10338. if (!isGenFunction)
  10339. mFuncReferences[methodRef] = func;
  10340. BfLogSysM("Adding func reference. Module:%p MethodInst:%p NewLLVMFunc:%d OldLLVMFunc:%d\n", this, methodInstance, func.mId, methodInstance->mIRFunction.mId);
  10341. if ((isInlined) && (!mIsScratchModule) && ((flags & BfGetMethodInstanceFlag_NoInline) == 0))
  10342. {
  10343. // We can't just add a dependency to mCurTypeInstance because we may have nested inlined functions, and
  10344. // mCurTypeInstance will just reflect the owner of the method currently being inlined, not the top-level
  10345. // type instance
  10346. // Be smarter about this if we ever insert a lot of type instances into a single module - track in a field
  10347. BF_ASSERT(mOwnedTypeInstances.size() <= 1);
  10348. for (auto ownedTypeInst : mOwnedTypeInstances)
  10349. AddDependency(methodInstance->GetOwner(), ownedTypeInst, BfDependencyMap::DependencyFlag_InlinedCall);
  10350. if ((!mCompiler->mIsResolveOnly) && (mIsReified) && (!methodInstance->mIsUnspecialized))
  10351. {
  10352. mIncompleteMethodCount++;
  10353. BfInlineMethodRequest* inlineMethodRequest = mContext->mInlineMethodWorkList.Alloc();
  10354. inlineMethodRequest->mType = methodInstance->GetOwner();
  10355. inlineMethodRequest->mFromModule = this;
  10356. inlineMethodRequest->mFunc = func;
  10357. inlineMethodRequest->mFromModuleRevision = mRevision;
  10358. inlineMethodRequest->mMethodInstance = methodInstance;
  10359. BF_ASSERT(mIsModuleMutable);
  10360. BfLogSysM("mInlineMethodWorkList %p for method %p in module %p in ReferenceExternalMethodInstance\n", inlineMethodRequest, methodInstance, this);
  10361. }
  10362. }
  10363. return BfModuleMethodInstance(methodInstance, func);
  10364. }
  10365. BfModule* BfModule::GetOrCreateMethodModule(BfMethodInstance* methodInstance)
  10366. {
  10367. BfTypeInstance* typeInst = methodInstance->mMethodInstanceGroup->mOwner;
  10368. if (mBfIRBuilder == NULL)
  10369. {
  10370. // To allow for custom attribute data
  10371. PrepareForIRWriting(typeInst);
  10372. }
  10373. BfModule* declareModule = this;
  10374. // Get to the optionless branch head -- but this could still be a specialized method module, not the true root
  10375. while ((declareModule->mParentModule != NULL) && (!declareModule->mIsSpecializedMethodModuleRoot))
  10376. declareModule = declareModule->mParentModule;
  10377. // Check for attributes
  10378. if (typeInst == mContext->mBfObjectType)
  10379. {
  10380. auto methodDecl = methodInstance->mMethodDef->GetMethodDeclaration();
  10381. if (methodDecl != NULL)
  10382. {
  10383. auto attributesDirective = methodDecl->mAttributes;
  10384. if ((attributesDirective != NULL) && (mCompiler->mResolvePassData != NULL) &&
  10385. (attributesDirective->IsFromParser(mCompiler->mResolvePassData->mParser)) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  10386. {
  10387. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(attributesDirective);
  10388. }
  10389. }
  10390. }
  10391. else
  10392. {
  10393. // Only allow attributes on System.Object methods that can be handled inside the DefBuilder
  10394. GetMethodCustomAttributes(methodInstance);
  10395. }
  10396. BF_ASSERT(mModuleOptions == NULL);
  10397. if (methodInstance->GetCustomAttributes() != NULL)
  10398. {
  10399. auto project = typeInst->mTypeDef->mProject;
  10400. BfModuleOptions moduleOptions = declareModule->GetModuleOptions();
  10401. BfModuleOptions wantOptions = moduleOptions;
  10402. auto typeOptions = mSystem->GetTypeOptions(typeInst->mTypeOptionsIdx);
  10403. if (typeOptions != NULL)
  10404. {
  10405. wantOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)wantOptions.mOptLevel, (int)typeOptions->mOptimizationLevel);
  10406. wantOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mSIMDSetting, typeOptions->mSIMDSetting);
  10407. wantOptions.mEmitDebugInfo = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mEmitDebugInfo, typeOptions->mEmitDebugInfo);
  10408. }
  10409. if (!mCompiler->mAttributeTypeOptionMap.IsEmpty())
  10410. {
  10411. StringT<128> attrName;
  10412. for (auto& customAttrs : methodInstance->GetCustomAttributes()->mAttributes)
  10413. {
  10414. attrName.Clear();
  10415. customAttrs.mType->mTypeDef->mFullName.ToString(attrName);
  10416. Array<int>* arrPtr;
  10417. if (mCompiler->mAttributeTypeOptionMap.TryGetValue(attrName, &arrPtr))
  10418. {
  10419. for (auto optionsIdx : *arrPtr)
  10420. {
  10421. auto& typeOptions = mCompiler->mSystem->mTypeOptions[optionsIdx];
  10422. wantOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)wantOptions.mOptLevel, (int)typeOptions.mOptimizationLevel);
  10423. wantOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mSIMDSetting, typeOptions.mSIMDSetting);
  10424. wantOptions.mEmitDebugInfo = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mEmitDebugInfo, typeOptions.mEmitDebugInfo);
  10425. }
  10426. }
  10427. }
  10428. }
  10429. if ((HasCompiledOutput()) && (wantOptions != moduleOptions) && (!mIsScratchModule))
  10430. {
  10431. auto lastCheckModule = this;
  10432. auto checkModule = this->mNextAltModule;
  10433. while (checkModule != NULL)
  10434. {
  10435. if (*checkModule->mModuleOptions == wantOptions)
  10436. {
  10437. declareModule = checkModule;
  10438. break;
  10439. }
  10440. lastCheckModule = checkModule;
  10441. checkModule = checkModule->mNextAltModule;
  10442. }
  10443. // Not found?
  10444. if (declareModule == this)
  10445. {
  10446. String specModuleName = mModuleName + "@@";
  10447. if (wantOptions.mOptLevel != moduleOptions.mOptLevel)
  10448. specModuleName += StrFormat("O%d", wantOptions.mOptLevel);
  10449. if (wantOptions.mSIMDSetting != moduleOptions.mSIMDSetting)
  10450. specModuleName += StrFormat("SIMD%d", wantOptions.mSIMDSetting);
  10451. declareModule = new BfModule(mContext, specModuleName);
  10452. declareModule->mProject = project;
  10453. declareModule->mModuleOptions = new BfModuleOptions();
  10454. *declareModule->mModuleOptions = wantOptions;
  10455. declareModule->mParentModule = lastCheckModule;
  10456. declareModule->Init();
  10457. lastCheckModule->mNextAltModule = declareModule;
  10458. }
  10459. }
  10460. }
  10461. declareModule->PrepareForIRWriting(typeInst);
  10462. return declareModule;
  10463. }
  10464. BfModuleMethodInstance BfModule::GetMethodInstance(BfTypeInstance* typeInst, BfMethodDef* methodDef, const BfTypeVector& methodGenericArguments, BfGetMethodInstanceFlags flags, BfTypeInstance* foreignType)
  10465. {
  10466. if (((flags & BfGetMethodInstanceFlag_ForceInline) != 0) && (mCompiler->mIsResolveOnly))
  10467. {
  10468. // Don't bother inlining for resolve-only
  10469. flags = (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline);
  10470. }
  10471. bool processNow = false;
  10472. bool keepInCurrentModule = false;
  10473. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsUnspecialized))
  10474. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_NoForceReification);
  10475. if (!typeInst->IsTypeMemberIncluded(methodDef->mDeclaringType))
  10476. {
  10477. return BfModuleMethodInstance();
  10478. }
  10479. if (methodDef->mIsLocalMethod)
  10480. {
  10481. auto rootMethodState = mCurMethodState->GetRootMethodState();
  10482. BfLocalMethod* localMethod;
  10483. if (rootMethodState->mLocalMethodCache.TryGetValue(methodDef->mName, &localMethod))
  10484. {
  10485. // Handle the def in the correct method state
  10486. return GetLocalMethodInstance(localMethod, methodGenericArguments);
  10487. }
  10488. BFMODULE_FATAL(this, "Cannot find local method");
  10489. return BfModuleMethodInstance();
  10490. }
  10491. #ifdef _DEBUG
  10492. for (auto arg : methodGenericArguments)
  10493. BF_ASSERT(!arg->IsVar());
  10494. #endif
  10495. BF_ASSERT(methodDef->mMethodType != BfMethodType_Ignore);
  10496. // We need to do the 'mNeedsMethodProcessing' check because we want to do a proper initial "awaiting reference" population
  10497. // on the methods before we handle an on-demand situation. This also ensures that our type options are set before doing
  10498. // a FinishInit
  10499. if ((typeInst->IsIncomplete()) &&
  10500. (!typeInst->mResolvingVarField) && (!typeInst->mTypeFailed))
  10501. {
  10502. // For autocomplete, we still may not actually generate methods. This shouldn't matter, and on-demand works differently
  10503. // for resolve-only because we don't differentiate between reified/unreified there
  10504. PopulateType(typeInst, BfPopulateType_Full);
  10505. }
  10506. bool tryModuleMethodLookup = false;
  10507. BfModuleMethodInstance moduleMethodInst;
  10508. BfModule* instModule = typeInst->mModule;
  10509. if (keepInCurrentModule)
  10510. {
  10511. // Stay here
  10512. instModule = this;
  10513. }
  10514. if (this == mContext->mUnreifiedModule)
  10515. {
  10516. // Stay in this 'resolve only' module here
  10517. }
  10518. else if (flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass)
  10519. {
  10520. BF_ASSERT(this == mContext->mUnreifiedModule);
  10521. }
  10522. else if (flags & BfGetMethodInstanceFlag_ExplicitSpecializedModule)
  10523. {
  10524. BF_ASSERT(instModule == mParentModule);
  10525. }
  10526. else if (instModule != this)
  10527. {
  10528. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mMinDependDepth >= 32))
  10529. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_DepthExceeded);
  10530. if ((!mIsReified) && (instModule->mIsReified))
  10531. {
  10532. BF_ASSERT(!mCompiler->mIsResolveOnly);
  10533. // A resolve-only module is specializing a method from a type in a reified module,
  10534. // we need to take care that this doesn't cause anything new to become reified
  10535. BfModuleMethodInstance moduleMethodInstance = mContext->mUnreifiedModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ExplicitResolveOnlyPass), foreignType);
  10536. if (!moduleMethodInstance)
  10537. return moduleMethodInstance;
  10538. SetMethodDependency(moduleMethodInstance.mMethodInstance);
  10539. return moduleMethodInstance;
  10540. }
  10541. else
  10542. {
  10543. if ((mIsReified) && (!instModule->mIsReified))
  10544. {
  10545. if (!typeInst->IsUnspecializedTypeVariation())
  10546. {
  10547. if (!instModule->mReifyQueued)
  10548. {
  10549. BF_ASSERT((instModule != mContext->mUnreifiedModule) && (instModule != mContext->mScratchModule));
  10550. BF_ASSERT((mCompiler->mCompileState != BfCompiler::CompileState_Unreified) && (mCompiler->mCompileState != BfCompiler::CompileState_VData));
  10551. BfLogSysM("Queueing ReifyModule: %p\n", instModule);
  10552. mContext->mReifyModuleWorkList.Add(instModule);
  10553. instModule->mReifyQueued = true;
  10554. }
  10555. // This ensures that the method will actually be created when it gets reified
  10556. BfMethodSpecializationRequest* specializationRequest = mContext->mMethodSpecializationWorkList.Alloc();
  10557. specializationRequest->mFromModule = typeInst->mModule;
  10558. specializationRequest->mFromModuleRevision = typeInst->mModule->mRevision;
  10559. specializationRequest->mMethodDef = methodDef;
  10560. specializationRequest->mMethodGenericArguments = methodGenericArguments;
  10561. specializationRequest->mType = typeInst;
  10562. specializationRequest->mFlags = flags;
  10563. }
  10564. }
  10565. auto defFlags = (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline);
  10566. // Not extern
  10567. // Create the instance in the proper module and then create a reference in this one
  10568. moduleMethodInst = instModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, defFlags, foreignType);
  10569. if (!moduleMethodInst)
  10570. return moduleMethodInst;
  10571. tryModuleMethodLookup = true;
  10572. if ((mIsReified) && (!moduleMethodInst.mMethodInstance->mIsReified))
  10573. {
  10574. CheckHotMethod(moduleMethodInst.mMethodInstance, "");
  10575. }
  10576. }
  10577. }
  10578. if (tryModuleMethodLookup)
  10579. {
  10580. SetMethodDependency(moduleMethodInst.mMethodInstance);
  10581. return ReferenceExternalMethodInstance(moduleMethodInst.mMethodInstance, flags);
  10582. }
  10583. if (((flags & BfGetMethodInstanceFlag_ForceInline) != 0) && (!methodDef->mAlwaysInline))
  10584. {
  10585. auto moduleMethodInstance = GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline), foreignType);
  10586. if (moduleMethodInstance)
  10587. return ReferenceExternalMethodInstance(moduleMethodInstance.mMethodInstance, flags);
  10588. return moduleMethodInst;
  10589. }
  10590. bool isReified = mIsReified /* || ((flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass) != 0)*/;
  10591. bool hadConcreteInterfaceGenericArgument = false;
  10592. if ((flags & BfGetMethodInstanceFlag_Unreified) != 0)
  10593. isReified = false;
  10594. if ((flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass) != 0)
  10595. {
  10596. isReified = false;
  10597. }
  10598. BfTypeVector sanitizedMethodGenericArguments;
  10599. SizedArray<BfProject*, 4> projectList;
  10600. bool isUnspecializedPass = (flags & BfGetMethodInstanceFlag_UnspecializedPass) != 0;
  10601. if ((isUnspecializedPass) && (methodDef->mGenericParams.size() == 0))
  10602. isUnspecializedPass = false;
  10603. // 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
  10604. bool isExternalExtensionMethod = false;
  10605. if ((!typeInst->IsUnspecializedType()) && (!isUnspecializedPass))
  10606. {
  10607. if (((flags & BfGetMethodInstanceFlag_ForeignMethodDef) == 0) && (methodDef->mDeclaringType->mProject != typeInst->mTypeDef->mProject))
  10608. {
  10609. auto specProject = methodDef->mDeclaringType->mProject;
  10610. isExternalExtensionMethod = true;
  10611. if (typeInst->IsGenericTypeInstance())
  10612. {
  10613. auto genericTypeInst = (BfTypeInstance*)typeInst;
  10614. if (genericTypeInst->mGenericTypeInfo->mProjectsReferenced.empty())
  10615. genericTypeInst->GenerateProjectsReferenced();
  10616. if (genericTypeInst->mGenericTypeInfo->mProjectsReferenced.Contains(specProject))
  10617. {
  10618. // This is a generic type where a generic param is already confined to the project in question
  10619. isExternalExtensionMethod = false;
  10620. }
  10621. }
  10622. if (isExternalExtensionMethod)
  10623. {
  10624. BF_ASSERT(typeInst->mTypeDef->mIsCombinedPartial);
  10625. projectList.push_back(methodDef->mDeclaringType->mProject);
  10626. }
  10627. }
  10628. }
  10629. if ((!isUnspecializedPass) && (methodGenericArguments.size() != 0))
  10630. {
  10631. int typeProjectsCounts = 0;
  10632. if (typeInst->IsGenericTypeInstance())
  10633. {
  10634. auto genericTypeInst = (BfTypeInstance*)typeInst;
  10635. if (genericTypeInst->mGenericTypeInfo->mProjectsReferenced.empty())
  10636. genericTypeInst->GenerateProjectsReferenced();
  10637. typeProjectsCounts = (int)genericTypeInst->mGenericTypeInfo->mProjectsReferenced.size();
  10638. projectList.Insert(0, &genericTypeInst->mGenericTypeInfo->mProjectsReferenced[0], genericTypeInst->mGenericTypeInfo->mProjectsReferenced.size());
  10639. }
  10640. else
  10641. {
  10642. typeProjectsCounts = 1;
  10643. projectList.Insert(0, typeInst->mTypeDef->mProject);
  10644. }
  10645. isUnspecializedPass = true;
  10646. for (int genericArgIdx = 0; genericArgIdx < (int) methodGenericArguments.size(); genericArgIdx++)
  10647. {
  10648. auto genericArgType = methodGenericArguments[genericArgIdx];
  10649. //BF_ASSERT(!genericArgType->IsRef());
  10650. if (genericArgType->IsConcreteInterfaceType())
  10651. {
  10652. hadConcreteInterfaceGenericArgument = true;
  10653. auto concreteInterfaceType = (BfConcreteInterfaceType*)genericArgType;
  10654. genericArgType = concreteInterfaceType->mInterface;
  10655. }
  10656. if (genericArgType->IsGenericParam())
  10657. {
  10658. auto genericParam = (BfGenericParamType*) genericArgType;
  10659. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  10660. isUnspecializedPass = false;
  10661. }
  10662. else
  10663. {
  10664. BfTypeUtils::GetProjectList(genericArgType, &projectList, typeProjectsCounts);
  10665. isUnspecializedPass = false;
  10666. }
  10667. sanitizedMethodGenericArguments.push_back(genericArgType);
  10668. }
  10669. if ((int)projectList.size() > typeProjectsCounts)
  10670. {
  10671. // Just leave the new items
  10672. projectList.RemoveRange(0, typeProjectsCounts);
  10673. std::sort(projectList.begin(), projectList.end(), [](BfProject* lhs, BfProject*rhs)
  10674. {
  10675. return lhs->mName < rhs->mName;
  10676. });
  10677. }
  10678. else
  10679. {
  10680. projectList.Clear();
  10681. }
  10682. }
  10683. const BfTypeVector& lookupMethodGenericArguments = isUnspecializedPass ? BfTypeVector() : sanitizedMethodGenericArguments;
  10684. BfMethodInstanceGroup* methodInstGroup = NULL;
  10685. if ((flags & BfGetMethodInstanceFlag_ForeignMethodDef) != 0)
  10686. {
  10687. BF_ASSERT(!typeInst->IsInterface());
  10688. //for (auto& checkGroup : typeInst->mMethodInstanceGroups)
  10689. for (int methodIdx = (int)typeInst->mTypeDef->mMethods.size(); methodIdx < (int)typeInst->mMethodInstanceGroups.size(); methodIdx++)
  10690. {
  10691. auto& checkGroup = typeInst->mMethodInstanceGroups[methodIdx];
  10692. // if (checkGroup.mDefault == NULL)
  10693. // {
  10694. // // This should only be for when we explicitly add a spot so we can set mOnDemandKind
  10695. // BF_ASSERT(methodIdx == typeInst->mMethodInstanceGroups.size() - 1);
  10696. // methodInstGroup = &checkGroup;
  10697. // break;
  10698. // }
  10699. if ((checkGroup.mDefault != NULL) && (checkGroup.mDefault->mMethodDef == methodDef))
  10700. {
  10701. methodInstGroup = &checkGroup;
  10702. break;
  10703. }
  10704. }
  10705. if (methodInstGroup == NULL)
  10706. {
  10707. // Allocate a new entry
  10708. typeInst->mMethodInstanceGroups.Resize(typeInst->mMethodInstanceGroups.size() + 1);
  10709. methodInstGroup = &typeInst->mMethodInstanceGroups.back();
  10710. methodInstGroup->mMethodIdx = (int)typeInst->mMethodInstanceGroups.size() - 1;
  10711. methodInstGroup->mOwner = typeInst;
  10712. // if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet)
  10713. // methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  10714. if (mCompiler->mOptions.mCompileOnDemandKind == BfCompileOnDemandKind_AlwaysInclude)
  10715. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  10716. else
  10717. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingDecl;
  10718. }
  10719. }
  10720. else
  10721. {
  10722. methodInstGroup = &typeInst->mMethodInstanceGroups[methodDef->mIdx];
  10723. }
  10724. if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet)
  10725. {
  10726. BfLogSysM("Forcing BfMethodOnDemandKind_NotSet to BfMethodOnDemandKind_AlwaysInclude for Method:%s in Type:%p\n", methodDef->mName.c_str(), typeInst);
  10727. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  10728. }
  10729. BfIRFunction prevIRFunc;
  10730. bool doingRedeclare = false;
  10731. BfMethodInstance* methodInstance = NULL;
  10732. auto _SetReified = [&]()
  10733. {
  10734. methodInstance->mIsReified = true;
  10735. };
  10736. if (lookupMethodGenericArguments.size() == 0)
  10737. {
  10738. methodInstance = methodInstGroup->mDefault;
  10739. if ((methodInstance != NULL) && (isReified) && (!methodInstance->mIsReified))
  10740. {
  10741. MarkDerivedDirty(typeInst);
  10742. if (mIsScratchModule)
  10743. {
  10744. BfLogSysM("Marking scratch module method instance as reified: %p\n", methodInstance);
  10745. _SetReified();
  10746. CheckHotMethod(methodInstance, "");
  10747. }
  10748. else if ((flags & BfGetMethodInstanceFlag_NoForceReification) != 0)
  10749. {
  10750. // We don't need to force reification if we're in an unspecialized generic- we can wait for
  10751. // the specializations to handle that for us
  10752. return BfModuleMethodInstance(methodInstance);
  10753. }
  10754. else if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_Referenced)
  10755. {
  10756. if (methodDef->mIsAbstract)
  10757. {
  10758. BfLogSysM("Reifying abstract unreified method instance: %p IRFunction:%d\n", methodInstance, methodInstance->mIRFunction.mId);
  10759. _SetReified();
  10760. }
  10761. else
  10762. {
  10763. BfLogSysM("Re-declaring processed but unreified method instance: %p IRFunction:%d\n", methodInstance, methodInstance->mIRFunction.mId);
  10764. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_NoDecl_AwaitingReference;
  10765. methodInstance->UndoDeclaration(!methodInstance->mIRFunction.IsFake());
  10766. doingRedeclare = true;
  10767. mOnDemandMethodCount++;
  10768. }
  10769. }
  10770. else
  10771. {
  10772. BfLogSysM("Marking unprocessed method instance as reified: %p\n", methodInstance);
  10773. // We haven't processed it yet
  10774. _SetReified();
  10775. CheckHotMethod(methodInstance, "");
  10776. if (methodInstance->mDeclModule == this)
  10777. {
  10778. if (methodInstance->mMethodProcessRequest != NULL)
  10779. {
  10780. // Disconnect method process request
  10781. BF_ASSERT(methodInstance->mMethodProcessRequest->mFromModule == this);
  10782. }
  10783. }
  10784. else
  10785. {
  10786. if (methodInstance->mMethodProcessRequest != NULL)
  10787. {
  10788. // Disconnect method process request
  10789. methodInstance->mMethodProcessRequest->mMethodInstance = NULL;
  10790. methodInstance->mMethodProcessRequest = NULL;
  10791. }
  10792. if (methodInstance->mDeclModule == mContext->mUnreifiedModule)
  10793. {
  10794. // Add new request in proper module
  10795. methodInstance->mDeclModule = this;
  10796. }
  10797. else
  10798. {
  10799. if (methodInstance->mDeclModule == NULL)
  10800. {
  10801. //
  10802. }
  10803. else if (methodInstance->mDeclModule != this)
  10804. {
  10805. // Is from specialized module?
  10806. BF_ASSERT(methodInstance->mDeclModule->mParentModule == this);
  10807. }
  10808. }
  10809. if ((!methodInstance->mIRFunction) || (methodInstance->mIRFunction.IsFake()))
  10810. {
  10811. methodInstance->mIRFunction = BfIRFunction();
  10812. if (!mIsModuleMutable)
  10813. StartExtension();
  10814. if ((!mBfIRBuilder->mIgnoreWrites) && (methodInstance->mDeclModule != NULL))
  10815. {
  10816. StringT<128> mangledName;
  10817. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  10818. bool isIntrinsic = false;
  10819. SetupIRFunction(methodInstance, mangledName, false, &isIntrinsic);
  10820. BfLogSysM("Creating new IRFunction %d\n", methodInstance->mIRFunction.mId);
  10821. }
  10822. }
  10823. AddMethodToWorkList(methodInstance);
  10824. }
  10825. }
  10826. }
  10827. }
  10828. else
  10829. {
  10830. BF_ASSERT(lookupMethodGenericArguments.size() != 0);
  10831. if (methodInstGroup->mMethodSpecializationMap == NULL)
  10832. methodInstGroup->mMethodSpecializationMap = new BfMethodInstanceGroup::MapType();
  10833. BfMethodInstance** methodInstancePtr = NULL;
  10834. if (methodInstGroup->mMethodSpecializationMap->TryGetValue(lookupMethodGenericArguments, &methodInstancePtr))
  10835. {
  10836. methodInstance = *methodInstancePtr;
  10837. if ((methodInstance->mRequestedByAutocomplete) && (!mCompiler->IsAutocomplete()))
  10838. {
  10839. // We didn't want to process this message yet if it was autocomplete-specific, but now we will
  10840. AddMethodToWorkList(methodInstance);
  10841. methodInstance->mRequestedByAutocomplete = false;
  10842. }
  10843. if ((isReified) && (!methodInstance->mIsReified))
  10844. {
  10845. MarkDerivedDirty(typeInst);
  10846. if (methodInstance->mHasBeenProcessed)
  10847. {
  10848. BfLogSysM("Deleting processed but unreified specialized method instance %p\n", methodInstance);
  10849. delete methodInstance;
  10850. methodInstGroup->mMethodSpecializationMap->Remove(lookupMethodGenericArguments);
  10851. methodInstance = NULL;
  10852. }
  10853. else if ((!methodInstance->mIRFunction) || (methodInstance->mIRFunction.IsFake()))
  10854. {
  10855. BfLogSysM("Deleting declared but uncreated specialized method instance %p\n", methodInstance);
  10856. delete methodInstance;
  10857. methodInstGroup->mMethodSpecializationMap->Remove(lookupMethodGenericArguments);
  10858. methodInstance = NULL;
  10859. }
  10860. else
  10861. {
  10862. BfLogSysM("Reifying declared but unreified method instance %p\n", methodInstance);
  10863. // We haven't processed it yet
  10864. _SetReified();
  10865. CheckHotMethod(methodInstance, "");
  10866. }
  10867. }
  10868. }
  10869. }
  10870. if ((methodInstance != NULL) && (!doingRedeclare))
  10871. {
  10872. SetMethodDependency(methodInstance);
  10873. if (methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference)
  10874. {
  10875. /*if ((!mCompiler->mIsResolveOnly) && (!isReified))
  10876. BF_ASSERT(!methodInstance->mIsReified);*/
  10877. if (methodInstance->mIsReified != isReified)
  10878. BfLogSysM("GetMethodInstance %p Decl_AwaitingReference setting reified to %d\n", methodInstance, isReified);
  10879. if ((!isReified) &&
  10880. ((methodInstance->mDeclModule == NULL) || (!methodInstance->mDeclModule->mIsModuleMutable)))
  10881. {
  10882. methodInstance->mDeclModule = mContext->mUnreifiedModule;
  10883. methodInstance->mIRFunction = BfIRFunction();
  10884. }
  10885. methodInstance->mIsReified = isReified;
  10886. if ((methodInstance->mHotMethod != NULL) && (!mCompiler->IsHotCompile()) && (isReified))
  10887. {
  10888. methodInstance->mHotMethod->mFlags = (BfHotDepDataFlags)(methodInstance->mHotMethod->mFlags | BfHotDepDataFlag_IsOriginalBuild);
  10889. }
  10890. if (!methodInstance->mMethodDef->mIsAbstract)
  10891. {
  10892. if ((methodInstance->mMethodDef->mMethodType == BfMethodType_Mixin) && (!methodInstance->mDeclModule->mIsModuleMutable))
  10893. {
  10894. // Wait until unreified
  10895. }
  10896. else
  10897. AddMethodToWorkList(methodInstance);
  10898. }
  10899. else
  10900. {
  10901. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Referenced;
  10902. }
  10903. }
  10904. if (mExtensionCount > 0)
  10905. {
  10906. if ((mIsModuleMutable) && (!methodInstance->mIRFunction) &&
  10907. ((projectList.IsEmpty() || ((flags & BfGetMethodInstanceFlag_ExplicitSpecializedModule) != 0))))
  10908. {
  10909. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, false);
  10910. if (mAwaitingInitFinish)
  10911. FinishInit();
  10912. // We need to refer to a function that was defined in a prior module
  10913. bool isInlined = (methodInstance->mAlwaysInline) || ((flags & BfGetMethodInstanceFlag_ForceInline) != 0);
  10914. methodInstance->mIRFunction = CreateFunctionFrom(methodInstance, false, isInlined);
  10915. BF_ASSERT((methodInstance->mDeclModule == this) || (methodInstance->mDeclModule == mContext->mUnreifiedModule) || (methodInstance->mDeclModule == NULL));
  10916. methodInstance->mDeclModule = this;
  10917. // Add this inlined def to ourselves
  10918. if ((methodInstance->mAlwaysInline) && (HasCompiledOutput()) && (!methodInstance->mIsUnspecialized) && ((flags & BfGetMethodInstanceFlag_NoInline) == 0))
  10919. {
  10920. mIncompleteMethodCount++;
  10921. BfInlineMethodRequest* inlineMethodRequest = mContext->mInlineMethodWorkList.Alloc();
  10922. inlineMethodRequest->mType = typeInst;
  10923. inlineMethodRequest->mFromModule = this;
  10924. inlineMethodRequest->mFunc = methodInstance->mIRFunction;
  10925. inlineMethodRequest->mFromModuleRevision = mRevision;
  10926. inlineMethodRequest->mMethodInstance = methodInstance;
  10927. BfLogSysM("mInlineMethodWorkList %p for method %p in module %p in GetMethodInstance\n", inlineMethodRequest, methodInstance, this);
  10928. BF_ASSERT(mIsModuleMutable);
  10929. }
  10930. }
  10931. }
  10932. if (mCompiler->IsSkippingExtraResolveChecks())
  10933. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  10934. else
  10935. {
  10936. if (methodInstance->mDeclModule != this)
  10937. return ReferenceExternalMethodInstance(methodInstance, flags);
  10938. if ((!methodInstance->mIRFunction) && (mIsModuleMutable) && (!mBfIRBuilder->mIgnoreWrites))
  10939. {
  10940. auto importKind = methodInstance->GetImportCallKind();
  10941. if (importKind != BfImportCallKind_None)
  10942. {
  10943. BfLogSysM("DllImportGlobalVar creating %p\n", methodInstance);
  10944. methodInstance->mIRFunction = mBfIRBuilder->GetFakeVal();
  10945. mFuncReferences[methodInstance] = CreateDllImportGlobalVar(methodInstance, true);;
  10946. }
  10947. }
  10948. return BfModuleMethodInstance(methodInstance);
  10949. }
  10950. }
  10951. if (!doingRedeclare)
  10952. {
  10953. BfModule* specModule = NULL;
  10954. if ((!keepInCurrentModule) && (projectList.size() > 0) && (!isUnspecializedPass) && (HasCompiledOutput()) && (!mIsScratchModule))
  10955. {
  10956. specModule = GetSpecializedMethodModule(projectList);
  10957. }
  10958. if ((specModule != NULL) && (specModule != this))
  10959. {
  10960. auto specMethodInstance = specModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ExplicitSpecializedModule));
  10961. if (mAwaitingInitFinish)
  10962. return BfModuleMethodInstance(specMethodInstance.mMethodInstance, BfIRFunction());
  10963. return ReferenceExternalMethodInstance(specMethodInstance.mMethodInstance, flags);
  10964. }
  10965. if ((!isUnspecializedPass) && (methodGenericArguments.size() != 0) && (methodInstGroup->mDefault == NULL))
  10966. {
  10967. // We are attempting to specialize but we don't have the unspecialized method yet. Generate that first.
  10968. GetMethodInstance(typeInst, methodDef, BfTypeVector(), BfGetMethodInstanceFlag_UnspecializedPass);
  10969. }
  10970. }
  10971. if (methodInstance == NULL)
  10972. {
  10973. if (lookupMethodGenericArguments.size() == 0)
  10974. {
  10975. BF_ASSERT(methodInstGroup->mDefault == NULL);
  10976. methodInstance = new BfMethodInstance();
  10977. methodInstGroup->mDefault = methodInstance;
  10978. BfLogSysM("Created Default MethodInst: %p TypeInst: %p Group: %p\n", methodInstance, typeInst, methodInstGroup);
  10979. }
  10980. else
  10981. {
  10982. bool depthExceeded = ((flags & BfGetMethodInstanceFlag_DepthExceeded) != 0);
  10983. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mMinDependDepth >= 32))
  10984. depthExceeded = true;
  10985. if (depthExceeded)
  10986. {
  10987. Fail("Generic method dependency depth exceeded", methodDef->GetRefNode());
  10988. return BfModuleMethodInstance();
  10989. }
  10990. BfMethodInstance** methodInstancePtr = NULL;
  10991. bool added = methodInstGroup->mMethodSpecializationMap->TryAdd(lookupMethodGenericArguments, NULL, &methodInstancePtr);
  10992. BF_ASSERT(added);
  10993. methodInstance = new BfMethodInstance();
  10994. *methodInstancePtr = methodInstance;
  10995. if (mCompiler->IsAutocomplete())
  10996. methodInstance->mRequestedByAutocomplete = true;
  10997. BfLogSysM("Created Specialized MethodInst: %p TypeInst: %p\n", methodInstance, typeInst);
  10998. }
  10999. if ((prevIRFunc) && (!prevIRFunc.IsFake()))
  11000. methodInstance->mIRFunction = prevIRFunc; // Take it over
  11001. }
  11002. /*// 24 bits for typeid, 20 for method id, 20 for specialization index
  11003. methodInstance->mMethodId = ((int64)typeInst->mTypeId) + ((int64)methodInstGroup->mMethodIdx << 24);
  11004. if (methodInstGroup->mMethodSpecializationMap != NULL)
  11005. methodInstance->mMethodId += ((int64)methodInstGroup->mMethodSpecializationMap->size() << 44);*/
  11006. methodInstance->mMethodDef = methodDef;
  11007. methodInstance->mAlwaysInline = methodDef->mAlwaysInline;
  11008. methodInstance->mMethodInstanceGroup = methodInstGroup;
  11009. methodInstance->mIsReified = isReified;
  11010. SetupMethodIdHash(methodInstance);
  11011. if (hadConcreteInterfaceGenericArgument)
  11012. methodInstance->mIgnoreBody = true;
  11013. if ((flags & BfGetMethodInstanceFlag_ForeignMethodDef) != 0)
  11014. {
  11015. methodInstance->mIsForeignMethodDef = true;
  11016. BF_ASSERT(foreignType != NULL);
  11017. methodInstance->GetMethodInfoEx()->mForeignType = foreignType;
  11018. }
  11019. if ((typeInst->mTypeDef == mCompiler->mValueTypeTypeDef) && (methodDef->mName == BF_METHODNAME_EQUALS))
  11020. {
  11021. if (!lookupMethodGenericArguments.empty())
  11022. {
  11023. auto compareType = lookupMethodGenericArguments[0];
  11024. PopulateType(compareType, BfPopulateType_Data);
  11025. if (compareType->IsSplattable())
  11026. methodInstance->mAlwaysInline = true;
  11027. }
  11028. }
  11029. if (methodDef->mDeclaringType->mTypeDeclaration != typeInst->mTypeDef->mTypeDeclaration)
  11030. {
  11031. // With extensions we can have multiple definitions of the same method
  11032. //methodInstance->mMangleWithIdx = true;
  11033. }
  11034. BfModule* declareModule = GetOrCreateMethodModule(methodInstance);
  11035. if ((doingRedeclare) && (methodInstance->mDeclModule != mContext->mUnreifiedModule))
  11036. declareModule = methodInstance->mDeclModule;
  11037. BF_ASSERT(typeInst == methodInstance->GetOwner());
  11038. auto methodDeclaration = methodDef->GetMethodDeclaration();
  11039. if (isUnspecializedPass)
  11040. {
  11041. for (int genericParamIdx = 0; genericParamIdx < (int) methodDef->mGenericParams.size(); genericParamIdx++)
  11042. {
  11043. auto genericParamType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  11044. methodInstance->GetMethodInfoEx()->mMethodGenericArguments.Add(genericParamType);
  11045. }
  11046. }
  11047. else if ((methodDeclaration != NULL) && (methodDeclaration->mGenericParams != NULL))
  11048. {
  11049. if (!sanitizedMethodGenericArguments.IsEmpty())
  11050. methodInstance->GetMethodInfoEx()->mMethodGenericArguments = sanitizedMethodGenericArguments;
  11051. if (methodDef->mGenericParams.size() != sanitizedMethodGenericArguments.size())
  11052. {
  11053. Fail("Internal error");
  11054. BFMODULE_FATAL(this, "Generic method argument counts mismatch");
  11055. return NULL;
  11056. }
  11057. for (auto genericArg : sanitizedMethodGenericArguments)
  11058. {
  11059. if (genericArg->IsPrimitiveType())
  11060. genericArg = GetWrappedStructType(genericArg);
  11061. if (genericArg != NULL)
  11062. AddDependency(genericArg, typeInst, BfDependencyMap::DependencyFlag_MethodGenericArg);
  11063. }
  11064. }
  11065. // Generic constraints
  11066. if (!methodDef->mGenericParams.IsEmpty())
  11067. {
  11068. BF_ASSERT(methodInstance->GetMethodInfoEx()->mGenericParams.IsEmpty());
  11069. for (int genericParamIdx = 0; genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  11070. {
  11071. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, genericParamIdx);
  11072. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  11073. }
  11074. }
  11075. for (int externConstraintIdx = 0; externConstraintIdx < (int)methodDef->mExternalConstraints.size(); externConstraintIdx++)
  11076. {
  11077. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, externConstraintIdx + (int)methodDef->mGenericParams.size());
  11078. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  11079. }
  11080. bool addToWorkList = !processNow;
  11081. if (mCompiler->GetAutoComplete() != NULL)
  11082. {
  11083. if (typeInst->IsSpecializedByAutoCompleteMethod())
  11084. addToWorkList = false;
  11085. if (methodInstance->mRequestedByAutocomplete)
  11086. addToWorkList = false;
  11087. }
  11088. BF_ASSERT(declareModule != NULL);
  11089. methodInstance->mDeclModule = declareModule;
  11090. if ((!methodInstance->mIsReified) && (mCompiler->mCompileState != BfCompiler::CompileState_Normal))
  11091. {
  11092. // We can be sure this method won't become reified later. Normally we can "go either way" with an unreified method
  11093. // of a reified module -
  11094. // If we declare it in the reified module then we can switch it to "reified" before actual processing without any extra work,
  11095. // BUT if we don't reify it then we have to remove the body after processing.
  11096. // 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
  11097. // the proper reified module.
  11098. declareModule = mContext->mUnreifiedModule;
  11099. }
  11100. else if ((!declareModule->mIsModuleMutable) && (!mCompiler->mIsResolveOnly))
  11101. {
  11102. BF_ASSERT(!methodInstance->mIsReified);
  11103. declareModule = mContext->mUnreifiedModule;
  11104. }
  11105. SetMethodDependency(methodInstance);
  11106. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  11107. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(declareModule->mCurTypeInstance, typeInst);
  11108. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  11109. if ((methodDef->mMethodType == BfMethodType_Mixin) && (methodDef->mGenericParams.size() != 0) && (!isUnspecializedPass))
  11110. {
  11111. // For mixins we only process the unspecialized version
  11112. addToWorkList = false;
  11113. }
  11114. declareModule->DoMethodDeclaration(methodDef->GetMethodDeclaration(), false, addToWorkList);
  11115. if (processNow)
  11116. {
  11117. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, NULL);
  11118. ProcessMethod(methodInstance);
  11119. }
  11120. if (mCompiler->IsSkippingExtraResolveChecks())
  11121. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  11122. if (methodInstance->mDeclModule != this)
  11123. return ReferenceExternalMethodInstance(methodInstance, flags);
  11124. return BfModuleMethodInstance(methodInstance);
  11125. }
  11126. BfModuleMethodInstance BfModule::GetMethodInstance(BfMethodInstance* methodInstance, BfGetMethodInstanceFlags flags)
  11127. {
  11128. BF_ASSERT((methodInstance->mMethodInfoEx == NULL) || (methodInstance->mMethodInfoEx->mGenericParams.IsEmpty()));
  11129. if (methodInstance->mIsForeignMethodDef)
  11130. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ForeignMethodDef);
  11131. return GetMethodInstance(methodInstance->GetOwner(), methodInstance->mMethodDef, BfTypeVector(), flags);
  11132. }
  11133. BfMethodInstance* BfModule::GetOuterMethodInstance(BfMethodInstance* methodInstance)
  11134. {
  11135. if (!methodInstance->mMethodDef->mIsLocalMethod)
  11136. return NULL;
  11137. auto outerLocal = methodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod->mOuterLocalMethod;
  11138. if (outerLocal == NULL)
  11139. return NULL;
  11140. BfTypeVector genericArgs;
  11141. for (int i = 0; i < (int)outerLocal->mMethodDef->mGenericParams.size(); i++)
  11142. genericArgs.Add(methodInstance->mMethodInfoEx->mMethodGenericArguments[i]);
  11143. return GetLocalMethodInstance(outerLocal, genericArgs).mMethodInstance;
  11144. }
  11145. void BfModule::SetupMethodIdHash(BfMethodInstance* methodInstance)
  11146. {
  11147. HashContext hashCtx;
  11148. std::function<void(BfMethodInstance*)> _MixinMethodInstance = [&](BfMethodInstance* methodInstance)
  11149. {
  11150. hashCtx.Mixin(methodInstance->GetOwner()->mTypeId);
  11151. hashCtx.Mixin(methodInstance->mMethodDef->mIdx);
  11152. if (methodInstance->GetNumGenericArguments() != 0)
  11153. {
  11154. hashCtx.Mixin((int32)methodInstance->mMethodInfoEx->mMethodGenericArguments.size());
  11155. for (auto methodGenericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  11156. hashCtx.Mixin(methodGenericArg->mTypeId);
  11157. }
  11158. };
  11159. _MixinMethodInstance(methodInstance);
  11160. if (methodInstance->mMethodDef->mIsLocalMethod)
  11161. {
  11162. auto outmostMethodInstance = mCurMethodState->GetRootMethodState()->mMethodInstance;
  11163. BF_ASSERT((outmostMethodInstance->mIdHash != 0) || (outmostMethodInstance->mIsAutocompleteMethod));
  11164. hashCtx.Mixin(outmostMethodInstance->mIdHash);
  11165. }
  11166. methodInstance->mIdHash = (int64)hashCtx.Finish64();
  11167. }
  11168. BfIRValue BfModule::GetInterfaceSlotNum(BfTypeInstance* ifaceType)
  11169. {
  11170. BfIRValue globalValue;
  11171. BfIRValue* globalValuePtr = NULL;
  11172. if (mInterfaceSlotRefs.TryGetValue(ifaceType, &globalValuePtr))
  11173. {
  11174. globalValue = *globalValuePtr;
  11175. }
  11176. if (!globalValue)
  11177. {
  11178. // This is necessary to reify the interface type
  11179. PopulateType(ifaceType);
  11180. StringT<128> slotVarName;
  11181. BfMangler::MangleStaticFieldName(slotVarName, mCompiler->GetMangleKind(), ifaceType, "sBfSlotOfs");
  11182. BfType* intType = GetPrimitiveType(BfTypeCode_Int32);
  11183. BfIRValue value;
  11184. if ((mCompiler->mHotState != NULL) && (ifaceType->mSlotNum >= 0))
  11185. {
  11186. /*// If this interface already existed before this hot compile but we never indirectly called any of its methods
  11187. // then the sBfSlotOfs could have gotten its symbol stripped, so actually define it here.
  11188. int virtSlotIdx = ifaceType->mSlotNum + 1;
  11189. value = GetConstValue32(virtSlotIdx);*/
  11190. mCompiler->mHotState->mSlotDefineTypeIds.Add(ifaceType->mTypeId);
  11191. ifaceType->mDirty = true; // Makes sure we create interface in vdata
  11192. }
  11193. globalValue = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(intType), true, BfIRLinkageType_External, value, slotVarName);
  11194. mInterfaceSlotRefs[ifaceType] = globalValue;
  11195. }
  11196. return mBfIRBuilder->CreateLoad(globalValue/*, "slotOfs"*/);
  11197. }
  11198. void BfModule::HadSlotCountDependency()
  11199. {
  11200. if (mCompiler->mIsResolveOnly)
  11201. return;
  11202. BF_ASSERT(!mBfIRBuilder->mIgnoreWrites);
  11203. BF_ASSERT((mUsedSlotCount == BF_MAX(mCompiler->mMaxInterfaceSlots, 0)) || (mUsedSlotCount == -1));
  11204. mUsedSlotCount = BF_MAX(mCompiler->mMaxInterfaceSlots, 0);
  11205. }
  11206. BfTypedValue BfModule::GetCompilerFieldValue(const StringImpl& str)
  11207. {
  11208. if (str == "#TimeLocal")
  11209. {
  11210. time_t rawtime;
  11211. time(&rawtime);
  11212. tm* timeinfo = localtime(&rawtime);
  11213. char result[32];
  11214. sprintf(result, "%d/%.2d/%.2d %.2d:%.2d:%.2d",
  11215. 1900 + timeinfo->tm_year,
  11216. timeinfo->tm_mon,
  11217. timeinfo->tm_mday,
  11218. timeinfo->tm_hour,
  11219. timeinfo->tm_min,
  11220. timeinfo->tm_sec);
  11221. return BfTypedValue(GetStringObjectValue(result), ResolveTypeDef(mCompiler->mStringTypeDef));
  11222. }
  11223. return BfTypedValue();
  11224. }
  11225. BfTypedValue BfModule::ReferenceStaticField(BfFieldInstance* fieldInstance)
  11226. {
  11227. BfIRValue globalValue;
  11228. auto fieldDef = fieldInstance->GetFieldDef();
  11229. if ((fieldDef->mIsConst) && (!fieldDef->mIsExtern))
  11230. {
  11231. if (fieldInstance->mConstIdx != -1)
  11232. {
  11233. auto constant = fieldInstance->mOwner->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  11234. return BfTypedValue(ConstantToCurrent(constant, fieldInstance->mOwner->mConstHolder, fieldInstance->GetResolvedType()), fieldInstance->GetResolvedType());
  11235. }
  11236. else
  11237. {
  11238. return GetDefaultTypedValue(fieldInstance->GetResolvedType());
  11239. }
  11240. }
  11241. if (mIsScratchModule)
  11242. {
  11243. // Just fake it for the extern and unspecialized modules
  11244. return BfTypedValue(mBfIRBuilder->CreateConstNull(), fieldInstance->GetResolvedType(), true);
  11245. }
  11246. BfIRValue* globalValuePtr = NULL;
  11247. if (mStaticFieldRefs.TryGetValue(fieldInstance, &globalValuePtr))
  11248. {
  11249. globalValue = *globalValuePtr;
  11250. BF_ASSERT(globalValue);
  11251. }
  11252. else
  11253. {
  11254. StringT<128> staticVarName;
  11255. BfMangler::Mangle(staticVarName, mCompiler->GetMangleKind(), fieldInstance);
  11256. auto typeType = fieldInstance->GetResolvedType();
  11257. if ((fieldDef->mIsExtern) && (fieldDef->mIsConst) && (typeType->IsPointer()))
  11258. {
  11259. typeType = typeType->GetUnderlyingType();
  11260. }
  11261. PopulateType(typeType);
  11262. if ((typeType != NULL) && (!typeType->IsValuelessType()))
  11263. {
  11264. BfIRType irType = mBfIRBuilder->MapType(typeType);
  11265. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mBfIRBuilder->mIgnoreWrites || staticVarName.StartsWith('#'));
  11266. globalValue = mBfIRBuilder->CreateGlobalVariable(
  11267. irType,
  11268. false,
  11269. BfIRLinkageType_External,
  11270. BfIRValue(),
  11271. staticVarName,
  11272. IsThreadLocal(fieldInstance));
  11273. if (!mBfIRBuilder->mIgnoreWrites)
  11274. {
  11275. // Only store this if we actually did the creation
  11276. BF_ASSERT(globalValue);
  11277. mStaticFieldRefs[fieldInstance] = globalValue;
  11278. }
  11279. BfLogSysM("Mod:%p Type:%p ReferenceStaticField %p -> %p\n", this, fieldInstance->mOwner, fieldInstance, globalValue);
  11280. }
  11281. }
  11282. auto type = fieldInstance->GetResolvedType();
  11283. if (type->IsValuelessType())
  11284. return BfTypedValue(globalValue, type);
  11285. return BfTypedValue(globalValue, type, !fieldDef->mIsConst);
  11286. }
  11287. BfTypedValue BfModule::GetThis()
  11288. {
  11289. auto useMethodState = mCurMethodState;
  11290. while ((useMethodState != NULL) && (useMethodState->mClosureState != NULL) && (useMethodState->mClosureState->mCapturing))
  11291. {
  11292. useMethodState = useMethodState->mPrevMethodState;
  11293. }
  11294. if (useMethodState != NULL)
  11295. {
  11296. // Fake a 'this' for var field resolution
  11297. if (useMethodState->mTempKind == BfMethodState::TempKind_NonStatic)
  11298. {
  11299. auto thisType = mCurTypeInstance;
  11300. if (thisType->IsValueType())
  11301. return BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(thisType)), thisType, BfTypedValueKind_ThisAddr);
  11302. else
  11303. return BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInst(thisType)), thisType, BfTypedValueKind_ThisValue);
  11304. }
  11305. else if (useMethodState->mTempKind == BfMethodState::TempKind_Static)
  11306. {
  11307. return BfTypedValue();
  11308. }
  11309. }
  11310. else
  11311. {
  11312. //TODO: Do we allow useMethodState to be NULL anymore?
  11313. return BfTypedValue();
  11314. }
  11315. // if (useMethodState->HasNonStaticMixin())
  11316. // {
  11317. // auto checkMethodState = useMethodState;
  11318. // while (checkMethodState != NULL)
  11319. // {
  11320. // for (int localIdx = (int)checkMethodState->mLocals.size() - 1; localIdx >= 0; localIdx--)
  11321. // {
  11322. // auto varDecl = checkMethodState->mLocals[localIdx];
  11323. // if (varDecl->mName == "this")
  11324. // {
  11325. // varDecl->mReadFromId = useMethodState->GetRootMethodState()->mCurAccessId++;
  11326. // if (varDecl->mIsSplat)
  11327. // {
  11328. // return BfTypedValue(varDecl->mValue, varDecl->mResolvedType, BfTypedValueKind_ThisSplatHead);
  11329. // }
  11330. // else if ((varDecl->mResolvedType->IsValueType()) && (varDecl->mAddr))
  11331. // {
  11332. // return BfTypedValue(varDecl->mAddr, varDecl->mResolvedType, BfTypedValueKind_ThisAddr);
  11333. // }
  11334. // return BfTypedValue(varDecl->mValue, varDecl->mResolvedType, varDecl->mResolvedType->IsValueType() ? BfTypedValueKind_ThisAddr : BfTypedValueKind_ThisValue);
  11335. // }
  11336. // }
  11337. //
  11338. // checkMethodState = checkMethodState->mPrevMethodState;
  11339. // }
  11340. // }
  11341. // Check mixin state for 'this'
  11342. {
  11343. auto checkMethodState = useMethodState;
  11344. while (checkMethodState != NULL)
  11345. {
  11346. if (checkMethodState->mMixinState != NULL)
  11347. {
  11348. BfTypedValue thisValue = checkMethodState->mMixinState->mTarget;
  11349. if (thisValue.HasType())
  11350. {
  11351. checkMethodState->mMixinState->mLastTargetAccessId = useMethodState->GetRootMethodState()->mCurAccessId++;
  11352. if (!thisValue.mType->IsValueType())
  11353. thisValue = LoadValue(thisValue);
  11354. return thisValue;
  11355. }
  11356. }
  11357. checkMethodState = checkMethodState->mPrevMethodState;
  11358. }
  11359. }
  11360. auto curMethodInstance = mCurMethodInstance;
  11361. if (useMethodState->mMethodInstance != NULL)
  11362. curMethodInstance = useMethodState->mMethodInstance;
  11363. if ((curMethodInstance == NULL) /*|| (!mCurMethodInstance->mIRFunction)*/ || (curMethodInstance->mMethodDef->mIsStatic))
  11364. {
  11365. if ((useMethodState->mClosureState != NULL) && (!useMethodState->mClosureState->mConstLocals.empty()))
  11366. {
  11367. auto& constLocal = useMethodState->mClosureState->mConstLocals[0];
  11368. if (constLocal.mIsThis)
  11369. {
  11370. BF_ASSERT(constLocal.mResolvedType->IsValuelessType());
  11371. return BfTypedValue(mBfIRBuilder->GetFakeVal(), constLocal.mResolvedType);
  11372. }
  11373. }
  11374. return BfTypedValue();
  11375. }
  11376. if (useMethodState->mLocals.IsEmpty())
  11377. {
  11378. // 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
  11379. BF_ASSERT(useMethodState->mPrevMethodState != NULL);
  11380. return BfTypedValue();
  11381. }
  11382. auto thisLocal = useMethodState->mLocals[0];
  11383. BF_ASSERT(thisLocal->mIsThis);
  11384. bool preferValue = !IsTargetingBeefBackend();
  11385. if (!thisLocal->mAddr)
  11386. preferValue = true;
  11387. bool usedVal = false;
  11388. BfIRValue thisValue;
  11389. if ((preferValue) && (!thisLocal->mIsLowered))
  11390. {
  11391. thisValue = thisLocal->mValue;
  11392. usedVal = true;
  11393. }
  11394. else if ((thisLocal->mIsSplat) || (thisLocal->mIsLowered))
  11395. thisValue = thisLocal->mAddr;
  11396. else
  11397. thisValue = mBfIRBuilder->CreateLoad(thisLocal->mAddr);
  11398. useMethodState->mLocals[0]->mReadFromId = useMethodState->GetRootMethodState()->mCurAccessId++;
  11399. if (useMethodState->mClosureState != NULL)
  11400. {
  11401. auto closureTypeInst = useMethodState->mClosureState->mClosureType;
  11402. if (closureTypeInst != NULL)
  11403. {
  11404. if (closureTypeInst->mFieldInstances.size() > 0)
  11405. {
  11406. auto& field = closureTypeInst->mFieldInstances[0];
  11407. auto fieldDef = field.GetFieldDef();
  11408. if (fieldDef->mName == "__this")
  11409. {
  11410. if (mCurMethodState->mClosureState->mCapturing)
  11411. mCurMethodState->mClosureState->mReferencedOuterClosureMembers.Add(&field);
  11412. // This is a captured 'this'
  11413. BfTypedValue result = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(thisValue, 0, field.mDataIdx), field.mResolvedType, true);
  11414. if (field.mResolvedType->IsRef())
  11415. {
  11416. auto refType = (BfRefType*)field.mResolvedType;
  11417. auto underlyingType = refType->GetUnderlyingType();
  11418. result = BfTypedValue(mBfIRBuilder->CreateLoad(result.mValue), underlyingType, true);
  11419. }
  11420. if (field.mResolvedType->IsObject())
  11421. {
  11422. result = LoadValue(result);
  11423. result.mKind = BfTypedValueKind_ThisValue;
  11424. }
  11425. else
  11426. {
  11427. if (fieldDef->mIsReadOnly)
  11428. result.mKind = BfTypedValueKind_ReadOnlyThisAddr;
  11429. else
  11430. result.mKind = BfTypedValueKind_ThisAddr;
  11431. }
  11432. return result;
  11433. }
  11434. }
  11435. return BfTypedValue();
  11436. }
  11437. if (useMethodState->mClosureState->mCapturing)
  11438. {
  11439. auto thisType = useMethodState->mLocals[0]->mResolvedType;
  11440. if (thisType->IsValueType())
  11441. return BfTypedValue(CreateAlloca(thisType), thisType, BfTypedValueKind_ThisAddr);
  11442. else
  11443. return BfTypedValue(GetDefaultValue(thisType), thisType, BfTypedValueKind_ThisValue);
  11444. }
  11445. }
  11446. auto localDef = useMethodState->mLocals[0];
  11447. auto curMethodOwner = mCurMethodInstance->mMethodInstanceGroup->mOwner;
  11448. if ((curMethodOwner->IsStruct()) || (curMethodOwner->IsTypedPrimitive()))
  11449. {
  11450. if ((localDef->mResolvedType->IsTypedPrimitive()) && (!mCurMethodInstance->mMethodDef->mIsMutating))
  11451. {
  11452. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, BfTypedValueKind_ReadOnlyThisValue);
  11453. }
  11454. if (localDef->mIsSplat)
  11455. {
  11456. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, BfTypedValueKind_ThisSplatHead);
  11457. }
  11458. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, localDef->mIsReadOnly ? BfTypedValueKind_ReadOnlyThisAddr : BfTypedValueKind_ThisAddr);
  11459. }
  11460. return BfTypedValue(thisValue, mCurMethodInstance->mMethodInstanceGroup->mOwner, BfTypedValueKind_ThisValue);
  11461. }
  11462. BfLocalVariable* BfModule::GetThisVariable()
  11463. {
  11464. if (mCurMethodState == NULL)
  11465. return NULL;
  11466. auto methodState = mCurMethodState->GetNonCaptureState();
  11467. if ((methodState->mLocals.size() > 0) && (methodState->mLocals[0]->mIsThis))
  11468. return methodState->mLocals[0];
  11469. return NULL;
  11470. }
  11471. bool BfModule::IsInGeneric()
  11472. {
  11473. return ((mCurMethodInstance != NULL) && (mCurMethodInstance->GetNumGenericArguments() != 0)) || (mCurTypeInstance->IsGenericTypeInstance());
  11474. }
  11475. bool BfModule::InDefinitionSection()
  11476. {
  11477. if (mCurTypeInstance != NULL)
  11478. {
  11479. if (mCurTypeInstance->IsUnspecializedTypeVariation())
  11480. return false;
  11481. }
  11482. return !IsInSpecializedSection();
  11483. }
  11484. bool BfModule::IsInSpecializedGeneric()
  11485. {
  11486. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsSpecializedType()))
  11487. return true;
  11488. if ((mCurMethodInstance == NULL) || (mCurMethodInstance->mIsUnspecialized))
  11489. return false;
  11490. return (mCurMethodInstance->GetNumGenericArguments() != 0);
  11491. }
  11492. bool BfModule::IsInSpecializedSection()
  11493. {
  11494. return IsInSpecializedGeneric() ||
  11495. ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL));
  11496. }
  11497. bool BfModule::IsInUnspecializedGeneric()
  11498. {
  11499. if (mCurMethodInstance != NULL)
  11500. return mCurMethodInstance->mIsUnspecialized;
  11501. return false;
  11502. }
  11503. //////////////////////////////////////////////////////////////////////////
  11504. BfIRValue BfModule::AllocLocalVariable(BfType* type, const StringImpl& name, bool doLifetimeEnd)
  11505. {
  11506. //if ((type->IsValuelessType()) || (type->IsMethodRef()))
  11507. if (type->IsValuelessType())
  11508. return mBfIRBuilder->GetFakeVal();
  11509. auto allocaInst = CreateAlloca(type, doLifetimeEnd, name.c_str());
  11510. if ((!doLifetimeEnd) && (WantsLifetimes()))
  11511. {
  11512. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  11513. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  11514. }
  11515. bool initLocalVariables = mCompiler->mOptions.mInitLocalVariables;
  11516. auto typeOptions = GetTypeOptions();
  11517. if (typeOptions != NULL)
  11518. initLocalVariables = typeOptions->Apply(initLocalVariables, BfOptionFlags_InitLocalVariables);
  11519. // Local variable inits are implicitly handled in the Beef Backend
  11520. if ((initLocalVariables) && (!IsTargetingBeefBackend()))
  11521. {
  11522. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  11523. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  11524. auto storeInst = mBfIRBuilder->CreateAlignedStore(GetDefaultValue(type), allocaInst, type->mAlign);
  11525. mBfIRBuilder->ClearDebugLocation(storeInst);
  11526. mBfIRBuilder->SetInsertPoint(prevBlock);
  11527. }
  11528. return allocaInst;
  11529. }
  11530. void BfModule::DoAddLocalVariable(BfLocalVariable* localVar)
  11531. {
  11532. localVar->mLocalVarIdx = (int)mCurMethodState->mLocals.size();
  11533. mCurMethodState->mLocals.push_back(localVar);
  11534. BfLocalVarEntry* localVarEntryPtr;
  11535. if (!mCurMethodState->mLocalVarSet.TryAdd(BfLocalVarEntry(localVar), &localVarEntryPtr))
  11536. {
  11537. localVar->mShadowedLocal = localVarEntryPtr->mLocalVar;
  11538. localVarEntryPtr->mLocalVar = localVar;
  11539. }
  11540. }
  11541. void BfModule::DoLocalVariableDebugInfo(BfLocalVariable* localVarDef, bool doAliasValue, BfIRValue declareBefore, BfIRInitType initType)
  11542. {
  11543. if ((mBfIRBuilder->DbgHasInfo()) &&
  11544. ((mCurMethodInstance == NULL) || (!mCurMethodInstance->mIsUnspecialized)) &&
  11545. (mHasFullDebugInfo) &&
  11546. ((mCurMethodState->mClosureState == NULL) || (!mCurMethodState->mClosureState->mCapturing)))
  11547. {
  11548. auto varType = localVarDef->mResolvedType;
  11549. if (localVarDef->mResolvedType->IsValuelessType())
  11550. {
  11551. }
  11552. else
  11553. {
  11554. bool isByAddr = false;
  11555. auto diValue = localVarDef->mValue;
  11556. if (localVarDef->mConstValue)
  11557. diValue = localVarDef->mConstValue;
  11558. else if (localVarDef->mAddr)
  11559. {
  11560. diValue = localVarDef->mAddr;
  11561. isByAddr = true;
  11562. }
  11563. auto diType = mBfIRBuilder->DbgGetType(localVarDef->mResolvedType);
  11564. bool didConstToMem = false;
  11565. bool isConstant = false;
  11566. if ((localVarDef->mIsReadOnly) && (localVarDef->mAddr))
  11567. diType = mBfIRBuilder->DbgCreateConstType(diType);
  11568. else if (localVarDef->mConstValue)
  11569. {
  11570. auto constant = mBfIRBuilder->GetConstant(localVarDef->mConstValue);
  11571. isConstant =
  11572. (constant->mConstType < BfConstType_GlobalVar) ||
  11573. (constant->mConstType == BfConstType_AggZero) ||
  11574. (constant->mConstType == BfConstType_Array);
  11575. if (isConstant)
  11576. {
  11577. if (localVarDef->mResolvedType->IsComposite())
  11578. {
  11579. mBfIRBuilder->PopulateType(localVarDef->mResolvedType);
  11580. auto constMem = mBfIRBuilder->ConstToMemory(localVarDef->mConstValue);
  11581. if (IsTargetingBeefBackend())
  11582. {
  11583. diValue = mBfIRBuilder->CreateAliasValue(constMem);
  11584. didConstToMem = true;
  11585. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  11586. }
  11587. else
  11588. {
  11589. isByAddr = true;
  11590. mBfIRBuilder->SaveDebugLocation();
  11591. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  11592. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  11593. mBfIRBuilder->ClearDebugLocation();
  11594. auto ptrType = CreatePointerType(localVarDef->mResolvedType);
  11595. auto addrVal = CreateAlloca(ptrType);
  11596. mBfIRBuilder->CreateStore(constMem, addrVal);
  11597. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  11598. diValue = addrVal;
  11599. didConstToMem = true;
  11600. mBfIRBuilder->SetInsertPoint(prevBlock);
  11601. mBfIRBuilder->RestoreDebugLocation();
  11602. }
  11603. }
  11604. if (mCompiler->mOptions.IsCodeView())
  11605. diType = mBfIRBuilder->DbgCreateConstType(diType);
  11606. }
  11607. }
  11608. if (!mBfIRBuilder->mIgnoreWrites)
  11609. {
  11610. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  11611. localVarDef->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, initType);
  11612. localVarDef->mDbgVarInst = diVariable;
  11613. if (mBfIRBuilder->HasDebugLocation())
  11614. {
  11615. if ((isConstant) && (!didConstToMem))
  11616. {
  11617. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(localVarDef->mConstValue, diVariable);
  11618. }
  11619. else
  11620. {
  11621. if ((IsTargetingBeefBackend()) && (doAliasValue))
  11622. {
  11623. diValue = mBfIRBuilder->CreateAliasValue(diValue);
  11624. mCurMethodState->mCurScope->mDeferredLifetimeEnds.Add(diValue);
  11625. }
  11626. if (isByAddr)
  11627. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertDeclare(diValue, diVariable, declareBefore);
  11628. else if (diValue)
  11629. {
  11630. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(diValue, diVariable);
  11631. }
  11632. else if (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU) // DWARF chokes on this:
  11633. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  11634. }
  11635. }
  11636. }
  11637. }
  11638. }
  11639. }
  11640. BfLocalVariable* BfModule::AddLocalVariableDef(BfLocalVariable* localVarDef, bool addDebugInfo, bool doAliasValue, BfIRValue declareBefore, BfIRInitType initType)
  11641. {
  11642. if ((localVarDef->mValue) && (!localVarDef->mAddr) && (IsTargetingBeefBackend()) && (!localVarDef->mResolvedType->IsValuelessType()))
  11643. {
  11644. if ((!localVarDef->mValue.IsConst()) &&
  11645. (!localVarDef->mValue.IsArg()) && (!localVarDef->mValue.IsFake()))
  11646. {
  11647. mBfIRBuilder->CreateValueScopeRetain(localVarDef->mValue);
  11648. mCurMethodState->mCurScope->mHadScopeValueRetain = true;
  11649. }
  11650. }
  11651. if (addDebugInfo)
  11652. DoLocalVariableDebugInfo(localVarDef, doAliasValue, declareBefore, initType);
  11653. localVarDef->mDeclBlock = mBfIRBuilder->GetInsertBlock();
  11654. DoAddLocalVariable(localVarDef);
  11655. auto rootMethodState = mCurMethodState->GetRootMethodState();
  11656. if (localVarDef->mLocalVarId == -1)
  11657. {
  11658. BF_ASSERT(rootMethodState->mCurLocalVarId >= 0);
  11659. localVarDef->mLocalVarId = rootMethodState->mCurLocalVarId++;
  11660. }
  11661. if ((localVarDef->mNameNode != NULL) && (mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  11662. mCompiler->mResolvePassData->mAutoComplete->CheckLocalDef(localVarDef->mNameNode, localVarDef);
  11663. if ((localVarDef->mNameNode != NULL) && (mCurMethodInstance != NULL))
  11664. {
  11665. bool isClosureProcessing = (mCurMethodState->mClosureState != NULL) && (!mCurMethodState->mClosureState->mCapturing);
  11666. if ((!isClosureProcessing) && (mCompiler->mResolvePassData != NULL) && (localVarDef->mNameNode != NULL))
  11667. mCompiler->mResolvePassData->HandleLocalReference(localVarDef->mNameNode, rootMethodState->mMethodInstance->GetOwner()->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, localVarDef->mLocalVarId);
  11668. }
  11669. return localVarDef;
  11670. }
  11671. void BfModule::CreateDIRetVal()
  11672. {
  11673. if (!WantsDebugInfo())
  11674. return;
  11675. /*if (!mCurMethodState->mRetVal)
  11676. {
  11677. if (mCurMethodInstance->mMethodDef->mName != "Ziggle")
  11678. return;
  11679. }*/
  11680. if ((mCurMethodState->mRetVal) || (mCurMethodState->mRetValAddr))
  11681. {
  11682. BfType* dbgType = mCurMethodInstance->mReturnType;
  11683. BfIRValue dbgValue = mCurMethodState->mRetVal.mValue;
  11684. if (mCurMethodInstance->GetStructRetIdx() != -1)
  11685. {
  11686. BF_ASSERT(mCurMethodState->mRetValAddr);
  11687. dbgType = CreatePointerType(dbgType);
  11688. dbgValue = mCurMethodState->mRetValAddr;
  11689. }
  11690. else
  11691. {
  11692. BF_ASSERT(!mCurMethodState->mRetValAddr);
  11693. }
  11694. mCurMethodState->mDIRetVal = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  11695. "__return", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(dbgType));
  11696. auto declareCall = mBfIRBuilder->DbgInsertDeclare(dbgValue, mCurMethodState->mDIRetVal);
  11697. }
  11698. }
  11699. void BfModule::CheckVariableDef(BfLocalVariable* variableDef)
  11700. {
  11701. if (variableDef->mName.IsEmpty())
  11702. return;
  11703. BfLocalVarEntry* localVarEntryPtr = NULL;
  11704. if ((mCurMethodState != NULL) && (mCurMethodState->mLocalVarSet.TryGet(BfLocalVarEntry(variableDef), &localVarEntryPtr)))
  11705. {
  11706. auto checkLocal = localVarEntryPtr->mLocalVar;
  11707. if ((checkLocal->mLocalVarIdx >= mCurMethodState->GetLocalStartIdx()) && (!checkLocal->mIsShadow))
  11708. {
  11709. BfError* error;
  11710. if (checkLocal->mIsImplicitParam)
  11711. return; // Ignore 'redefinition'
  11712. if (checkLocal->IsParam())
  11713. error = Fail(StrFormat("A parameter named '%s' has already been declared.", variableDef->mName.c_str()), variableDef->mNameNode);
  11714. else if (checkLocal->mLocalVarIdx < mCurMethodState->mCurScope->mLocalVarStart)
  11715. error = Fail(StrFormat("A variable named '%s' has already been declared in this parent's scope.", variableDef->mName.c_str()), variableDef->mNameNode);
  11716. else
  11717. error = Fail(StrFormat("A variable named '%s' has already been declared in this scope.", variableDef->mName.c_str()), variableDef->mNameNode);
  11718. if ((checkLocal->mNameNode != NULL) && (error != NULL))
  11719. mCompiler->mPassInstance->MoreInfo("Previous declaration", checkLocal->mNameNode);
  11720. return;
  11721. }
  11722. }
  11723. }
  11724. BfScopeData* BfModule::FindScope(BfAstNode* scopeName, BfMixinState* fromMixinState, bool allowAcrossDeferredBlock)
  11725. {
  11726. bool inMixinDecl = (mCurMethodInstance != NULL) && (mCurMethodInstance->IsMixin());
  11727. if (auto tokenNode = BfNodeDynCast<BfTokenNode>(scopeName))
  11728. {
  11729. if (tokenNode->GetToken() == BfToken_Colon)
  11730. {
  11731. if ((!allowAcrossDeferredBlock) && (mCurMethodState->mInDeferredBlock))
  11732. {
  11733. Fail("Cannot access method scope across deferred block boundary", scopeName);
  11734. return NULL;
  11735. }
  11736. return &mCurMethodState->mHeadScope;
  11737. }
  11738. else if (tokenNode->GetToken() == BfToken_Mixin)
  11739. {
  11740. if (fromMixinState == NULL)
  11741. {
  11742. if (mCurMethodInstance->mMethodDef->mMethodType != BfMethodType_Mixin)
  11743. Fail("'mixin' scope specifier can only be used within a mixin declaration", scopeName);
  11744. return mCurMethodState->mCurScope;
  11745. }
  11746. fromMixinState->mUsedInvocationScope = true;
  11747. return fromMixinState->mTargetScope;
  11748. }
  11749. else if (tokenNode->GetToken() == BfToken_New)
  11750. return NULL;
  11751. }
  11752. if (auto identifier = BfNodeDynCast<BfIdentifierNode>(scopeName))
  11753. {
  11754. auto findLabel = scopeName->ToString();
  11755. bool crossedDeferredBlock = false;
  11756. auto checkScope = mCurMethodState->mCurScope;
  11757. while (checkScope != NULL)
  11758. {
  11759. if (checkScope->mIsDeferredBlock)
  11760. crossedDeferredBlock = true;
  11761. if (checkScope->mLabel == findLabel)
  11762. {
  11763. if ((crossedDeferredBlock) && (!allowAcrossDeferredBlock))
  11764. {
  11765. Fail(StrFormat("Cannot access scope '%s' across deferred block boundary", findLabel.c_str()), scopeName);
  11766. return NULL;
  11767. }
  11768. return checkScope;
  11769. }
  11770. checkScope = checkScope->mPrevScope;
  11771. }
  11772. if (!inMixinDecl)
  11773. Fail(StrFormat("Unable to locate label '%s'", findLabel.c_str()), scopeName);
  11774. }
  11775. if (auto scopeNode = BfNodeDynCast<BfScopeNode>(scopeName))
  11776. {
  11777. return FindScope(scopeNode->mTargetNode, allowAcrossDeferredBlock);
  11778. }
  11779. return mCurMethodState->mCurScope;
  11780. }
  11781. BfScopeData* BfModule::FindScope(BfAstNode* scopeName, bool allowAcrossDeferredBlock)
  11782. {
  11783. return FindScope(scopeName, mCurMethodState->mMixinState, allowAcrossDeferredBlock);
  11784. }
  11785. BfBreakData* BfModule::FindBreakData(BfAstNode* scopeName)
  11786. {
  11787. auto scopeData = FindScope(scopeName, false);
  11788. if (scopeData == NULL)
  11789. return NULL;
  11790. int scopeDepth = scopeData->GetDepth();
  11791. // Find the first break data that is at or below the depth of our requested scope
  11792. auto breakData = mCurMethodState->mBreakData;
  11793. while ((breakData != NULL) && (scopeDepth < breakData->mScope->GetDepth()))
  11794. {
  11795. if (breakData->mScope->mIsConditional)
  11796. return NULL;
  11797. breakData = breakData->mPrevBreakData;
  11798. }
  11799. return breakData;
  11800. }
  11801. void BfModule::EmitLifetimeEnds(BfScopeData* scopeData)
  11802. {
  11803. // LLVM is stricter about the placement of these (ie: they can't occur after a 'ret')
  11804. if (!IsTargetingBeefBackend())
  11805. return;
  11806. for (auto lifetimeEnd : scopeData->mDeferredLifetimeEnds)
  11807. {
  11808. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  11809. }
  11810. }
  11811. void BfModule::ClearLifetimeEnds()
  11812. {
  11813. auto scopeData = mCurMethodState->mCurScope;
  11814. while (scopeData != NULL)
  11815. {
  11816. scopeData->mDeferredLifetimeEnds.Clear();
  11817. scopeData = scopeData->mPrevScope;
  11818. }
  11819. }
  11820. bool BfModule::WantsDebugInfo()
  11821. {
  11822. if ((mCurMethodInstance != NULL) &&
  11823. ((mCurMethodInstance->mIsUnspecialized) || (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)))
  11824. return false;
  11825. return (mBfIRBuilder->DbgHasInfo()) && (mHasFullDebugInfo) &&
  11826. ((mCurMethodState == NULL) || (mCurMethodState->mClosureState == NULL) || (!mCurMethodState->mClosureState->mCapturing));
  11827. }
  11828. BfTypeOptions* BfModule::GetTypeOptions()
  11829. {
  11830. if ((mCurMethodState != NULL) && (mCurMethodState->mMethodTypeOptions != NULL))
  11831. return mCurMethodState->mMethodTypeOptions;
  11832. return mSystem->GetTypeOptions(mCurTypeInstance->mTypeOptionsIdx);
  11833. }
  11834. BfReflectKind BfModule::GetUserReflectKind(BfTypeInstance* attrType)
  11835. {
  11836. BfReflectKind reflectKind = BfReflectKind_None;
  11837. if (attrType->mCustomAttributes != NULL)
  11838. {
  11839. for (auto& customAttr : attrType->mCustomAttributes->mAttributes)
  11840. {
  11841. if (customAttr.mType->mTypeDef->mName->ToString() == "AttributeUsageAttribute")
  11842. {
  11843. for (auto& prop : customAttr.mSetProperties)
  11844. {
  11845. auto propDef = prop.mPropertyRef.mTypeInstance->mTypeDef->mProperties[prop.mPropertyRef.mPropIdx];
  11846. if (propDef->mName == "ReflectUser")
  11847. {
  11848. if (prop.mParam.mValue.IsConst())
  11849. {
  11850. auto constant = attrType->mConstHolder->GetConstant(prop.mParam.mValue);
  11851. reflectKind = (BfReflectKind)(reflectKind | (BfReflectKind)constant->mInt32);
  11852. }
  11853. }
  11854. }
  11855. // Check for Flags arg
  11856. if (customAttr.mCtorArgs.size() < 2)
  11857. continue;
  11858. auto constant = attrType->mConstHolder->GetConstant(customAttr.mCtorArgs[1]);
  11859. if (constant == NULL)
  11860. continue;
  11861. if (constant->mTypeCode == BfTypeCode_Boolean)
  11862. continue;
  11863. if ((constant->mInt8 & BfCustomAttributeFlags_ReflectAttribute) != 0)
  11864. reflectKind = (BfReflectKind)(reflectKind | BfReflectKind_User);
  11865. }
  11866. }
  11867. }
  11868. return reflectKind;
  11869. }
  11870. BfReflectKind BfModule::GetReflectKind(BfReflectKind reflectKind, BfTypeInstance* typeInstance)
  11871. {
  11872. auto checkTypeInstance = typeInstance;
  11873. while (checkTypeInstance != NULL)
  11874. {
  11875. if (checkTypeInstance->mCustomAttributes != NULL)
  11876. {
  11877. auto checkReflectKind = BfReflectKind_None;
  11878. for (auto& customAttr : checkTypeInstance->mCustomAttributes->mAttributes)
  11879. {
  11880. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  11881. {
  11882. if (customAttr.mCtorArgs.size() > 0)
  11883. {
  11884. auto constant = checkTypeInstance->mConstHolder->GetConstant(customAttr.mCtorArgs[0]);
  11885. checkReflectKind = (BfReflectKind)((int)checkReflectKind | constant->mInt32);
  11886. }
  11887. else
  11888. {
  11889. checkReflectKind = BfReflectKind_All;
  11890. }
  11891. }
  11892. else
  11893. {
  11894. auto userReflectKind = GetUserReflectKind(customAttr.mType);
  11895. checkReflectKind = (BfReflectKind)(checkReflectKind | userReflectKind);
  11896. }
  11897. }
  11898. if ((checkTypeInstance == typeInstance) ||
  11899. ((checkReflectKind & BfReflectKind_ApplyToInnerTypes) != 0))
  11900. {
  11901. reflectKind = (BfReflectKind)(reflectKind | checkReflectKind);
  11902. }
  11903. }
  11904. for (auto ifaceEntry : typeInstance->mInterfaces)
  11905. {
  11906. if (ifaceEntry.mInterfaceType->mCustomAttributes != NULL)
  11907. {
  11908. auto iface = ifaceEntry.mInterfaceType;
  11909. auto customAttr = iface->mCustomAttributes->Get(mCompiler->mReflectAttributeTypeDef);
  11910. if (customAttr != NULL)
  11911. {
  11912. for (auto& prop : customAttr->mSetProperties)
  11913. {
  11914. auto propDef = prop.mPropertyRef.mTypeInstance->mTypeDef->mProperties[prop.mPropertyRef.mPropIdx];
  11915. if (propDef->mName == "ReflectImplementer")
  11916. {
  11917. if (prop.mParam.mValue.IsConst())
  11918. {
  11919. auto constant = iface->mConstHolder->GetConstant(prop.mParam.mValue);
  11920. reflectKind = (BfReflectKind)(reflectKind | (BfReflectKind)constant->mInt32);
  11921. }
  11922. }
  11923. }
  11924. }
  11925. }
  11926. }
  11927. checkTypeInstance = mContext->mUnreifiedModule->GetOuterType(checkTypeInstance);
  11928. }
  11929. return reflectKind;
  11930. }
  11931. bool BfModule::HasDeferredScopeCalls(BfScopeData* scope)
  11932. {
  11933. BfScopeData* checkScope = mCurMethodState->mCurScope;
  11934. while (checkScope != NULL)
  11935. {
  11936. if ((!checkScope->mDeferredCallEntries.IsEmpty()) || (!checkScope->mDeferredLifetimeEnds.empty()))
  11937. return true;
  11938. if (checkScope == scope)
  11939. break;
  11940. checkScope = checkScope->mPrevScope;
  11941. }
  11942. return false;
  11943. }
  11944. void BfModule::EmitDeferredScopeCalls(bool useSrcPositions, BfScopeData* scopeData, BfIRBlock doneBlock)
  11945. {
  11946. // Is there anything we need to do here?
  11947. if (mBfIRBuilder->mIgnoreWrites)
  11948. {
  11949. // Just visit deferred blocks
  11950. BfScopeData* checkScope = mCurMethodState->mCurScope;
  11951. while (checkScope != NULL)
  11952. {
  11953. BfDeferredCallEntry* deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  11954. while (deferredCallEntry != NULL)
  11955. {
  11956. if (deferredCallEntry->mDeferredBlock != NULL)
  11957. {
  11958. VisitEmbeddedStatement(deferredCallEntry->mDeferredBlock, NULL, BfEmbeddedStatementFlags_IsDeferredBlock);
  11959. }
  11960. deferredCallEntry = deferredCallEntry->mNext;
  11961. }
  11962. if (checkScope == scopeData)
  11963. break;
  11964. checkScope = checkScope->mPrevScope;
  11965. }
  11966. return;
  11967. }
  11968. // Why did we want to do SetIllegalSrcPos here?
  11969. // Don't we always want to step onto these instances?
  11970. // Find a case where we don't and perhaps only do it there.
  11971. // The downside was that 'EmitEnsureInstructionAt' on the end of block statements causes
  11972. // a (seemingly) unneeded NOP when we do SetIllegalSrcPos
  11973. //SetIllegalSrcPos();
  11974. bool setSrcPos = false;
  11975. bool wantsNop = true;
  11976. BfAstNode* deferCloseNode = NULL;
  11977. if (mCurMethodState->mInPostReturn)
  11978. {
  11979. // These won't get used, they are post-return
  11980. return;
  11981. }
  11982. SizedArray<BfIRValue, 8> deferredLifetimeEnds;
  11983. BfScopeData* scopeJumpBlock = NULL;
  11984. bool hadExtraDeferredLifetimeEnds = false;
  11985. auto _FlushLifetimeEnds = [&]()
  11986. {
  11987. for (auto lifetimeEnd : deferredLifetimeEnds)
  11988. {
  11989. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  11990. mBfIRBuilder->ClearDebugLocation_Last();
  11991. }
  11992. deferredLifetimeEnds.clear();
  11993. };
  11994. BfScopeData* checkScope = mCurMethodState->mCurScope;
  11995. while (checkScope != NULL)
  11996. {
  11997. if (checkScope->mCloseNode != NULL)
  11998. deferCloseNode = checkScope->mCloseNode;
  11999. if (doneBlock)
  12000. {
  12001. // Try to find a match where we've already emitted these calls and then jumped to the correct block
  12002. for (auto& checkHandler : checkScope->mDeferredHandlers)
  12003. {
  12004. if (checkHandler.mDoneBlock == doneBlock)
  12005. {
  12006. scopeJumpBlock = checkScope;
  12007. mBfIRBuilder->CreateBr(checkHandler.mHandlerBlock);
  12008. mBfIRBuilder->ClearDebugLocation_Last();
  12009. _FlushLifetimeEnds();
  12010. break;
  12011. }
  12012. }
  12013. if (scopeJumpBlock != NULL)
  12014. break;
  12015. }
  12016. bool hasWork = (checkScope->mSavedStack) || (checkScope->mDeferredCallEntries.mHead != NULL);
  12017. if (checkScope != scopeData) // Only emit a block for deferred lifetimes if we're going back beyond this entry
  12018. hasWork |= (!deferredLifetimeEnds.IsEmpty());
  12019. if (hasWork)
  12020. {
  12021. SetAndRestoreValue<BfScopeData*> prevScope(mCurMethodState->mCurScope, checkScope);
  12022. if (deferCloseNode != NULL)
  12023. {
  12024. UpdateSrcPos(deferCloseNode);
  12025. }
  12026. if (doneBlock)
  12027. {
  12028. bool crossingMixin = mCurMethodState->mCurScope->mMixinDepth != checkScope->mMixinDepth;
  12029. String blockName = "deferredCalls";
  12030. //blockName += StrFormat("_%d", mBfIRBuilder->mBlockCount);
  12031. BfDeferredHandler deferredHandler;
  12032. if ((!crossingMixin) && (deferredLifetimeEnds.IsEmpty()))
  12033. {
  12034. mBfIRBuilder->SaveDebugLocation();
  12035. mBfIRBuilder->ClearDebugLocation();
  12036. deferredHandler.mHandlerBlock = mBfIRBuilder->MaybeChainNewBlock(blockName);
  12037. mBfIRBuilder->RestoreDebugLocation();
  12038. }
  12039. else
  12040. {
  12041. // Definitely chain
  12042. deferredHandler.mHandlerBlock = mBfIRBuilder->CreateBlock(blockName);
  12043. mBfIRBuilder->CreateBr(deferredHandler.mHandlerBlock);
  12044. mBfIRBuilder->ClearDebugLocation_Last();
  12045. _FlushLifetimeEnds();
  12046. mBfIRBuilder->AddBlock(deferredHandler.mHandlerBlock);
  12047. mBfIRBuilder->SetInsertPoint(deferredHandler.mHandlerBlock);
  12048. }
  12049. deferredHandler.mDoneBlock = doneBlock;
  12050. if (!mBfIRBuilder->mIgnoreWrites)
  12051. checkScope->mDeferredHandlers.push_back(deferredHandler);
  12052. if (checkScope == &mCurMethodState->mHeadScope)
  12053. {
  12054. if (!mCurMethodState->mDIRetVal)
  12055. {
  12056. // 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
  12057. // be scoped to the physical method
  12058. /*if (deferCloseNode != NULL)
  12059. {
  12060. UpdateSrcPos(deferCloseNode);
  12061. }*/
  12062. CreateDIRetVal();
  12063. }
  12064. }
  12065. if (checkScope != mCurMethodState->mTailScope)
  12066. {
  12067. if (deferredHandler.mHandlerBlock.IsFake())
  12068. {
  12069. BF_ASSERT(mBfIRBuilder->mIgnoreWrites);
  12070. }
  12071. if (!mBfIRBuilder->mIgnoreWrites)
  12072. checkScope->mAtEndBlocks.push_back(deferredHandler.mHandlerBlock);
  12073. }
  12074. }
  12075. std::unordered_set<BfDeferredCallEntry*> handledSet;
  12076. BfDeferredCallEntry* deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  12077. while (deferredCallEntry != NULL)
  12078. {
  12079. BfDeferredCallEmitState deferredCallEmitState;
  12080. deferredCallEmitState.mCloseNode = deferCloseNode;
  12081. SetAndRestoreValue<BfDeferredCallEmitState*> prevDeferredCallEmitState(mCurMethodState->mDeferredCallEmitState, &deferredCallEmitState);
  12082. SetAndRestoreValue<bool> prevIgnoredWrites(mBfIRBuilder->mIgnoreWrites, deferredCallEntry->mIgnored);
  12083. if (deferCloseNode != NULL)
  12084. {
  12085. UpdateSrcPos(deferCloseNode);
  12086. }
  12087. if (wantsNop)
  12088. EmitEnsureInstructionAt();
  12089. wantsNop = false;
  12090. if (deferredCallEntry->mDeferredBlock != NULL)
  12091. {
  12092. auto itr = handledSet.insert(deferredCallEntry);
  12093. if (!itr.second)
  12094. {
  12095. // Already handled, can happen if we defer again within the block
  12096. deferredCallEntry = deferredCallEntry->mNext;
  12097. continue;
  12098. }
  12099. auto prevHead = checkScope->mDeferredCallEntries.mHead;
  12100. EmitDeferredCall(*deferredCallEntry, true);
  12101. if (prevHead != checkScope->mDeferredCallEntries.mHead)
  12102. {
  12103. // The list changed, start over and ignore anything we've already handled
  12104. deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  12105. }
  12106. else
  12107. deferredCallEntry = deferredCallEntry->mNext;
  12108. }
  12109. else
  12110. {
  12111. EmitDeferredCall(*deferredCallEntry, true);
  12112. deferredCallEntry = deferredCallEntry->mNext;
  12113. }
  12114. }
  12115. if (checkScope->mSavedStack)
  12116. {
  12117. checkScope->mSavedStackUses.Add(mBfIRBuilder->CreateStackRestore(checkScope->mSavedStack));
  12118. if (mCurMethodState->mDynStackRevIdx)
  12119. {
  12120. auto curValue = mBfIRBuilder->CreateLoad(mCurMethodState->mDynStackRevIdx);
  12121. auto newValue = mBfIRBuilder->CreateAdd(curValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  12122. mBfIRBuilder->CreateStore(newValue, mCurMethodState->mDynStackRevIdx);
  12123. }
  12124. }
  12125. }
  12126. if (!checkScope->mIsScopeHead)
  12127. {
  12128. // We manually emit function-level lifetime ends after the 'ret' in ProcessMethod
  12129. if (!IsTargetingBeefBackend())
  12130. {
  12131. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  12132. {
  12133. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  12134. }
  12135. }
  12136. else
  12137. {
  12138. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  12139. {
  12140. deferredLifetimeEnds.Add(lifetimeEnd);
  12141. }
  12142. }
  12143. }
  12144. if (checkScope == scopeData)
  12145. break;
  12146. checkScope = checkScope->mPrevScope;
  12147. }
  12148. if ((doneBlock) && (scopeJumpBlock == NULL))
  12149. {
  12150. mBfIRBuilder->CreateBr(doneBlock);
  12151. mBfIRBuilder->ClearDebugLocation_Last();
  12152. }
  12153. // Keeping CreateLifetimeEnds until the end messes up when we chain to old mDeferredHandlers that
  12154. // may have been created when other scope lifetimes were available
  12155. _FlushLifetimeEnds();
  12156. // Emit lifetimeEnds after the branch for Beef
  12157. /*if (IsTargetingBeefBackend())
  12158. {
  12159. bool needsEnsureInst = (!doneBlock) && (scopeJumpBlock == NULL);
  12160. BfScopeData* checkScope = mCurMethodState->mCurScope;
  12161. while (checkScope != NULL)
  12162. {
  12163. if (checkScope == scopeJumpBlock)
  12164. break;
  12165. if (!checkScope->mIsScopeHead)
  12166. {
  12167. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  12168. {
  12169. if (needsEnsureInst)
  12170. {
  12171. needsEnsureInst = false;
  12172. }
  12173. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  12174. }
  12175. }
  12176. if (checkScope == scopeData)
  12177. break;
  12178. checkScope = checkScope->mPrevScope;
  12179. }
  12180. }*/
  12181. }
  12182. void BfModule::MarkScopeLeft(BfScopeData* scopeData)
  12183. {
  12184. if (mCurMethodState->mDeferredLocalAssignData != NULL)
  12185. {
  12186. auto deferredLocalAssignData = mCurMethodState->mDeferredLocalAssignData;
  12187. while (deferredLocalAssignData != NULL)
  12188. {
  12189. if ((deferredLocalAssignData->mScopeData == NULL) || (deferredLocalAssignData->mScopeData->mScopeDepth < scopeData->mScopeDepth))
  12190. break;
  12191. if ((deferredLocalAssignData->mScopeData != NULL) && (deferredLocalAssignData->mScopeData->mScopeDepth == scopeData->mScopeDepth))
  12192. deferredLocalAssignData->mIsUnconditional = false;
  12193. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  12194. }
  12195. }
  12196. // When we leave a scope, mark those as assigned for deferred assignment purposes
  12197. for (int localIdx = scopeData->mLocalVarStart; localIdx < (int)mCurMethodState->mLocals.size(); localIdx++)
  12198. {
  12199. auto localDef = mCurMethodState->mLocals[localIdx];
  12200. if (localDef->mAssignedKind == BfLocalVarAssignKind_None)
  12201. {
  12202. bool hadAssignment = false;
  12203. if (mCurMethodState->mDeferredLocalAssignData != NULL)
  12204. {
  12205. for (auto& entry : mCurMethodState->mDeferredLocalAssignData->mAssignedLocals)
  12206. if (entry.mLocalVar == localDef)
  12207. hadAssignment = true;
  12208. }
  12209. if (!hadAssignment)
  12210. {
  12211. localDef->mHadExitBeforeAssign = true;
  12212. mCurMethodState->LocalDefined(localDef);
  12213. }
  12214. }
  12215. }
  12216. }
  12217. void BfModule::CreateReturn(BfIRValue val)
  12218. {
  12219. if (mCurMethodInstance->GetStructRetIdx() != -1)
  12220. {
  12221. // Store to sret
  12222. BF_ASSERT(val);
  12223. mBfIRBuilder->CreateStore(val, mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()));
  12224. mBfIRBuilder->CreateRetVoid();
  12225. return;
  12226. }
  12227. if (mCurMethodInstance->mReturnType->IsValuelessType())
  12228. {
  12229. mBfIRBuilder->CreateRetVoid();
  12230. return;
  12231. }
  12232. if (mCurMethodInstance->mReturnType->IsStruct())
  12233. {
  12234. BfTypeCode loweredReturnType = BfTypeCode_None;
  12235. BfTypeCode loweredReturnType2 = BfTypeCode_None;
  12236. mCurMethodInstance->GetLoweredReturnType(&loweredReturnType, &loweredReturnType2);
  12237. if (loweredReturnType != BfTypeCode_None)
  12238. {
  12239. auto retVal = CreateAlloca(mCurMethodInstance->mReturnType);
  12240. mBfIRBuilder->CreateStore(val, retVal);
  12241. auto irRetType = GetIRLoweredType(loweredReturnType, loweredReturnType2);
  12242. irRetType = mBfIRBuilder->GetPointerTo(irRetType);
  12243. auto ptrReturnValue = mBfIRBuilder->CreateBitCast(retVal, irRetType);
  12244. auto loadedReturnValue = mBfIRBuilder->CreateLoad(ptrReturnValue);
  12245. mBfIRBuilder->CreateRet(loadedReturnValue);
  12246. return;
  12247. }
  12248. }
  12249. BF_ASSERT(val);
  12250. mBfIRBuilder->CreateRet(val);
  12251. }
  12252. void BfModule::EmitReturn(BfIRValue val)
  12253. {
  12254. if (mCurMethodState->mIRExitBlock)
  12255. {
  12256. if (!mCurMethodInstance->mReturnType->IsValuelessType())
  12257. {
  12258. if (val) // We allow for val to be empty if we know we've already written the value to mRetVal
  12259. {
  12260. BfIRValue retVal = mCurMethodState->mRetVal.mValue;
  12261. if (!mCurMethodState->mRetVal)
  12262. retVal = mBfIRBuilder->CreateLoad(mCurMethodState->mRetValAddr);
  12263. mBfIRBuilder->CreateStore(val, retVal);
  12264. }
  12265. }
  12266. EmitDeferredScopeCalls(true, NULL, mCurMethodState->mIRExitBlock);
  12267. }
  12268. else
  12269. {
  12270. EmitDeferredScopeCalls(false, NULL);
  12271. if (val)
  12272. {
  12273. if (mCurMethodInstance->mReturnType->IsValuelessType())
  12274. mBfIRBuilder->CreateRetVoid();
  12275. else
  12276. mBfIRBuilder->CreateRet(val);
  12277. }
  12278. }
  12279. mCurMethodState->SetHadReturn(true);
  12280. mCurMethodState->mLeftBlockUncond = true;
  12281. }
  12282. void BfModule::EmitDefaultReturn()
  12283. {
  12284. if (mCurMethodState->mInDeferredBlock)
  12285. return;
  12286. if (mCurMethodState->mIRExitBlock)
  12287. {
  12288. EmitDeferredScopeCalls(true, NULL, mCurMethodState->mIRExitBlock);
  12289. }
  12290. else
  12291. {
  12292. if (mCurMethodInstance->mReturnType->IsVoid())
  12293. mBfIRBuilder->CreateRetVoid();
  12294. else if (mCurMethodInstance->GetStructRetIdx() == -1)
  12295. mBfIRBuilder->CreateRet(GetDefaultValue(mCurMethodInstance->mReturnType));
  12296. }
  12297. mCurMethodState->SetHadReturn(true);
  12298. mCurMethodState->mLeftBlockUncond = true;
  12299. }
  12300. void BfModule::AssertErrorState()
  12301. {
  12302. if (mIgnoreErrors)
  12303. return;
  12304. if (mHadBuildError)
  12305. return;
  12306. if (mCurTypeInstance != NULL)
  12307. {
  12308. if (mCurTypeInstance->IsUnspecializedTypeVariation())
  12309. return;
  12310. }
  12311. if (mCurMethodInstance != NULL)
  12312. {
  12313. if (mCurMethodInstance->IsOrInUnspecializedVariation())
  12314. return;
  12315. if (mCurMethodInstance->mHasFailed)
  12316. return;
  12317. }
  12318. // We want the module to be marked as failed even if it's just an error in the parser
  12319. if (mCurMethodInstance != NULL)
  12320. mCurMethodInstance->mHasFailed = true;
  12321. mHadBuildError = true;
  12322. // We check for either the parsing to have failed (possibly on a previous run), or for the current instance to have failed
  12323. if (mCurTypeInstance != NULL)
  12324. {
  12325. if (mCurTypeInstance->mTypeFailed)
  12326. return;
  12327. if (mCurTypeInstance->mTypeDef->mSource->mParsingFailed)
  12328. return;
  12329. }
  12330. if (mCurMethodInstance != NULL)
  12331. {
  12332. if ((mCurMethodInstance->mMethodDef->mDeclaringType != NULL) && (mCurMethodInstance->mMethodDef->mDeclaringType->mSource->mParsingFailed))
  12333. return;
  12334. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL) && (mCurMethodState->mMixinState->mMixinMethodInstance->mMethodDef->mDeclaringType->mSource->mParsingFailed))
  12335. return;
  12336. }
  12337. if (mCompiler->IsAutocomplete())
  12338. return;
  12339. BF_ASSERT(mCompiler->mPassInstance->HasFailed());
  12340. }
  12341. void BfModule::AssertParseErrorState()
  12342. {
  12343. if (mCompiler->mRevision == 1)
  12344. AssertErrorState();
  12345. }
  12346. BfType* BfModule::GetDelegateReturnType(BfType* delegateType)
  12347. {
  12348. BF_ASSERT(delegateType->IsDelegate());
  12349. auto typeInst = delegateType->ToTypeInstance();
  12350. PopulateType(typeInst, BfPopulateType_DataAndMethods);
  12351. BfMethodInstance* invokeMethodInstance = GetRawMethodInstanceAtIdx(typeInst->ToTypeInstance(), 0, "Invoke");
  12352. return invokeMethodInstance->mReturnType;
  12353. }
  12354. BfMethodInstance* BfModule::GetDelegateInvokeMethod(BfTypeInstance* typeInstance)
  12355. {
  12356. return GetRawMethodInstanceAtIdx(typeInstance, 0, "Invoke");
  12357. }
  12358. void BfModule::CreateDelegateInvokeMethod()
  12359. {
  12360. // Clear out debug loc - otherwise we'll single step onto the delegate type declaration
  12361. //mBfIRBuilder->ClearDebugLocation();
  12362. SetIllegalSrcPos();
  12363. auto typeInstance = mCurTypeInstance;
  12364. auto memberFuncType = mBfIRBuilder->MapMethod(mCurMethodInstance);
  12365. SizedArray<BfIRType, 4> staticParamTypes;
  12366. SizedArray<BfIRValue, 4> staticFuncArgs;
  12367. SizedArray<BfIRValue, 4> memberFuncArgs;
  12368. auto multicastDelegateType = typeInstance->mBaseType;
  12369. if (multicastDelegateType->mFieldInstances.size() != 2)
  12370. {
  12371. AssertErrorState();
  12372. return;
  12373. }
  12374. auto multicastDelegate = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapType(multicastDelegateType));
  12375. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 2); // Load 'delegate.mTarget'
  12376. auto fieldVal = mBfIRBuilder->CreateLoad(fieldPtr);
  12377. BfExprEvaluator exprEvaluator(this);
  12378. SizedArray<BfIRType, 8> origParamTypes;
  12379. BfIRType origReturnType;
  12380. mCurMethodInstance->GetIRFunctionInfo(this, origReturnType, origParamTypes);
  12381. if (mCurMethodInstance->mReturnType->IsValueType())
  12382. mBfIRBuilder->PopulateType(mCurMethodInstance->mReturnType, BfIRPopulateType_Full);
  12383. if (mCurMethodInstance->GetStructRetIdx() != 0)
  12384. memberFuncArgs.push_back(BfIRValue()); // Push 'target'
  12385. int thisIdx = 0;
  12386. if (mCurMethodInstance->GetStructRetIdx() != -1)
  12387. {
  12388. thisIdx = mCurMethodInstance->GetStructRetIdx() ^ 1;
  12389. staticFuncArgs.push_back(mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()));
  12390. memberFuncArgs.push_back(mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()));
  12391. }
  12392. if (mCurMethodInstance->GetStructRetIdx() == 0)
  12393. memberFuncArgs.push_back(BfIRValue()); // Push 'target'
  12394. mCurMethodInstance->GetIRFunctionInfo(this, origReturnType, staticParamTypes, true);
  12395. for (int i = 1; i < (int)mCurMethodState->mLocals.size(); i++)
  12396. {
  12397. BfTypedValue localVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[i], true);
  12398. exprEvaluator.PushArg(localVal, staticFuncArgs);
  12399. exprEvaluator.PushArg(localVal, memberFuncArgs);
  12400. }
  12401. auto staticFunc = mBfIRBuilder->CreateFunctionType(origReturnType, staticParamTypes, false);
  12402. auto staticFuncPtr = mBfIRBuilder->GetPointerTo(staticFunc);
  12403. auto staticFuncPtrPtr = mBfIRBuilder->GetPointerTo(staticFuncPtr);
  12404. auto trueBB = mBfIRBuilder->CreateBlock("if.then", true);
  12405. auto falseBB = mBfIRBuilder->CreateBlock("if.else");
  12406. auto doneBB = mBfIRBuilder->CreateBlock("done");
  12407. auto checkTargetNull = mBfIRBuilder->CreateIsNotNull(fieldVal);
  12408. mBfIRBuilder->CreateCondBr(checkTargetNull, trueBB, falseBB);
  12409. BfIRValue nonStaticResult;
  12410. BfIRValue staticResult;
  12411. auto callingConv = GetIRCallingConvention(mCurMethodInstance);
  12412. /// Non-static invocation
  12413. {
  12414. auto memberFuncPtr = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapMethod(mCurMethodInstance));
  12415. auto memberFuncPtrPtr = mBfIRBuilder->GetPointerTo(memberFuncPtr);
  12416. mBfIRBuilder->SetInsertPoint(trueBB);
  12417. memberFuncArgs[thisIdx] = mBfIRBuilder->CreateBitCast(fieldVal, mBfIRBuilder->MapType(mCurTypeInstance));
  12418. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 1); // Load 'delegate.mFuncPtr'
  12419. auto funcPtrPtr = mBfIRBuilder->CreateBitCast(fieldPtr, memberFuncPtrPtr);
  12420. auto funcPtr = mBfIRBuilder->CreateLoad(funcPtrPtr);
  12421. nonStaticResult = mBfIRBuilder->CreateCall(funcPtr, memberFuncArgs);
  12422. if (mCurMethodInstance->GetStructRetIdx() != -1)
  12423. mBfIRBuilder->Call_AddAttribute(nonStaticResult, mCurMethodInstance->GetStructRetIdx() + 1, BfIRAttribute_StructRet);
  12424. if (callingConv != BfIRCallingConv_CDecl)
  12425. mBfIRBuilder->SetCallCallingConv(nonStaticResult, callingConv);
  12426. mCurMethodState->SetHadReturn(false);
  12427. mCurMethodState->mLeftBlockUncond = false;
  12428. mCurMethodState->mLeftBlockCond = false;
  12429. mBfIRBuilder->CreateBr(doneBB);
  12430. }
  12431. // Static invocation
  12432. {
  12433. mBfIRBuilder->AddBlock(falseBB);
  12434. mBfIRBuilder->SetInsertPoint(falseBB);
  12435. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 1); // Load 'delegate.mFuncPtr'
  12436. auto funcPtrPtr = mBfIRBuilder->CreateBitCast(fieldPtr, staticFuncPtrPtr);
  12437. auto funcPtr = mBfIRBuilder->CreateLoad(funcPtrPtr);
  12438. staticResult = mBfIRBuilder->CreateCall(funcPtr, staticFuncArgs);
  12439. if (mCurMethodInstance->GetStructRetIdx() != -1)
  12440. {
  12441. // Note: since this is a forced static invocation, we know the sret will be the first parameter
  12442. mBfIRBuilder->Call_AddAttribute(staticResult, 0 + 1, BfIRAttribute_StructRet);
  12443. }
  12444. if (callingConv == BfIRCallingConv_ThisCall)
  12445. callingConv = BfIRCallingConv_CDecl;
  12446. if (callingConv != BfIRCallingConv_CDecl)
  12447. mBfIRBuilder->SetCallCallingConv(staticResult, callingConv);
  12448. mCurMethodState->SetHadReturn(false);
  12449. mCurMethodState->mLeftBlockUncond = false;
  12450. mCurMethodState->mLeftBlockCond = false;
  12451. mBfIRBuilder->CreateBr(doneBB);
  12452. }
  12453. mBfIRBuilder->AddBlock(doneBB);
  12454. mBfIRBuilder->SetInsertPoint(doneBB);
  12455. if ((mCurMethodInstance->mReturnType->IsValuelessType()) || (mCurMethodInstance->GetStructRetIdx() != -1))
  12456. {
  12457. mBfIRBuilder->CreateRetVoid();
  12458. }
  12459. else
  12460. {
  12461. BfIRType loweredIRReturnType;
  12462. BfTypeCode loweredTypeCode = BfTypeCode_None;
  12463. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  12464. if (mCurMethodInstance->GetLoweredReturnType(&loweredTypeCode, &loweredTypeCode2))
  12465. loweredIRReturnType = GetIRLoweredType(loweredTypeCode, loweredTypeCode2);
  12466. else
  12467. loweredIRReturnType = mBfIRBuilder->MapType(mCurMethodInstance->mReturnType);
  12468. auto phi = mBfIRBuilder->CreatePhi(loweredIRReturnType, 2);
  12469. mBfIRBuilder->AddPhiIncoming(phi, nonStaticResult, trueBB);
  12470. mBfIRBuilder->AddPhiIncoming(phi, staticResult, falseBB);
  12471. mBfIRBuilder->CreateRet(phi);
  12472. }
  12473. }
  12474. // "Interested" here means every method for a normal compile, and just the method the cursor is on for autocompletion
  12475. bool BfModule::IsInterestedInMethod(BfTypeInstance* typeInstance, BfMethodDef* methodDef)
  12476. {
  12477. auto typeDef = typeInstance->mTypeDef;
  12478. auto methodDeclaration = methodDef->mMethodDeclaration;
  12479. if (!mCompiler->mIsResolveOnly)
  12480. return true;
  12481. if (typeInstance->IsGenericTypeInstance())
  12482. {
  12483. // We only really want to process the unspecialized type for autocompletion
  12484. if ((!typeInstance->IsUnspecializedType()) || (typeInstance->IsUnspecializedTypeVariation()))
  12485. return false;
  12486. }
  12487. BfAstNode* checkNode = methodDeclaration;
  12488. if (methodDeclaration == NULL)
  12489. checkNode = methodDef->mBody;
  12490. if ((mCompiler->mResolvePassData->mParser != NULL) && (typeDef->mTypeDeclaration->IsFromParser(mCompiler->mResolvePassData->mParser)))
  12491. {
  12492. if (mCompiler->mResolvePassData->mAutoComplete == NULL)
  12493. return true;
  12494. }
  12495. return false;
  12496. }
  12497. void BfModule::CalcAppendAlign(BfMethodInstance* methodInst)
  12498. {
  12499. methodInst->mAppendAllocAlign = 1;
  12500. }
  12501. BfTypedValue BfModule::TryConstCalcAppend(BfMethodInstance* methodInst, SizedArrayImpl<BfIRValue>& args)
  12502. {
  12503. BP_ZONE("BfModule::TryConstCalcAppend");
  12504. if (mCompiler->mIsResolveOnly)
  12505. return BfTypedValue();
  12506. // We want to regenerate all ctor calls when the method internals change
  12507. {
  12508. auto checkTypeInst = methodInst->GetOwner();
  12509. while (checkTypeInst->mTypeDef->mHasAppendCtor)
  12510. {
  12511. AddDependency(checkTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_InlinedCall);
  12512. checkTypeInst = GetBaseType(checkTypeInst);
  12513. }
  12514. }
  12515. if (!methodInst->mMayBeConst)
  12516. return BfTypedValue();
  12517. // Do we need to iterate in order to resolve mAppendAllocAlign?
  12518. bool isFirstRun = methodInst->mAppendAllocAlign < 0;
  12519. bool wasAllConst = true;
  12520. int argIdx = 0;
  12521. int paramIdx = 0;
  12522. while (true)
  12523. {
  12524. if (argIdx >= (int)args.size())
  12525. break;
  12526. auto paramType = methodInst->GetParamType(paramIdx);
  12527. PopulateType(paramType);
  12528. int argCount = 0;
  12529. if (!paramType->IsValuelessType())
  12530. {
  12531. if (methodInst->GetParamIsSplat(paramIdx))
  12532. argCount = paramType->GetSplatCount();
  12533. else
  12534. argCount = 1;
  12535. for (int argOfs = 0; argOfs < argCount; argOfs++)
  12536. {
  12537. auto arg = args[argIdx + argOfs];
  12538. if (!arg.IsConst())
  12539. {
  12540. wasAllConst = false;
  12541. if (!isFirstRun)
  12542. {
  12543. auto& param = methodInst->mParams[argIdx];
  12544. if (param.mReferencedInConstPass)
  12545. {
  12546. // If this param is required as part of the const calculation then
  12547. // we require that it be const...
  12548. return BfTypedValue();
  12549. }
  12550. }
  12551. }
  12552. }
  12553. }
  12554. paramIdx++;
  12555. argIdx += argCount;
  12556. }
  12557. auto methodDef = methodInst->mMethodDef;
  12558. auto methodDecl = methodDef->GetMethodDeclaration();
  12559. auto methodDeclBlock = BfNodeDynCast<BfBlock>(methodDecl->mBody);
  12560. if (methodDeclBlock == NULL)
  12561. return GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr)); // Must not have an append alloc at all!
  12562. BfTypedValue constValue;
  12563. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  12564. auto checkState = mCurMethodState->mConstResolveState;
  12565. while (checkState != NULL)
  12566. {
  12567. if (checkState->mMethodInstance == methodInst)
  12568. {
  12569. return BfTypedValue();
  12570. }
  12571. checkState = checkState->mPrevConstResolveState;
  12572. }
  12573. //auto accumValue = GetConstValue(0);
  12574. bool failed = false;
  12575. //
  12576. {
  12577. BfConstResolveState constResolveState;
  12578. constResolveState.mMethodInstance = methodInst;
  12579. constResolveState.mPrevConstResolveState = mCurMethodState->mConstResolveState;
  12580. SetAndRestoreValue<bool> ignoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  12581. BfMethodState methodState;
  12582. SetAndRestoreValue<BfTypeInstance*> prevTypeInst(mCurTypeInstance, methodInst->GetOwner());
  12583. SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, methodInst);
  12584. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  12585. methodState.mTempKind = BfMethodState::TempKind_NonStatic;
  12586. methodState.mConstResolveState = &constResolveState;
  12587. int argIdx = 0;
  12588. for (int paramIdx = 0; paramIdx < methodInst->GetParamCount(); paramIdx++)
  12589. {
  12590. if (methodInst->GetParamKind(paramIdx) == BfParamKind_AppendIdx)
  12591. continue;
  12592. auto paramType = methodInst->GetParamType(paramIdx);
  12593. // Fix this after we allow structs to be consts
  12594. //BF_ASSERT(!paramType->IsSplattable());
  12595. BfLocalVariable* localVar = new BfLocalVariable();
  12596. localVar->mName = methodInst->GetParamName(paramIdx);
  12597. localVar->mResolvedType = paramType;
  12598. localVar->mConstValue = args[argIdx];
  12599. localVar->mParamIdx = paramIdx;
  12600. AddLocalVariableDef(localVar);
  12601. argIdx++;
  12602. }
  12603. AppendAllocVisitor appendAllocVisitor;
  12604. appendAllocVisitor.mConstAccum = GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr));
  12605. appendAllocVisitor.mIsFirstConstPass = isFirstRun;
  12606. BfTypedValue baseCtorAppendValue = CallBaseCtorCalc(true);
  12607. if (baseCtorAppendValue)
  12608. {
  12609. if (baseCtorAppendValue.mValue.IsFake())
  12610. appendAllocVisitor.mFailed = true;
  12611. else
  12612. appendAllocVisitor.mConstAccum = baseCtorAppendValue;
  12613. }
  12614. appendAllocVisitor.mModule = this;
  12615. appendAllocVisitor.VisitChild(methodDecl->mBody);
  12616. if (!appendAllocVisitor.mFailed)
  12617. constValue = appendAllocVisitor.mConstAccum;
  12618. if (isFirstRun)
  12619. mCurMethodInstance->mEndingAppendAllocAlign = appendAllocVisitor.mCurAppendAlign;
  12620. if (isFirstRun)
  12621. {
  12622. for (int paramIdx = 0; paramIdx < methodInst->GetParamCount(); paramIdx++)
  12623. {
  12624. auto localVar = mCurMethodState->mLocals[paramIdx];
  12625. if (localVar->mReadFromId != -1)
  12626. {
  12627. auto& param = methodInst->mParams[paramIdx];
  12628. param.mReferencedInConstPass = true;
  12629. }
  12630. }
  12631. }
  12632. }
  12633. mBfIRBuilder->SetInsertPoint(prevBlock);
  12634. if (!constValue)
  12635. {
  12636. // If we did a 'force' then some params may not have been const -- only clear mMayBeConst if we had
  12637. // all-const args
  12638. if (wasAllConst)
  12639. {
  12640. methodInst->mMayBeConst = false;
  12641. }
  12642. }
  12643. return constValue;
  12644. }
  12645. BfTypedValue BfModule::CallBaseCtorCalc(bool constOnly)
  12646. {
  12647. // Any errors should only be shown in the actual CTOR call
  12648. SetAndRestoreValue<bool> prevIgnoreWrites(mIgnoreErrors, true);
  12649. auto methodDef = mCurMethodInstance->mMethodDef;
  12650. BF_ASSERT((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend));
  12651. auto ctorDeclaration = (BfConstructorDeclaration*)methodDef->mMethodDeclaration;
  12652. BfCustomAttributes* customAttributes = NULL;
  12653. defer(delete customAttributes);
  12654. BfInvocationExpression* ctorInvocation = NULL;
  12655. if (ctorDeclaration != NULL)
  12656. {
  12657. ctorInvocation = BfNodeDynCast<BfInvocationExpression>(ctorDeclaration->mInitializer);
  12658. if (auto attributedExpr = BfNodeDynCast<BfAttributedExpression>(ctorDeclaration->mInitializer))
  12659. {
  12660. ctorInvocation = BfNodeDynCast<BfInvocationExpression>(attributedExpr->mExpression);
  12661. customAttributes = GetCustomAttributes(attributedExpr->mAttributes, BfAttributeTargets_MemberAccess);
  12662. }
  12663. }
  12664. BfTypeInstance* targetType = NULL;
  12665. if (ctorInvocation != NULL)
  12666. {
  12667. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorInvocation->mTarget);
  12668. targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  12669. }
  12670. else
  12671. targetType = mCurTypeInstance->mBaseType;
  12672. if ((targetType == NULL) || (targetType == mContext->mBfObjectType))
  12673. return NULL;
  12674. auto targetRefNode = methodDef->GetRefNode();
  12675. BfType* targetThisType = targetType;
  12676. BfTypedValue target(mBfIRBuilder->GetFakeVal(), targetThisType);
  12677. BfExprEvaluator exprEvaluator(this);
  12678. BfResolvedArgs argValues;
  12679. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL))
  12680. {
  12681. argValues.Init(&ctorInvocation->mArguments);
  12682. }
  12683. //
  12684. {
  12685. }
  12686. BfFunctionBindResult bindResult;
  12687. bindResult.mSkipThis = true;
  12688. bindResult.mWantsArgs = true;
  12689. {
  12690. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  12691. exprEvaluator.ResolveArgValues(argValues, BfResolveArgFlag_DeferParamEval);
  12692. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(exprEvaluator.mFunctionBindResult, &bindResult);
  12693. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, true);
  12694. }
  12695. if (bindResult.mMethodInstance == NULL)
  12696. {
  12697. AssertErrorState();
  12698. return BfTypedValue();
  12699. }
  12700. if (!bindResult.mMethodInstance->mMethodDef->mHasAppend)
  12701. {
  12702. return BfTypedValue();
  12703. }
  12704. BF_ASSERT(bindResult.mIRArgs[0].IsFake());
  12705. bindResult.mIRArgs.RemoveAt(0);
  12706. auto calcAppendMethodModule = GetMethodInstanceAtIdx(bindResult.mMethodInstance->GetOwner(), bindResult.mMethodInstance->mMethodDef->mIdx + 1, BF_METHODNAME_CALCAPPEND);
  12707. BfTypedValue appendSizeTypedValue = TryConstCalcAppend(calcAppendMethodModule.mMethodInstance, bindResult.mIRArgs);
  12708. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mAppendAllocAlign >= 0);
  12709. mCurMethodInstance->mAppendAllocAlign = BF_MAX((int)mCurMethodInstance->mAppendAllocAlign, calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  12710. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign > -1);
  12711. mCurMethodState->mCurAppendAlign = BF_MAX(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign, 0);
  12712. if (appendSizeTypedValue)
  12713. return appendSizeTypedValue;
  12714. if (constOnly)
  12715. return BfTypedValue(mBfIRBuilder->GetFakeVal(), GetPrimitiveType(BfTypeCode_IntPtr));
  12716. bool needsRecalc = false;
  12717. for (auto irArg : bindResult.mIRArgs)
  12718. {
  12719. if (irArg.IsFake())
  12720. needsRecalc = true;
  12721. }
  12722. auto calcAppendArgs = bindResult.mIRArgs;
  12723. if (needsRecalc)
  12724. {
  12725. // Do it again, but without mIgnoreWrites set
  12726. BfResolvedArgs argValues;
  12727. argValues.Init(&ctorInvocation->mArguments);
  12728. exprEvaluator.ResolveArgValues(argValues, BfResolveArgFlag_DeferParamEval);
  12729. BfFunctionBindResult bindResult;
  12730. bindResult.mSkipThis = true;
  12731. bindResult.mWantsArgs = true;
  12732. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(exprEvaluator.mFunctionBindResult, &bindResult);
  12733. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, true);
  12734. BF_ASSERT(bindResult.mIRArgs[0].IsFake());
  12735. bindResult.mIRArgs.RemoveAt(0);
  12736. calcAppendArgs = bindResult.mIRArgs;
  12737. }
  12738. BF_ASSERT(calcAppendMethodModule.mFunc);
  12739. appendSizeTypedValue = exprEvaluator.CreateCall(calcAppendMethodModule.mMethodInstance, calcAppendMethodModule.mFunc, false, calcAppendArgs);
  12740. BF_ASSERT(appendSizeTypedValue.mType == GetPrimitiveType(BfTypeCode_IntPtr));
  12741. return appendSizeTypedValue;
  12742. }
  12743. // This method never throws errors - it relies on the proper ctor actually throwing the errors
  12744. void BfModule::EmitCtorCalcAppend()
  12745. {
  12746. if (mCompiler->mIsResolveOnly)
  12747. return;
  12748. auto methodDef = mCurMethodInstance->mMethodDef;
  12749. auto methodDecl = methodDef->GetMethodDeclaration();
  12750. Array<BfAstNode*> deferredNodeList;
  12751. auto methodDeclBlock = BfNodeDynCast<BfBlock>(methodDecl->mBody);
  12752. if (methodDeclBlock == NULL)
  12753. return;
  12754. AppendAllocVisitor appendAllocVisitor;
  12755. auto baseCalcAppend = CallBaseCtorCalc(false);
  12756. if (baseCalcAppend)
  12757. {
  12758. mBfIRBuilder->CreateStore(baseCalcAppend.mValue, mCurMethodState->mRetVal.mValue);
  12759. }
  12760. appendAllocVisitor.mModule = this;
  12761. appendAllocVisitor.VisitChild(methodDecl->mBody);
  12762. }
  12763. void BfModule::CreateStaticCtor()
  12764. {
  12765. auto typeDef = mCurTypeInstance->mTypeDef;
  12766. auto methodDef = mCurMethodInstance->mMethodDef;
  12767. BfIRBlock exitBB;
  12768. if ((HasCompiledOutput()) && (!mCurMethodInstance->mIsUnspecialized) && (mCurMethodInstance->mChainType != BfMethodChainType_ChainMember))
  12769. {
  12770. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  12771. auto didStaticInitVarAddr = mBfIRBuilder->CreateGlobalVariable(
  12772. mBfIRBuilder->MapType(boolType),
  12773. false,
  12774. BfIRLinkageType_Internal,
  12775. GetDefaultValue(boolType),
  12776. "didStaticInit");
  12777. auto initBB = mBfIRBuilder->CreateBlock("init", true);
  12778. mCurMethodState->mIRExitBlock = mBfIRBuilder->CreateBlock("exit", true);
  12779. auto didStaticInitVar = mBfIRBuilder->CreateLoad(didStaticInitVarAddr);
  12780. mBfIRBuilder->CreateCondBr(didStaticInitVar, mCurMethodState->mIRExitBlock, initBB);
  12781. mBfIRBuilder->SetInsertPoint(initBB);
  12782. mBfIRBuilder->CreateStore(GetConstValue(1, boolType), didStaticInitVarAddr);
  12783. }
  12784. // Do DLL imports
  12785. if (!mDllImportEntries.empty())
  12786. {
  12787. auto internalType = ResolveTypeDef(mCompiler->mInternalTypeDef);
  12788. PopulateType(internalType);
  12789. auto getSharedProcAddressInstance = GetMethodByName(internalType->ToTypeInstance(), "GetSharedProcAddress");
  12790. if (!getSharedProcAddressInstance)
  12791. {
  12792. if (!mCompiler->mPassInstance->HasFailed())
  12793. Fail("Internal error: System.Internal doesn't contain LoadSharedLibrary method");
  12794. }
  12795. }
  12796. // Fill in initializer values
  12797. if ((!mCompiler->mIsResolveOnly) || (mCompiler->mResolvePassData->mAutoComplete == NULL))
  12798. {
  12799. for (auto fieldDef : typeDef->mFields)
  12800. {
  12801. if ((!fieldDef->mIsConst) && (fieldDef->mIsStatic) && (fieldDef->mInitializer != NULL))
  12802. {
  12803. // For extensions, only handle these fields in the appropriate extension
  12804. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  12805. continue;
  12806. UpdateSrcPos(fieldDef->mInitializer);
  12807. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  12808. if (!fieldInst->mFieldIncluded)
  12809. continue;
  12810. if (fieldInst->mResolvedType->IsVar())
  12811. {
  12812. continue;
  12813. }
  12814. GetFieldInitializerValue(fieldInst, NULL, NULL, NULL, true);
  12815. }
  12816. }
  12817. }
  12818. else
  12819. {
  12820. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  12821. {
  12822. if (tempTypeDef->mFullName == typeDef->mFullName)
  12823. {
  12824. for (auto fieldDef : tempTypeDef->mFields)
  12825. {
  12826. if ((fieldDef->mIsStatic) && (!fieldDef->mIsConst))
  12827. {
  12828. if (fieldDef->mInitializer != NULL)
  12829. {
  12830. if (mCompiler->mResolvePassData->mSourceClassifier != NULL)
  12831. {
  12832. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(fieldDef->mInitializer, BfSourceElementType_Normal);
  12833. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(fieldDef->mInitializer);
  12834. }
  12835. BfType* wantType = NULL;
  12836. if ((!BfNodeIsA<BfVarTypeReference>(fieldDef->mTypeRef)) && (!BfNodeIsA<BfLetTypeReference>(fieldDef->mTypeRef)))
  12837. {
  12838. wantType = ResolveTypeRef(fieldDef->mTypeRef);
  12839. }
  12840. CreateValueFromExpression(fieldDef->mInitializer, wantType, BfEvalExprFlags_FieldInitializer);
  12841. }
  12842. }
  12843. }
  12844. }
  12845. }
  12846. }
  12847. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  12848. CallChainedMethods(mCurMethodInstance, false);
  12849. }
  12850. void BfModule::EmitDtorBody()
  12851. {
  12852. if (mCurTypeInstance->IsClosure())
  12853. {
  12854. BfFieldInstance* fieldInstance = &mCurTypeInstance->mFieldInstances.back();
  12855. BF_ASSERT(fieldInstance->GetFieldDef()->mName == "__dtorThunk");
  12856. auto thisVal = GetThis();
  12857. auto dtorThunkPtr = mBfIRBuilder->CreateInBoundsGEP(thisVal.mValue, 0, fieldInstance->mDataIdx);
  12858. auto dtorThunk = mBfIRBuilder->CreateLoad(dtorThunkPtr);
  12859. auto funcPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapMethod(mCurMethodInstance));
  12860. auto dtorPtr = mBfIRBuilder->CreateBitCast(dtorThunk, funcPtrType);
  12861. SizedArray<BfIRValue, 1> args;
  12862. args.push_back(thisVal.mValue);
  12863. auto result = mBfIRBuilder->CreateCall(dtorPtr, args);
  12864. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_CDecl);
  12865. // Fall through to Object::~this call
  12866. auto dtorFunc = GetMethodByName(mContext->mBfObjectType, "~this");
  12867. auto basePtr = mBfIRBuilder->CreateBitCast(thisVal.mValue, mBfIRBuilder->MapTypeInstPtr(mContext->mBfObjectType));
  12868. SizedArray<BfIRValue, 1> vals = { basePtr };
  12869. result = mBfIRBuilder->CreateCall(dtorFunc.mFunc, vals);
  12870. mBfIRBuilder->SetCallCallingConv(result, GetIRCallingConvention(dtorFunc.mMethodInstance));
  12871. mBfIRBuilder->SetTailCall(result);
  12872. return;
  12873. }
  12874. auto typeDef = mCurTypeInstance->mTypeDef;
  12875. auto methodDef = mCurMethodInstance->mMethodDef;
  12876. auto methodDeclaration = methodDef->GetMethodDeclaration();
  12877. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  12878. CallChainedMethods(mCurMethodInstance, true);
  12879. if (auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody))
  12880. {
  12881. VisitEmbeddedStatement(bodyBlock);
  12882. if (bodyBlock->mCloseBrace != NULL)
  12883. {
  12884. UpdateSrcPos(bodyBlock->mCloseBrace);
  12885. }
  12886. }
  12887. else
  12888. {
  12889. if (methodDeclaration != NULL)
  12890. UpdateSrcPos(methodDeclaration);
  12891. else if (typeDef->mTypeDeclaration != NULL)
  12892. UpdateSrcPos(typeDef->mTypeDeclaration);
  12893. if ((methodDeclaration != NULL) && (methodDeclaration->mFatArrowToken != NULL))
  12894. {
  12895. Fail("Destructors cannot have expression bodies", methodDeclaration->mFatArrowToken, true);
  12896. }
  12897. }
  12898. if ((!mCompiler->mIsResolveOnly) || (mCompiler->mResolvePassData->mAutoComplete == NULL))
  12899. {
  12900. for (int fieldIdx = (int)mCurTypeInstance->mFieldInstances.size() - 1; fieldIdx >= 0; fieldIdx--)
  12901. {
  12902. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldIdx];
  12903. auto fieldDef = fieldInst->GetFieldDef();
  12904. if ((fieldDef != NULL) && (fieldDef->mIsStatic == methodDef->mIsStatic) && (fieldDef->mFieldDeclaration != NULL) && (fieldDef->mFieldDeclaration->mFieldDtor != NULL))
  12905. {
  12906. if (fieldDef->mDeclaringType != mCurMethodInstance->mMethodDef->mDeclaringType)
  12907. {
  12908. BF_ASSERT(mCurTypeInstance->mTypeDef->mIsCombinedPartial);
  12909. continue;
  12910. }
  12911. if ((!methodDef->mIsStatic) && (mCurTypeInstance->IsValueType()))
  12912. {
  12913. Fail("Structs cannot have field destructors", fieldDef->mFieldDeclaration->mFieldDtor->mTildeToken, true);
  12914. }
  12915. SetAndRestoreValue<BfFilePosition> prevFilePos(mCurFilePosition);
  12916. auto fieldDtor = fieldDef->mFieldDeclaration->mFieldDtor;
  12917. if ((fieldDef->mIsStatic) != (methodDef->mIsStatic))
  12918. continue;
  12919. UpdateSrcPos(fieldDtor);
  12920. BfScopeData scopeData;
  12921. mCurMethodState->AddScope(&scopeData);
  12922. NewScopeState();
  12923. UpdateSrcPos(fieldDtor);
  12924. bool hasDbgInfo = (!fieldDef->mIsConst);
  12925. if (hasDbgInfo)
  12926. {
  12927. mBfIRBuilder->SaveDebugLocation();
  12928. mBfIRBuilder->ClearDebugLocation();
  12929. }
  12930. BfIRValue value;
  12931. if (fieldDef->mIsStatic)
  12932. {
  12933. value = ReferenceStaticField(fieldInst).mValue;
  12934. }
  12935. else
  12936. {
  12937. if (!mCurTypeInstance->IsValueType())
  12938. {
  12939. auto thisValue = GetThis();
  12940. value = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInst->mDataIdx);
  12941. }
  12942. else
  12943. {
  12944. AssertErrorState();
  12945. value = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(fieldInst->mResolvedType));
  12946. }
  12947. }
  12948. BfIRValue staticVal;
  12949. if (hasDbgInfo)
  12950. {
  12951. BfIRValue dbgShowValue = value;
  12952. BfLocalVariable* localDef = new BfLocalVariable();
  12953. localDef->mName = "_";
  12954. localDef->mResolvedType = fieldInst->mResolvedType;
  12955. localDef->mAddr = value;
  12956. if ((mBfIRBuilder->DbgHasInfo()) && (!IsTargetingBeefBackend()))
  12957. {
  12958. // Create another pointer indirection, a ref to the gep
  12959. auto refFieldType = CreateRefType(fieldInst->mResolvedType);
  12960. auto allocaInst = CreateAlloca(refFieldType);
  12961. auto storeResult = mBfIRBuilder->CreateStore(value, allocaInst);
  12962. localDef->mResolvedType = refFieldType;
  12963. localDef->mAddr = allocaInst;
  12964. }
  12965. mBfIRBuilder->RestoreDebugLocation();
  12966. auto defLocalVar = AddLocalVariableDef(localDef, true);
  12967. // Put back so we actually modify the correct value*/
  12968. defLocalVar->mResolvedType = fieldInst->mResolvedType;
  12969. defLocalVar->mAddr = value;
  12970. }
  12971. while (fieldDtor != NULL)
  12972. {
  12973. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  12974. {
  12975. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(fieldDtor, BfSourceElementType_Normal);
  12976. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(fieldDtor);
  12977. }
  12978. UpdateSrcPos(fieldDtor);
  12979. VisitEmbeddedStatement(fieldDtor->mBody);
  12980. fieldDtor = fieldDtor->mNextFieldDtor;
  12981. }
  12982. RestoreScopeState();
  12983. }
  12984. }
  12985. if ((!methodDef->mIsStatic) && (mCurMethodInstance->mChainType != BfMethodChainType_ChainMember))
  12986. {
  12987. auto checkBaseType = mCurTypeInstance->mBaseType;
  12988. while (checkBaseType != NULL)
  12989. {
  12990. if (auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody))
  12991. {
  12992. if (bodyBlock->mCloseBrace != NULL)
  12993. UpdateSrcPos(bodyBlock->mCloseBrace);
  12994. }
  12995. else
  12996. {
  12997. UpdateSrcPos(typeDef->mTypeDeclaration->mNameNode);
  12998. }
  12999. if (checkBaseType->mTypeDef->mDtorDef != NULL)
  13000. {
  13001. auto dtorMethodInstance = GetMethodInstance(checkBaseType, checkBaseType->mTypeDef->mDtorDef, BfTypeVector());
  13002. if (mCompiler->IsSkippingExtraResolveChecks())
  13003. {
  13004. // Nothing
  13005. }
  13006. else if (dtorMethodInstance.mMethodInstance->GetParamCount() == 0)
  13007. {
  13008. if ((!mCompiler->IsSkippingExtraResolveChecks()) && (!checkBaseType->IsUnspecializedType()))
  13009. {
  13010. auto basePtr = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapTypeInstPtr(checkBaseType));
  13011. SizedArray<BfIRValue, 1> vals = { basePtr };
  13012. auto callInst = mBfIRBuilder->CreateCall(dtorMethodInstance.mFunc, vals);
  13013. mBfIRBuilder->SetCallCallingConv(callInst, GetIRCallingConvention(dtorMethodInstance.mMethodInstance));
  13014. }
  13015. }
  13016. else
  13017. {
  13018. // Invalid base dtor declaration
  13019. AssertErrorState();
  13020. }
  13021. break;
  13022. }
  13023. checkBaseType = checkBaseType->mBaseType;
  13024. }
  13025. }
  13026. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  13027. }
  13028. else
  13029. {
  13030. // The reason we can't just do the 'normal' path for this is that the BfTypeInstance here is NOT the
  13031. // autocomplete type instance, so FieldInstance initializer values contain expressions from the full
  13032. // resolve pass, NOT the autocomplete expression
  13033. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  13034. {
  13035. if (tempTypeDef->mFullName == typeDef->mFullName)
  13036. {
  13037. for (auto fieldDef : tempTypeDef->mFields)
  13038. {
  13039. if ((fieldDef->mIsStatic == methodDef->mIsStatic) && (fieldDef->mFieldDeclaration != NULL) &&
  13040. (fieldDef->mFieldDeclaration->mFieldDtor != NULL) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  13041. {
  13042. BfType* fieldType = NULL;
  13043. for (int curFieldIdx = 0; curFieldIdx < (int)mCurTypeInstance->mFieldInstances.size(); curFieldIdx++)
  13044. {
  13045. auto curFieldInstance = &mCurTypeInstance->mFieldInstances[curFieldIdx];
  13046. auto curFieldDef = curFieldInstance->GetFieldDef();
  13047. if ((curFieldDef != NULL) && (fieldDef->mName == curFieldDef->mName))
  13048. fieldType = curFieldInstance->GetResolvedType();
  13049. }
  13050. if (fieldType == NULL)
  13051. fieldType = GetPrimitiveType(BfTypeCode_Var);
  13052. auto fieldDtor = fieldDef->mFieldDeclaration->mFieldDtor;
  13053. BfScopeData scopeData;
  13054. mCurMethodState->AddScope(&scopeData);
  13055. NewScopeState();
  13056. // This is just for autocomplete, it doesn't matter that mAddr is incorrect
  13057. if (fieldType != NULL)
  13058. {
  13059. BfLocalVariable* localDef = new BfLocalVariable();
  13060. localDef->mName = "_";
  13061. localDef->mResolvedType = fieldType;
  13062. localDef->mAddr = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(fieldType));
  13063. localDef->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  13064. AddLocalVariableDef(localDef);
  13065. }
  13066. while (fieldDtor != NULL)
  13067. {
  13068. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(fieldDtor, BfSourceElementType_Normal);
  13069. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(fieldDtor);
  13070. UpdateSrcPos(fieldDtor);
  13071. VisitEmbeddedStatement(fieldDtor->mBody);
  13072. fieldDtor = fieldDtor->mNextFieldDtor;
  13073. }
  13074. RestoreScopeState();
  13075. }
  13076. }
  13077. }
  13078. }
  13079. }
  13080. }
  13081. BfIRValue BfModule::CreateDllImportGlobalVar(BfMethodInstance* methodInstance, bool define)
  13082. {
  13083. auto typeInstance = methodInstance->GetOwner();
  13084. bool foundDllImportAttr = false;
  13085. BfCallingConvention callingConvention = methodInstance->mCallingConvention;
  13086. for (auto customAttr : methodInstance->GetCustomAttributes()->mAttributes)
  13087. {
  13088. if (customAttr.mType->mTypeDef->mFullName.ToString() == "System.ImportAttribute")
  13089. {
  13090. foundDllImportAttr = true;
  13091. }
  13092. }
  13093. if (!foundDllImportAttr)
  13094. {
  13095. AssertErrorState();
  13096. return BfIRValue();
  13097. }
  13098. String name = "bf_hs_preserve@";
  13099. BfMangler::Mangle(name, mCompiler->GetMangleKind(), methodInstance);
  13100. name += "__imp";
  13101. BfIRType returnType;
  13102. SizedArray<BfIRType, 8> paramTypes;
  13103. methodInstance->GetIRFunctionInfo(this, returnType, paramTypes);
  13104. BfIRFunctionType externFunctionType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes, methodInstance->IsVarArgs());
  13105. auto ptrType = mBfIRBuilder->GetPointerTo(externFunctionType);
  13106. BfIRValue initVal;
  13107. if (define)
  13108. {
  13109. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  13110. initVal = mBfIRBuilder->CreateConstNull(ptrType);
  13111. }
  13112. auto globalVar = mBfIRBuilder->CreateGlobalVariable(ptrType, false, BfIRLinkageType_External, initVal, name);
  13113. if ((define) && (mBfIRBuilder->DbgHasInfo()))
  13114. {
  13115. auto voidType = GetPrimitiveType(BfTypeCode_None);
  13116. auto ptrType = CreatePointerType(voidType);
  13117. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, name, name, BfIRMDNode(), 0, mBfIRBuilder->DbgGetType(ptrType), false, globalVar);
  13118. }
  13119. return globalVar;
  13120. }
  13121. void BfModule::CreateDllImportMethod()
  13122. {
  13123. if (mBfIRBuilder->mIgnoreWrites)
  13124. return;
  13125. auto globalVar = mFuncReferences[mCurMethodInstance];
  13126. if (!globalVar)
  13127. return;
  13128. bool allowTailCall = true;
  13129. mBfIRBuilder->ClearDebugLocation();
  13130. bool isHotCompile = mCompiler->IsHotCompile();
  13131. // If we are hot swapping, we need to have this stub because we may need to call the LoadSharedLibraries on demand
  13132. if (isHotCompile)
  13133. {
  13134. auto loadSharedLibsFunc = GetBuiltInFunc(BfBuiltInFuncType_LoadSharedLibraries);
  13135. mBfIRBuilder->CreateCall(loadSharedLibsFunc, SizedArray<BfIRValue, 0>());
  13136. }
  13137. auto callingConvention = GetIRCallingConvention(mCurMethodInstance);
  13138. BfIRType returnType;
  13139. SizedArray<BfIRType, 8> paramTypes;
  13140. mCurMethodInstance->GetIRFunctionInfo(this, returnType, paramTypes, mCurMethodInstance->IsVarArgs());
  13141. SizedArray<BfIRValue, 8> args;
  13142. for (int i = 0; i < (int)paramTypes.size(); i++)
  13143. args.push_back(mBfIRBuilder->GetArgument(i));
  13144. BfIRFunctionType externFunctionType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes, mCurMethodInstance->IsVarArgs());
  13145. if (isHotCompile)
  13146. {
  13147. BfIRValue funcVal = mBfIRBuilder->CreateLoad(globalVar);
  13148. auto result = mBfIRBuilder->CreateCall(funcVal, args);
  13149. if (callingConvention == BfIRCallingConv_StdCall)
  13150. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_StdCall);
  13151. else if (callingConvention == BfIRCallingConv_FastCall)
  13152. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_FastCall);
  13153. else
  13154. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_CDecl);
  13155. if (allowTailCall)
  13156. mBfIRBuilder->SetTailCall(result);
  13157. CreateReturn(result);
  13158. mCurMethodState->mHadReturn = true;
  13159. }
  13160. if (HasCompiledOutput())
  13161. {
  13162. BfDllImportEntry dllImportEntry;
  13163. dllImportEntry.mFuncVar = globalVar;
  13164. dllImportEntry.mMethodInstance = mCurMethodInstance;
  13165. mDllImportEntries.push_back(dllImportEntry);
  13166. }
  13167. }
  13168. BfIRCallingConv BfModule::GetIRCallingConvention(BfMethodInstance* methodInstance)
  13169. {
  13170. auto methodDef = methodInstance->mMethodDef;
  13171. BfTypeInstance* owner = NULL;
  13172. if (!methodDef->mIsStatic)
  13173. owner = methodInstance->GetThisType()->ToTypeInstance();
  13174. if (owner == NULL)
  13175. owner = methodInstance->GetOwner();
  13176. if ((mCompiler->mOptions.mMachineType != BfMachineType_x86) || (mCompiler->mOptions.mPlatformType != BfPlatformType_Windows))
  13177. return BfIRCallingConv_CDecl;
  13178. if (methodInstance->mCallingConvention == BfCallingConvention_Stdcall)
  13179. return BfIRCallingConv_StdCall;
  13180. if (methodInstance->mCallingConvention == BfCallingConvention_Fastcall)
  13181. return BfIRCallingConv_FastCall;
  13182. if ((!methodDef->mIsStatic) && (!owner->IsValuelessType()) &&
  13183. ((!owner->IsSplattable()) || (methodDef->HasNoThisSplat())))
  13184. return BfIRCallingConv_ThisCall;
  13185. return BfIRCallingConv_CDecl;
  13186. //return GetIRCallingConvention(owner, methodInstance->mMethodDef);
  13187. }
  13188. void BfModule::SetupIRMethod(BfMethodInstance* methodInstance, BfIRFunction func, bool isInlined)
  13189. {
  13190. BfMethodDef* methodDef = NULL;
  13191. if (methodInstance != NULL)
  13192. methodDef = methodInstance->mMethodDef;
  13193. if (!func)
  13194. return;
  13195. if (mCompiler->mOptions.mNoFramePointerElim)
  13196. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_NoFramePointerElim);
  13197. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_NoUnwind);
  13198. if (mSystem->mPtrSize == 8) // We need unwind info for debugging
  13199. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_UWTable);
  13200. if (methodInstance == NULL)
  13201. return;
  13202. if (methodDef->mImportKind == BfImportKind_Export)
  13203. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_DllExport);
  13204. if (methodDef->mIsNoReturn)
  13205. mBfIRBuilder->Func_AddAttribute(func, -1, BfIRAttribute_NoReturn);
  13206. auto callingConv = GetIRCallingConvention(methodInstance);
  13207. if (callingConv != BfIRCallingConv_CDecl)
  13208. mBfIRBuilder->SetFuncCallingConv(func, callingConv);
  13209. if (isInlined)
  13210. {
  13211. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_AlwaysInline);
  13212. }
  13213. int argIdx = 0;
  13214. int paramIdx = 0;
  13215. if ((methodInstance->HasThis()) && (!methodDef->mHasExplicitThis))
  13216. paramIdx = -1;
  13217. int argCount = methodInstance->GetIRFunctionParamCount(this);
  13218. while (argIdx < argCount)
  13219. {
  13220. if (argIdx == methodInstance->GetStructRetIdx())
  13221. {
  13222. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_NoAlias);
  13223. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_StructRet);
  13224. argIdx++;
  13225. continue;
  13226. }
  13227. bool isThis = (paramIdx == -1) || ((methodDef->mHasExplicitThis) && (paramIdx == 0));
  13228. while ((!isThis) && (methodInstance->IsParamSkipped(paramIdx)))
  13229. paramIdx++;
  13230. BfType* resolvedTypeRef = NULL;
  13231. BfType* resolvedTypeRef2 = NULL;
  13232. String paramName;
  13233. bool isSplattable = false;
  13234. bool tryLowering = true;
  13235. if (isThis)
  13236. {
  13237. paramName = "this";
  13238. if (methodInstance->mIsClosure)
  13239. resolvedTypeRef = mCurMethodState->mClosureState->mClosureType;
  13240. else
  13241. resolvedTypeRef = methodInstance->GetThisType();
  13242. isSplattable = (resolvedTypeRef->IsSplattable()) && (methodInstance->AllowsThisSplatting());
  13243. tryLowering = methodInstance->AllowsThisSplatting();
  13244. }
  13245. else
  13246. {
  13247. paramName = methodInstance->GetParamName(paramIdx);
  13248. resolvedTypeRef = methodInstance->GetParamType(paramIdx);
  13249. if (resolvedTypeRef->IsMethodRef())
  13250. isSplattable = true;
  13251. else if ((resolvedTypeRef->IsSplattable()) && (methodInstance->AllowsSplatting()))
  13252. {
  13253. auto resolvedTypeInst = resolvedTypeRef->ToTypeInstance();
  13254. if ((resolvedTypeInst != NULL) && (resolvedTypeInst->mIsCRepr))
  13255. {
  13256. // crepr splat is always splattable
  13257. isSplattable = true;
  13258. }
  13259. else if (resolvedTypeRef->GetSplatCount() + argIdx <= mCompiler->mOptions.mMaxSplatRegs)
  13260. isSplattable = true;
  13261. }
  13262. }
  13263. if (tryLowering)
  13264. {
  13265. BfTypeCode loweredTypeCode = BfTypeCode_None;
  13266. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  13267. if (resolvedTypeRef->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2))
  13268. {
  13269. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, paramName + "__1");
  13270. argIdx++;
  13271. if (loweredTypeCode2 != BfTypeCode_None)
  13272. {
  13273. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, paramName + "__2");
  13274. argIdx++;
  13275. }
  13276. paramIdx++;
  13277. continue;
  13278. }
  13279. }
  13280. auto _SetupParam = [&](const StringImpl& paramName, BfType* resolvedTypeRef)
  13281. {
  13282. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, paramName);
  13283. int addDeref = -1;
  13284. if (resolvedTypeRef->IsRef())
  13285. {
  13286. auto refType = (BfRefType*)resolvedTypeRef;
  13287. auto elementType = refType->mElementType;
  13288. PopulateType(elementType, BfPopulateType_Data);
  13289. addDeref = elementType->mSize;
  13290. if ((addDeref <= 0) && (!elementType->IsValuelessType()))
  13291. AssertErrorState();
  13292. }
  13293. if ((resolvedTypeRef->IsComposite()) && (!resolvedTypeRef->IsTypedPrimitive()))
  13294. {
  13295. if (isThis)
  13296. {
  13297. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_NoCapture);
  13298. PopulateType(resolvedTypeRef, BfPopulateType_Data);
  13299. addDeref = resolvedTypeRef->mSize;
  13300. }
  13301. else if (methodInstance->WantsStructsAttribByVal())
  13302. {
  13303. mBfIRBuilder->PopulateType(resolvedTypeRef);
  13304. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_ByVal, mSystem->mPtrSize);
  13305. }
  13306. }
  13307. else if (resolvedTypeRef->IsPrimitiveType())
  13308. {
  13309. auto primType = (BfPrimitiveType*)resolvedTypeRef;
  13310. if (primType->mTypeDef->mTypeCode == BfTypeCode_Boolean)
  13311. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_ZExt);
  13312. }
  13313. if (addDeref >= 0)
  13314. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_Dereferencable, addDeref);
  13315. argIdx++;
  13316. };
  13317. if (isSplattable)
  13318. {
  13319. std::function<void(BfType*, const StringImpl&)> checkTypeLambda = [&](BfType* checkType, const StringImpl& curName)
  13320. {
  13321. if (checkType->IsStruct())
  13322. {
  13323. auto checkTypeInstance = checkType->ToTypeInstance();
  13324. if (checkTypeInstance->mBaseType != NULL)
  13325. checkTypeLambda(checkTypeInstance->mBaseType, curName);
  13326. if (checkTypeInstance->mIsUnion)
  13327. {
  13328. BfType* unionInnerType = checkTypeInstance->GetUnionInnerType();
  13329. checkTypeLambda(unionInnerType, curName + "_data");
  13330. }
  13331. else
  13332. {
  13333. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  13334. {
  13335. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  13336. auto fieldDef = fieldInstance->GetFieldDef();
  13337. if (fieldInstance->mDataIdx >= 0)
  13338. {
  13339. checkTypeLambda(fieldInstance->GetResolvedType(), curName + "_" + fieldInstance->GetFieldDef()->mName);
  13340. }
  13341. }
  13342. }
  13343. if (checkTypeInstance->IsEnum())
  13344. {
  13345. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, curName + "_dscr");
  13346. argIdx++;
  13347. }
  13348. }
  13349. else if (checkType->IsMethodRef())
  13350. {
  13351. auto methodRefType = (BfMethodRefType*)checkType;
  13352. BfMethodInstance* methodRefMethodInst = methodRefType->mMethodRef;
  13353. for (int dataIdx = 0; dataIdx < (int)methodRefType->GetCaptureDataCount(); dataIdx++)
  13354. {
  13355. int methodRefParamIdx = methodRefType->GetParamIdxFromDataIdx(dataIdx);
  13356. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  13357. {
  13358. checkTypeLambda(methodRefType->GetCaptureType(dataIdx), curName + "_" + methodRefMethodInst->GetParamName(methodRefParamIdx));
  13359. }
  13360. else
  13361. {
  13362. _SetupParam(curName + "_" + methodRefMethodInst->GetParamName(methodRefParamIdx), methodRefType->GetCaptureType(dataIdx));
  13363. }
  13364. }
  13365. }
  13366. else if (!checkType->IsValuelessType())
  13367. {
  13368. _SetupParam(curName, checkType);
  13369. }
  13370. };
  13371. checkTypeLambda(resolvedTypeRef, paramName);
  13372. paramIdx++;
  13373. continue;
  13374. }
  13375. _SetupParam(paramName, resolvedTypeRef);
  13376. if (resolvedTypeRef2 != NULL)
  13377. _SetupParam(paramName, resolvedTypeRef2);
  13378. paramIdx++;
  13379. }
  13380. }
  13381. void BfModule::EmitCtorBody(bool& skipBody)
  13382. {
  13383. auto methodInstance = mCurMethodInstance;
  13384. auto methodDef = methodInstance->mMethodDef;
  13385. auto methodDeclaration = methodDef->mMethodDeclaration;
  13386. auto ctorDeclaration = (BfConstructorDeclaration*)methodDef->mMethodDeclaration;
  13387. auto typeDef = mCurTypeInstance->mTypeDef;
  13388. BfCustomAttributes* customAttributes = NULL;
  13389. defer(delete customAttributes);
  13390. BfInvocationExpression* ctorInvocation = NULL;
  13391. BfAttributeState attributeState;
  13392. attributeState.mTarget = BfAttributeTargets_MemberAccess;
  13393. if (ctorDeclaration != NULL)
  13394. {
  13395. ctorInvocation = BfNodeDynCast<BfInvocationExpression>(ctorDeclaration->mInitializer);
  13396. if (auto attributedExpr = BfNodeDynCast<BfAttributedExpression>(ctorDeclaration->mInitializer))
  13397. {
  13398. ctorInvocation = BfNodeDynCast<BfInvocationExpression>(attributedExpr->mExpression);
  13399. attributeState.mCustomAttributes = GetCustomAttributes(attributedExpr->mAttributes, attributeState.mTarget);
  13400. }
  13401. }
  13402. SetAndRestoreValue<BfAttributeState*> prevAttributeState(mAttributeState, &attributeState);
  13403. // Prologue
  13404. mBfIRBuilder->ClearDebugLocation();
  13405. bool hadThisInitializer = false;
  13406. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL))
  13407. {
  13408. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorInvocation->mTarget);
  13409. auto targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  13410. if (targetToken->GetToken() == BfToken_This)
  13411. {
  13412. hadThisInitializer = true;
  13413. // Since we call a 'this', it's that other ctor's responsibility to fully assign the fields
  13414. mCurMethodState->LocalDefined(GetThisVariable());
  13415. }
  13416. }
  13417. // Zero out memory for default ctor
  13418. if ((methodDeclaration == NULL) && (mCurTypeInstance->IsStruct()))
  13419. {
  13420. if (mCurTypeInstance->IsTypedPrimitive())
  13421. {
  13422. auto thisRef = mCurMethodState->mLocals[0]->mValue;
  13423. mBfIRBuilder->CreateStore(GetDefaultValue(mCurTypeInstance), thisRef);
  13424. }
  13425. else if (mCurTypeInstance->mInstSize > 0)
  13426. {
  13427. BfIRValue fillValue = GetConstValue8(0);
  13428. BfIRValue sizeValue = GetConstValue(mCurTypeInstance->mInstSize);
  13429. auto thisRef = mCurMethodState->mLocals[0]->mValue;
  13430. BfIRValue destBits = mBfIRBuilder->CreateBitCast(thisRef, mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr));
  13431. mBfIRBuilder->CreateMemSet(destBits, fillValue, sizeValue, mCurTypeInstance->mAlign);
  13432. }
  13433. }
  13434. BfAstNode* baseCtorNode = NULL;
  13435. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL) && (ctorInvocation->mTarget != NULL))
  13436. baseCtorNode = ctorInvocation->mTarget;
  13437. else if (methodDef->mBody != NULL)
  13438. baseCtorNode = methodDef->mBody;
  13439. else if (ctorDeclaration != NULL)
  13440. baseCtorNode = ctorDeclaration;
  13441. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  13442. baseCtorNode = mCurTypeInstance->mTypeDef->mTypeDeclaration->mNameNode;
  13443. else if ((mCurTypeInstance->mBaseType != NULL) && (mCurTypeInstance->mBaseType->mTypeDef->mTypeDeclaration != NULL))
  13444. baseCtorNode = mCurTypeInstance->mBaseType->mTypeDef->mTypeDeclaration;
  13445. else
  13446. baseCtorNode = mContext->mBfObjectType->mTypeDef->mTypeDeclaration;
  13447. bool calledCtorNoBody = false;
  13448. if ((!mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType == BfMethodType_Ctor) && (!hadThisInitializer))
  13449. {
  13450. // Call the root type's default ctor (with no body) to initialize its fields and call the chained ctors
  13451. if (mCurTypeInstance->mTypeDef->mHasCtorNoBody)
  13452. {
  13453. BfMethodDef* defaultCtor = NULL;
  13454. for (auto methodDef : mCurTypeInstance->mTypeDef->mMethods)
  13455. {
  13456. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) && (methodDef->mDeclaringType->mTypeCode != BfTypeCode_Extension))
  13457. {
  13458. defaultCtor = methodDef;
  13459. }
  13460. }
  13461. if (defaultCtor != NULL)
  13462. {
  13463. UpdateSrcPos(mCurTypeInstance->mTypeDef->GetRefNode());
  13464. SetIllegalSrcPos();
  13465. auto moduleMethodInstance = GetMethodInstance(mCurTypeInstance, defaultCtor, BfTypeVector());
  13466. BfExprEvaluator exprEvaluator(this);
  13467. SizedArray<BfIRValue, 1> irArgs;
  13468. exprEvaluator.PushThis(NULL, GetThis(), moduleMethodInstance.mMethodInstance, irArgs);
  13469. exprEvaluator.CreateCall(moduleMethodInstance.mMethodInstance, moduleMethodInstance.mFunc, false, irArgs);
  13470. calledCtorNoBody = true;
  13471. }
  13472. }
  13473. }
  13474. // Initialize fields (if applicable)
  13475. if (mCurTypeInstance->IsBoxed())
  13476. {
  13477. skipBody = true;
  13478. }
  13479. else if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mDeclaringType->mTypeCode == BfTypeCode_Extension))
  13480. {
  13481. // Field initializers occur in CtorNoBody methods for extensions
  13482. }
  13483. else if ((!hadThisInitializer) && (!calledCtorNoBody))
  13484. {
  13485. // If we had a 'this' initializer, that other ctor will have initialized our fields
  13486. if ((!mCompiler->mIsResolveOnly) ||
  13487. (mCompiler->mResolvePassData->mAutoComplete == NULL) ||
  13488. (mCompiler->mResolvePassData->mAutoComplete->mResolveType == BfResolveType_ShowFileSymbolReferences))
  13489. {
  13490. bool hadInlineInitBlock = false;
  13491. BfScopeData scopeData;
  13492. for (auto fieldDef : typeDef->mFields)
  13493. {
  13494. // For extensions, only handle these fields in the appropriate extension
  13495. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  13496. continue;
  13497. if ((!fieldDef->mIsConst) && (!fieldDef->mIsStatic))
  13498. {
  13499. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  13500. if (!fieldInst->mFieldIncluded)
  13501. continue;
  13502. if (fieldInst->mDataIdx < 0)
  13503. continue;
  13504. if (fieldDef->mInitializer == NULL)
  13505. {
  13506. continue;
  13507. // if (fieldDef->mProtection != BfProtection_Hidden)
  13508. // continue;
  13509. // if (mCurTypeInstance->IsObject()) // Already zeroed out
  13510. // continue;
  13511. }
  13512. if (fieldInst->mResolvedType == NULL)
  13513. {
  13514. BF_ASSERT(mHadBuildError);
  13515. continue;
  13516. }
  13517. if (fieldDef->mInitializer != NULL)
  13518. {
  13519. if (!hadInlineInitBlock)
  13520. {
  13521. if ((mBfIRBuilder->DbgHasInfo()) && (!mCurTypeInstance->IsUnspecializedType()) && (mHasFullDebugInfo))
  13522. {
  13523. UpdateSrcPos(baseCtorNode);
  13524. if (methodDef->mBody == NULL)
  13525. SetIllegalSrcPos();
  13526. // 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
  13527. EmitEnsureInstructionAt();
  13528. BfType* thisType = mCurTypeInstance;
  13529. if (thisType->IsValueType())
  13530. thisType = CreateRefType(thisType);
  13531. SizedArray<BfIRMDNode, 1> diParamTypes;
  13532. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParamTypes);
  13533. mCurMethodState->AddScope(&scopeData);
  13534. NewScopeState();
  13535. int flags = 0;
  13536. mCurMethodState->mCurScope->mDIInlinedAt = mBfIRBuilder->DbgGetCurrentLocation();
  13537. BF_ASSERT(mCurMethodState->mCurScope->mDIInlinedAt);
  13538. // mCurMethodState->mCurScope->mDIInlinedAt may still be null ifwe don't have an explicit ctor
  13539. mCurMethodState->mCurScope->mDIScope = mBfIRBuilder->DbgCreateFunction(mBfIRBuilder->DbgGetTypeInst(mCurTypeInstance), "this$initFields", "", mCurFilePosition.mFileInstance->mDIFile,
  13540. mCurFilePosition.mCurLine + 1, diFuncType, false, true, mCurFilePosition.mCurLine + 1, flags, false, BfIRValue());
  13541. UpdateSrcPos(fieldDef->mInitializer);
  13542. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  13543. "this", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(thisType));
  13544. //
  13545. {
  13546. auto loadedThis = GetThis();
  13547. // LLVM can't handle two variables pointing to the same value
  13548. BfIRValue copiedThisPtr;
  13549. copiedThisPtr = CreateAlloca(thisType);
  13550. auto storeInst = mBfIRBuilder->CreateStore(loadedThis.mValue, copiedThisPtr);
  13551. mBfIRBuilder->ClearDebugLocation(storeInst);
  13552. mBfIRBuilder->DbgInsertDeclare(copiedThisPtr, diVariable);
  13553. }
  13554. hadInlineInitBlock = true;
  13555. }
  13556. }
  13557. UpdateSrcPos(fieldDef->mInitializer);
  13558. }
  13559. BfIRValue fieldAddr;
  13560. if ((!mCurTypeInstance->IsTypedPrimitive()) && (!fieldInst->mResolvedType->IsVar()))
  13561. {
  13562. fieldAddr = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, fieldInst->mDataIdx /*, fieldDef->mName*/);
  13563. }
  13564. else
  13565. {
  13566. // Failed
  13567. }
  13568. auto assignValue = GetFieldInitializerValue(fieldInst);
  13569. if (mCurTypeInstance->IsUnion())
  13570. {
  13571. auto fieldPtrType = CreatePointerType(fieldInst->mResolvedType);
  13572. fieldAddr = mBfIRBuilder->CreateBitCast(fieldAddr, mBfIRBuilder->MapType(fieldPtrType));
  13573. }
  13574. if ((fieldAddr) && (assignValue))
  13575. mBfIRBuilder->CreateStore(assignValue.mValue, fieldAddr);
  13576. }
  13577. }
  13578. if (hadInlineInitBlock)
  13579. {
  13580. RestoreScopeState();
  13581. // This gets set to false because of AddScope but we actually are still in the head block
  13582. mCurMethodState->mInHeadScope = true;
  13583. }
  13584. }
  13585. else // Autocomplete case
  13586. {
  13587. // The reason we can't just do the 'normal' path for this is that the BfTypeInstance here is NOT the
  13588. // autocomplete type instance, so FieldInstance initializer values contain expressions from the full
  13589. // resolve pass, NOT the autocomplete expression
  13590. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  13591. {
  13592. if (tempTypeDef->mFullName == typeDef->mFullName)
  13593. {
  13594. for (auto fieldDef : tempTypeDef->mFields)
  13595. {
  13596. if ((!fieldDef->mIsStatic) && (fieldDef->mInitializer != NULL) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  13597. {
  13598. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(fieldDef->mInitializer, BfSourceElementType_Normal);
  13599. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(fieldDef->mInitializer);
  13600. auto wantType = ResolveTypeRef(fieldDef->mTypeRef);
  13601. if ((wantType != NULL) &&
  13602. ((wantType->IsVar()) || (wantType->IsLet()) || (wantType->IsRef())))
  13603. wantType = NULL;
  13604. CreateValueFromExpression(fieldDef->mInitializer, wantType, BfEvalExprFlags_FieldInitializer);
  13605. }
  13606. }
  13607. }
  13608. }
  13609. // Mark fields from full type with initializers as initialized, to give proper initialization errors within ctor
  13610. for (auto fieldDef : typeDef->mFields)
  13611. {
  13612. if ((!fieldDef->mIsConst) && (!fieldDef->mIsStatic) && (fieldDef->mInitializer != NULL))
  13613. {
  13614. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  13615. if (fieldDef->mInitializer != NULL)
  13616. MarkFieldInitialized(fieldInst);
  13617. }
  13618. }
  13619. }
  13620. }
  13621. // Call base ctor (if applicable)
  13622. BfTypeInstance* targetType = NULL;
  13623. BfAstNode* targetRefNode = NULL;
  13624. if (ctorDeclaration != NULL)
  13625. targetRefNode = ctorDeclaration->mInitializer;
  13626. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(targetRefNode))
  13627. targetRefNode = invocationExpr->mTarget;
  13628. if (baseCtorNode != NULL)
  13629. {
  13630. UpdateSrcPos(baseCtorNode);
  13631. if (methodDef->mBody == NULL)
  13632. SetIllegalSrcPos();
  13633. }
  13634. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL))
  13635. {
  13636. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorInvocation->mTarget);
  13637. targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  13638. }
  13639. else if ((mCurTypeInstance->mBaseType != NULL) && (!mCurTypeInstance->IsUnspecializedType()))
  13640. {
  13641. auto baseType = mCurTypeInstance->mBaseType;
  13642. if ((!mCurTypeInstance->IsTypedPrimitive()) &&
  13643. (baseType->mTypeDef != mCompiler->mValueTypeTypeDef) &&
  13644. (baseType->mTypeDef != mCompiler->mBfObjectTypeDef))
  13645. {
  13646. // Try to find a ctor without any params first
  13647. BfMethodDef* matchedMethod = NULL;
  13648. bool hadCtorWithAllDefaults = false;
  13649. bool isHiddenGenerated = (methodDeclaration == NULL) && (methodDef->mProtection == BfProtection_Hidden);
  13650. for (int pass = 0; pass < 2; pass++)
  13651. {
  13652. baseType->mTypeDef->PopulateMemberSets();
  13653. BfMemberSetEntry* entry = NULL;
  13654. BfMethodDef* checkMethodDef = NULL;
  13655. baseType->mTypeDef->mMethodSet.TryGetWith(String("__BfCtor"), &entry);
  13656. if (entry != NULL)
  13657. checkMethodDef = (BfMethodDef*)entry->mMemberDef;
  13658. while (checkMethodDef != NULL)
  13659. {
  13660. bool allowMethod = checkMethodDef->mProtection > BfProtection_Private;
  13661. if (isHiddenGenerated)
  13662. {
  13663. // Allow calling of the default base ctor if it is implicitly defined
  13664. if ((checkMethodDef->mMethodDeclaration == NULL) && (pass == 1) && (!hadCtorWithAllDefaults))
  13665. allowMethod = true;
  13666. }
  13667. if ((checkMethodDef->mMethodType == BfMethodType_Ctor) && (!checkMethodDef->mIsStatic) && (allowMethod))
  13668. {
  13669. if (checkMethodDef->mParams.size() == 0)
  13670. {
  13671. matchedMethod = checkMethodDef;
  13672. }
  13673. else if (isHiddenGenerated)
  13674. {
  13675. if ((checkMethodDef->mParams[0]->mParamDeclaration != NULL) && (checkMethodDef->mParams[0]->mParamDeclaration->mInitializer != NULL))
  13676. hadCtorWithAllDefaults = true;
  13677. }
  13678. }
  13679. checkMethodDef = checkMethodDef->mNextWithSameName;
  13680. }
  13681. if (matchedMethod != NULL)
  13682. break;
  13683. }
  13684. if ((HasCompiledOutput()) && (matchedMethod != NULL))
  13685. {
  13686. SizedArray<BfIRValue, 1> args;
  13687. auto ctorBodyMethodInstance = GetMethodInstance(mCurTypeInstance->mBaseType, matchedMethod, BfTypeVector());
  13688. if (!mCurTypeInstance->mBaseType->IsValuelessType())
  13689. {
  13690. auto basePtr = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapTypeInstPtr(mCurTypeInstance->mBaseType));
  13691. args.push_back(basePtr);
  13692. }
  13693. AddCallDependency(ctorBodyMethodInstance.mMethodInstance, true);
  13694. auto callInst = mBfIRBuilder->CreateCall(ctorBodyMethodInstance.mFunc, args);
  13695. auto callingConv = GetIRCallingConvention(ctorBodyMethodInstance.mMethodInstance);
  13696. if (callingConv != BfIRCallingConv_CDecl)
  13697. mBfIRBuilder->SetCallCallingConv(callInst, callingConv);
  13698. }
  13699. if (matchedMethod == NULL)
  13700. {
  13701. targetType = mCurTypeInstance->mBaseType;
  13702. if (ctorDeclaration != NULL)
  13703. targetRefNode = ctorDeclaration->mThisToken;
  13704. else if (typeDef->mTypeDeclaration != NULL)
  13705. targetRefNode = typeDef->mTypeDeclaration->mNameNode;
  13706. }
  13707. }
  13708. }
  13709. if (methodDef->mHasAppend)
  13710. {
  13711. mCurMethodState->mCurAppendAlign = methodInstance->mAppendAllocAlign;
  13712. }
  13713. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL) && (ctorInvocation->mArguments.size() == 1) && (targetType != NULL))
  13714. {
  13715. if (auto tokenNode = BfNodeDynCast<BfUninitializedExpression>(ctorInvocation->mArguments[0]))
  13716. {
  13717. if (targetType == mCurTypeInstance)
  13718. {
  13719. auto thisVariable = GetThisVariable();
  13720. if (thisVariable != NULL)
  13721. {
  13722. thisVariable->mUnassignedFieldFlags = 0;
  13723. thisVariable->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  13724. }
  13725. }
  13726. targetType = NULL;
  13727. }
  13728. }
  13729. if (targetType != NULL)
  13730. {
  13731. BfAstNode* refNode = methodDeclaration;
  13732. if (refNode == NULL)
  13733. refNode = typeDef->mTypeDeclaration;
  13734. BfAutoParentNodeEntry autoParentNodeEntry(this, refNode);
  13735. auto autoComplete = mCompiler->GetAutoComplete();
  13736. auto wasCapturingMethodInfo = (autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo);
  13737. if ((autoComplete != NULL) && (ctorDeclaration != NULL) && (ctorInvocation != NULL))
  13738. {
  13739. auto invocationExpr = ctorInvocation;
  13740. autoComplete->CheckInvocation(invocationExpr, invocationExpr->mOpenParen, invocationExpr->mCloseParen, invocationExpr->mCommas);
  13741. }
  13742. BfType* targetThisType = targetType;
  13743. auto target = Cast(targetRefNode, GetThis(), targetThisType);
  13744. BfExprEvaluator exprEvaluator(this);
  13745. BfResolvedArgs argValues;
  13746. if ((ctorDeclaration != NULL) && (ctorInvocation != NULL))
  13747. {
  13748. argValues.Init(&ctorInvocation->mArguments);
  13749. if (gDebugStuff)
  13750. {
  13751. OutputDebugStrF("Expr: %@ %d\n", argValues.mArguments->mVals, argValues.mArguments->mSize);
  13752. }
  13753. }
  13754. exprEvaluator.ResolveArgValues(argValues, BfResolveArgFlag_DeferParamEval);
  13755. BfTypedValue appendIdxVal;
  13756. if (methodDef->mHasAppend)
  13757. {
  13758. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  13759. BF_ASSERT(localVar->mName == "appendIdx");
  13760. auto intRefType = localVar->mResolvedType;
  13761. appendIdxVal = BfTypedValue(localVar->mValue, intRefType);
  13762. mCurMethodState->mCurAppendAlign = 1; // Don't make any assumptions about how the base leaves the alignment
  13763. }
  13764. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, methodDef->mHasAppend, &appendIdxVal);
  13765. if (autoComplete != NULL)
  13766. {
  13767. if ((wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo))
  13768. {
  13769. if (autoComplete->mMethodMatchInfo != NULL)
  13770. autoComplete->mIsCapturingMethodMatchInfo = true;
  13771. else
  13772. autoComplete->mIsCapturingMethodMatchInfo = false;
  13773. }
  13774. else
  13775. autoComplete->mIsCapturingMethodMatchInfo = false;
  13776. }
  13777. }
  13778. }
  13779. void BfModule::EmitEnumToStringBody()
  13780. {
  13781. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  13782. auto strVal = CreateAlloca(stringType);
  13783. auto int64StructType = GetPrimitiveStructType(BfTypeCode_Int64);
  13784. BfExprEvaluator exprEvaluator(this);
  13785. auto stringDestAddr = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  13786. BfIRBlock appendBlock = mBfIRBuilder->CreateBlock("append");
  13787. BfIRBlock noMatchBlock = mBfIRBuilder->CreateBlock("noMatch");
  13788. BfIRBlock endBlock = mBfIRBuilder->CreateBlock("end");
  13789. BfType* discriminatorType = NULL;
  13790. BfTypedValue rawPayload;
  13791. BfIRValue enumVal;
  13792. if (mCurTypeInstance->IsPayloadEnum())
  13793. {
  13794. discriminatorType = mCurTypeInstance->GetDiscriminatorType();
  13795. auto enumTypedValue = ExtractValue(GetThis(), NULL, 2);
  13796. enumTypedValue = LoadValue(enumTypedValue);
  13797. enumVal = enumTypedValue.mValue;
  13798. rawPayload = ExtractValue(GetThis(), NULL, 1);
  13799. }
  13800. else
  13801. enumVal = mBfIRBuilder->GetArgument(0);
  13802. Array<BfType*> paramTypes;
  13803. paramTypes.Add(stringType);
  13804. auto appendModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  13805. auto switchVal = mBfIRBuilder->CreateSwitch(enumVal, noMatchBlock, (int)mCurTypeInstance->mFieldInstances.size());
  13806. HashSet<int64> handledCases;
  13807. for (auto& fieldInstance : mCurTypeInstance->mFieldInstances)
  13808. {
  13809. if (fieldInstance.mIsEnumPayloadCase)
  13810. {
  13811. int tagId = -fieldInstance.mDataIdx - 1;
  13812. BfIRBlock caseBlock = mBfIRBuilder->CreateBlock("case");
  13813. mBfIRBuilder->AddBlock(caseBlock);
  13814. mBfIRBuilder->SetInsertPoint(caseBlock);
  13815. BF_ASSERT(discriminatorType->IsPrimitiveType());
  13816. auto constVal = mBfIRBuilder->CreateConst(((BfPrimitiveType*)discriminatorType)->mTypeDef->mTypeCode, tagId);
  13817. mBfIRBuilder->AddSwitchCase(switchVal, constVal, caseBlock);
  13818. auto caseStr = GetStringObjectValue(fieldInstance.GetFieldDef()->mName);
  13819. auto stringDestVal = LoadValue(stringDestAddr);
  13820. SizedArray<BfIRValue, 2> args;
  13821. args.Add(stringDestVal.mValue);
  13822. args.Add(caseStr);
  13823. exprEvaluator.CreateCall(appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  13824. auto payloadType = fieldInstance.mResolvedType->ToTypeInstance();
  13825. BF_ASSERT(payloadType->IsTuple());
  13826. if (payloadType->mFieldInstances.size() != 0)
  13827. {
  13828. auto payload = rawPayload;
  13829. if (payload.mType != payloadType)
  13830. {
  13831. payload = Cast(NULL, payload, payloadType, BfCastFlags_Force);
  13832. }
  13833. auto toStringMethod = GetMethodByName(payloadType->ToTypeInstance(), "ToString");
  13834. SizedArray<BfIRValue, 2> irArgs;
  13835. exprEvaluator.PushThis(NULL, payload, toStringMethod.mMethodInstance, irArgs);
  13836. stringDestVal = LoadValue(stringDestAddr);
  13837. irArgs.Add(stringDestVal.mValue);
  13838. exprEvaluator.CreateCall(toStringMethod.mMethodInstance, toStringMethod.mFunc, true, irArgs);
  13839. }
  13840. mBfIRBuilder->CreateBr(endBlock);
  13841. continue;
  13842. }
  13843. if (fieldInstance.mConstIdx == -1)
  13844. continue;
  13845. auto constant = mCurTypeInstance->mConstHolder->GetConstantById(fieldInstance.mConstIdx);
  13846. if (!handledCases.TryAdd(constant->mInt64, NULL))
  13847. {
  13848. // Duplicate
  13849. continue;
  13850. }
  13851. BfIRBlock caseBlock = mBfIRBuilder->CreateBlock("case");
  13852. mBfIRBuilder->AddBlock(caseBlock);
  13853. mBfIRBuilder->SetInsertPoint(caseBlock);
  13854. BfIRValue constVal = ConstantToCurrent(constant, mCurTypeInstance->mConstHolder, mCurTypeInstance);
  13855. mBfIRBuilder->AddSwitchCase(switchVal, constVal, caseBlock);
  13856. auto caseStr = GetStringObjectValue(fieldInstance.GetFieldDef()->mName);
  13857. mBfIRBuilder->CreateStore(caseStr, strVal);
  13858. mBfIRBuilder->CreateBr(appendBlock);
  13859. }
  13860. mBfIRBuilder->AddBlock(appendBlock);
  13861. mBfIRBuilder->SetInsertPoint(appendBlock);
  13862. SizedArray<BfIRValue, 2> args;
  13863. auto stringDestVal = LoadValue(stringDestAddr);
  13864. args.Add(stringDestVal.mValue);
  13865. args.Add(mBfIRBuilder->CreateLoad(strVal));
  13866. exprEvaluator.CreateCall(appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  13867. mBfIRBuilder->CreateBr(endBlock);
  13868. mBfIRBuilder->AddBlock(noMatchBlock);
  13869. mBfIRBuilder->SetInsertPoint(noMatchBlock);
  13870. auto int64Val = mBfIRBuilder->CreateNumericCast(enumVal, false, BfTypeCode_Int64);
  13871. auto toStringModuleMethodInstance = GetMethodByName(int64StructType, "ToString", 1);
  13872. args.clear();
  13873. args.Add(int64Val);
  13874. stringDestVal = LoadValue(stringDestAddr);
  13875. args.Add(stringDestVal.mValue);
  13876. exprEvaluator.CreateCall(toStringModuleMethodInstance.mMethodInstance, toStringModuleMethodInstance.mFunc, false, args);
  13877. mBfIRBuilder->CreateBr(endBlock);
  13878. mBfIRBuilder->AddBlock(endBlock);
  13879. mBfIRBuilder->SetInsertPoint(endBlock);
  13880. }
  13881. void BfModule::EmitTupleToStringBody()
  13882. {
  13883. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  13884. BfExprEvaluator exprEvaluator(this);
  13885. auto stringDestRef = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  13886. Array<BfType*> paramTypes;
  13887. paramTypes.Add(GetPrimitiveType(BfTypeCode_Char8));
  13888. auto appendCharModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  13889. paramTypes.Clear();
  13890. paramTypes.Add(stringType);
  13891. auto appendModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  13892. auto _AppendChar = [&](char c)
  13893. {
  13894. SizedArray<BfIRValue, 2> args;
  13895. auto stringDestVal = LoadValue(stringDestRef);
  13896. args.Add(stringDestVal.mValue);
  13897. args.Add(mBfIRBuilder->CreateConst(BfTypeCode_Char8, (int)c));
  13898. exprEvaluator.CreateCall(appendCharModuleMethodInstance.mMethodInstance, appendCharModuleMethodInstance.mFunc, false, args);
  13899. };
  13900. int fieldIdx = 0;
  13901. auto thisValue = GetThis();
  13902. auto toStringModuleMethodInstance = GetMethodByName(mContext->mBfObjectType, "ToString", 1);
  13903. auto toStringSafeModuleMethodInstance = GetMethodByName(mContext->mBfObjectType, "ToString", 2);
  13904. BfIRValue commaStr;
  13905. auto iPrintableType = ResolveTypeDef(mCompiler->mIPrintableTypeDef)->ToTypeInstance();
  13906. auto printModuleMethodInstance = GetMethodByName(iPrintableType, "Print");
  13907. _AppendChar('(');
  13908. for (auto& fieldInstance : mCurTypeInstance->mFieldInstances)
  13909. {
  13910. if (fieldInstance.mDataIdx == -1)
  13911. continue;
  13912. if (fieldIdx > 0)
  13913. {
  13914. if (!commaStr)
  13915. commaStr = GetStringObjectValue(", ");
  13916. SizedArray<BfIRValue, 2> args;
  13917. auto stringDestVal = LoadValue(stringDestRef);
  13918. args.Add(stringDestVal.mValue);
  13919. args.Add(commaStr);
  13920. exprEvaluator.CreateCall(appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  13921. }
  13922. fieldIdx++;
  13923. if (fieldInstance.mResolvedType->IsValuelessType())
  13924. continue;
  13925. BfTypedValue fieldValue = ExtractValue(thisValue, &fieldInstance, fieldInstance.mDataIdx);
  13926. if (fieldValue.mType->IsPrimitiveType())
  13927. {
  13928. fieldValue.mType = GetPrimitiveStructType(((BfPrimitiveType*)fieldValue.mType)->mTypeDef->mTypeCode);
  13929. }
  13930. auto typeInstance = fieldValue.mType->ToTypeInstance();
  13931. if ((typeInstance != NULL) && (TypeIsSubTypeOf(typeInstance, iPrintableType, false)))
  13932. {
  13933. BfExprEvaluator exprEvaluator(this);
  13934. SizedArray<BfResolvedArg, 0> resolvedArgs;
  13935. BfMethodMatcher methodMatcher(NULL, this, printModuleMethodInstance.mMethodInstance, resolvedArgs);
  13936. methodMatcher.mBestMethodDef = printModuleMethodInstance.mMethodInstance->mMethodDef;
  13937. methodMatcher.mBestMethodTypeInstance = iPrintableType;
  13938. methodMatcher.TryDevirtualizeCall(fieldValue);
  13939. BfTypedValue callVal = Cast(NULL, fieldValue, methodMatcher.mBestMethodTypeInstance);
  13940. BfResolvedArg resolvedArg;
  13941. auto stringDestVal = LoadValue(stringDestRef);
  13942. resolvedArg.mTypedValue = stringDestVal;
  13943. resolvedArg.mResolvedType = stringDestVal.mType;
  13944. resolvedArgs.Add(resolvedArg);
  13945. exprEvaluator.CreateCall(&methodMatcher, callVal);
  13946. continue;
  13947. }
  13948. if (fieldValue.mType->IsObjectOrInterface())
  13949. {
  13950. fieldValue = LoadValue(fieldValue);
  13951. BF_ASSERT(!fieldValue.IsAddr());
  13952. SizedArray<BfIRValue, 2> args;
  13953. args.Add(mBfIRBuilder->CreateBitCast(fieldValue.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType)));
  13954. auto stringDestVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  13955. stringDestVal = LoadValue(stringDestVal);
  13956. args.Add(stringDestVal.mValue);
  13957. exprEvaluator.CreateCall(toStringSafeModuleMethodInstance.mMethodInstance, toStringSafeModuleMethodInstance.mFunc, false, args);
  13958. continue;
  13959. }
  13960. BfExprEvaluator exprEvaluator(this);
  13961. SizedArray<BfResolvedArg, 0> resolvedArgs;
  13962. BfMethodMatcher methodMatcher(NULL, this, toStringModuleMethodInstance.mMethodInstance, resolvedArgs);
  13963. methodMatcher.mBestMethodDef = toStringModuleMethodInstance.mMethodInstance->mMethodDef;
  13964. methodMatcher.mBestMethodTypeInstance = mContext->mBfObjectType;
  13965. methodMatcher.TryDevirtualizeCall(fieldValue);
  13966. if (methodMatcher.mBestMethodTypeInstance == mContext->mBfObjectType)
  13967. {
  13968. AddCallDependency(appendModuleMethodInstance.mMethodInstance);
  13969. AddDependency(fieldValue.mType, mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  13970. // Just append the type name
  13971. String typeName = TypeToString(fieldInstance.mResolvedType);
  13972. auto strVal = GetStringObjectValue(typeName);
  13973. SizedArray<BfIRValue, 2> args;
  13974. auto stringDestVal = LoadValue(stringDestRef);
  13975. args.Add(stringDestVal.mValue);
  13976. args.Add(strVal);
  13977. exprEvaluator.CreateCall(appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  13978. continue;
  13979. }
  13980. BfTypedValue callVal = Cast(NULL, fieldValue, methodMatcher.mBestMethodTypeInstance);
  13981. BfResolvedArg resolvedArg;
  13982. auto stringDestVal = LoadValue(stringDestRef);
  13983. resolvedArg.mTypedValue = stringDestVal;
  13984. resolvedArg.mResolvedType = stringDestVal.mType;
  13985. resolvedArgs.Add(resolvedArg);
  13986. exprEvaluator.CreateCall(&methodMatcher, callVal);
  13987. }
  13988. _AppendChar(')');
  13989. }
  13990. void BfModule::EmitIteratorBlock(bool& skipBody)
  13991. {
  13992. auto methodInstance = mCurMethodInstance;
  13993. auto methodDef = methodInstance->mMethodDef;
  13994. auto methodDeclaration = methodDef->GetMethodDeclaration();
  13995. auto typeDef = mCurTypeInstance->mTypeDef;
  13996. BfType* innerRetType = NULL;
  13997. BfTypeInstance* usingInterface = NULL;
  13998. auto retTypeInst = mCurMethodInstance->mReturnType->ToGenericTypeInstance();
  13999. if (retTypeInst != NULL)
  14000. {
  14001. if ((retTypeInst->mTypeDef == mCompiler->mGenericIEnumerableTypeDef) ||
  14002. (retTypeInst->mTypeDef == mCompiler->mGenericIEnumeratorTypeDef))
  14003. {
  14004. innerRetType = retTypeInst->mGenericTypeInfo->mTypeGenericArguments[0];
  14005. }
  14006. }
  14007. if (innerRetType == NULL)
  14008. {
  14009. Fail("Methods with yields must return either System.IEnumerable<T> or System.IEnumerator<T>", methodDeclaration->mReturnType);
  14010. return;
  14011. }
  14012. auto blockBody = BfNodeDynCast<BfBlock>(methodDeclaration->mBody);
  14013. if (blockBody == NULL)
  14014. return;
  14015. }
  14016. void BfModule::EmitGCMarkValue(BfTypedValue markVal, BfModuleMethodInstance markFromGCThreadMethodInstance)
  14017. {
  14018. auto fieldTypeInst = markVal.mType->ToTypeInstance();
  14019. if (fieldTypeInst == NULL)
  14020. return;
  14021. if (!markVal.mType->IsComposite())
  14022. markVal = LoadValue(markVal);
  14023. BfExprEvaluator exprEvaluator(this);
  14024. PopulateType(markVal.mType, BfPopulateType_Data);
  14025. if (markVal.mType->IsObjectOrInterface())
  14026. {
  14027. BfIRValue val = markVal.mValue;
  14028. val = mBfIRBuilder->CreateBitCast(val, mBfIRBuilder->MapType(mContext->mBfObjectType));
  14029. SizedArray<BfIRValue, 1> args;
  14030. args.push_back(val);
  14031. exprEvaluator.CreateCall(markFromGCThreadMethodInstance.mMethodInstance, markFromGCThreadMethodInstance.mFunc, false, args);
  14032. }
  14033. else if ((fieldTypeInst->IsComposite()) && (!fieldTypeInst->IsTypedPrimitive()))
  14034. {
  14035. auto markMemberMethodInstance = GetMethodByName(fieldTypeInst, BF_METHODNAME_MARKMEMBERS, 0, true);
  14036. if (markMemberMethodInstance)
  14037. {
  14038. SizedArray<BfIRValue, 1> args;
  14039. auto methodOwner = markMemberMethodInstance.mMethodInstance->GetOwner();
  14040. if (markVal.mType != methodOwner)
  14041. markVal = Cast(NULL, markVal, methodOwner);
  14042. exprEvaluator.PushThis(NULL, markVal, markMemberMethodInstance.mMethodInstance, args);
  14043. exprEvaluator.CreateCall(markMemberMethodInstance.mMethodInstance, markMemberMethodInstance.mFunc, false, args);
  14044. }
  14045. }
  14046. }
  14047. void BfModule::CallChainedMethods(BfMethodInstance* methodInstance, bool reverse)
  14048. {
  14049. Array<BfMethodInstance*> methodInstances;
  14050. for (int methodIdx = 0; methodIdx < (int)mCurTypeInstance->mMethodInstanceGroups.size(); methodIdx++)
  14051. {
  14052. auto& methodInstGroup = mCurTypeInstance->mMethodInstanceGroups[methodIdx];
  14053. auto chainedMethodInst = methodInstGroup.mDefault;
  14054. if ((chainedMethodInst != NULL) && (chainedMethodInst->mChainType == BfMethodChainType_ChainMember))
  14055. {
  14056. if ((chainedMethodInst->mMethodDef->mIsStatic == methodInstance->mMethodDef->mIsStatic) &&
  14057. (CompareMethodSignatures(methodInstance, chainedMethodInst)))
  14058. {
  14059. methodInstances.push_back(chainedMethodInst);
  14060. }
  14061. }
  14062. }
  14063. std::stable_sort(methodInstances.begin(), methodInstances.end(),
  14064. [&](BfMethodInstance* lhs, BfMethodInstance* rhs)
  14065. {
  14066. bool isBetter;
  14067. bool isWorse;
  14068. CompareDeclTypes(lhs->mMethodDef->mDeclaringType, rhs->mMethodDef->mDeclaringType, isBetter, isWorse);
  14069. if (isBetter == isWorse)
  14070. {
  14071. return false;
  14072. }
  14073. return isWorse;
  14074. });
  14075. if (reverse)
  14076. std::reverse(methodInstances.begin(), methodInstances.end());
  14077. for (auto chainedMethodInst : methodInstances)
  14078. {
  14079. auto declModule = this;
  14080. BfGetMethodInstanceFlags flags = BfGetMethodInstanceFlag_None;
  14081. auto moduleMethodInst = declModule->GetMethodInstance(mCurTypeInstance, chainedMethodInst->mMethodDef, BfTypeVector(), flags);
  14082. BfExprEvaluator exprEvaluator(this);
  14083. SizedArray<BfIRValue, 1> args;
  14084. exprEvaluator.PushThis(chainedMethodInst->mMethodDef->GetRefNode(), GetThis(), chainedMethodInst, args);
  14085. exprEvaluator.CreateCall(moduleMethodInst.mMethodInstance, moduleMethodInst.mFunc, true, args);
  14086. }
  14087. }
  14088. void BfModule::AddHotDataReferences(BfHotDataReferenceBuilder* builder)
  14089. {
  14090. BF_ASSERT(mCurMethodInstance->mIsReified);
  14091. if (mCurTypeInstance->mHotTypeData == NULL)
  14092. {
  14093. mCurTypeInstance->mHotTypeData = new BfHotTypeData();
  14094. BfLogSysM("Created HotTypeData %p created for type %p in AddHotDataReferences\n", mCurTypeInstance->mHotTypeData, mCurTypeInstance);
  14095. }
  14096. auto hotMethod = mCurMethodInstance->mHotMethod;
  14097. for (auto depData : hotMethod->mReferences)
  14098. {
  14099. // Only virtual decls are allowed to already be there
  14100. BF_ASSERT((depData->mDataKind == BfHotDepDataKind_VirtualDecl) || (depData->mDataKind == BfHotDepDataKind_DupMethod));
  14101. }
  14102. BF_ASSERT(hotMethod->mSrcTypeVersion != NULL);
  14103. int prevSize = (int)hotMethod->mReferences.size();
  14104. int refCount = (int)(prevSize + builder->mUsedData.size() + builder->mCalledMethods.size() + builder->mDevirtualizedCalledMethods.size());
  14105. if (!mCurMethodInstance->mMethodDef->mIsStatic)
  14106. refCount++;
  14107. hotMethod->mReferences.Reserve(refCount);
  14108. if (!mCurMethodInstance->mMethodDef->mIsStatic)
  14109. {
  14110. auto hotThis = mCompiler->mHotData->GetThisType(mCurMethodInstance->GetOwner()->mHotTypeData->GetLatestVersion());
  14111. hotThis->mRefCount++;
  14112. hotMethod->mReferences.Insert(0, hotThis);
  14113. prevSize++;
  14114. }
  14115. for (auto val : builder->mAllocatedData)
  14116. {
  14117. auto hotAllocation = mCompiler->mHotData->GetAllocation(val);
  14118. hotMethod->mReferences.Add(hotAllocation);
  14119. }
  14120. for (auto val : builder->mUsedData)
  14121. hotMethod->mReferences.Add(val);
  14122. for (auto val : builder->mCalledMethods)
  14123. hotMethod->mReferences.Add(val);
  14124. for (auto val : builder->mDevirtualizedCalledMethods)
  14125. {
  14126. auto devirtualizedMethod = mCompiler->mHotData->GetDevirtualizedMethod(val);
  14127. hotMethod->mReferences.Add(devirtualizedMethod);
  14128. }
  14129. for (auto val : builder->mFunctionPtrs)
  14130. {
  14131. auto funcRef = mCompiler->mHotData->GetFunctionReference(val);
  14132. hotMethod->mReferences.Add(funcRef);
  14133. }
  14134. for (auto val : builder->mInnerMethods)
  14135. {
  14136. auto innerMethod = mCompiler->mHotData->GetInnerMethod(val);
  14137. hotMethod->mReferences.Add(innerMethod);
  14138. }
  14139. for (int refIdx = prevSize; refIdx < (int)hotMethod->mReferences.size(); refIdx++)
  14140. {
  14141. auto depData = hotMethod->mReferences[refIdx];
  14142. BF_ASSERT(depData != NULL);
  14143. depData->mRefCount++;
  14144. }
  14145. }
  14146. void BfModule::ProcessMethod_SetupParams(BfMethodInstance* methodInstance, BfType* thisType, bool wantsDIData, SizedArrayImpl<BfIRMDNode>* diParams)
  14147. {
  14148. auto methodDef = methodInstance->mMethodDef;
  14149. auto methodDeclaration = methodDef->mMethodDeclaration;
  14150. bool isThisStruct = false;
  14151. if (thisType != NULL)
  14152. isThisStruct = thisType->IsStruct() && !thisType->IsTypedPrimitive();
  14153. int argIdx = 0;
  14154. if (argIdx == methodInstance->GetStructRetIdx())
  14155. argIdx++;
  14156. if (!methodDef->mIsStatic)
  14157. {
  14158. BfTypeCode loweredTypeCode = BfTypeCode_None;
  14159. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  14160. BfLocalVariable* paramVar = new BfLocalVariable();
  14161. paramVar->mResolvedType = thisType;
  14162. paramVar->mName = "this";
  14163. if (!thisType->IsValuelessType())
  14164. paramVar->mValue = mBfIRBuilder->GetArgument(argIdx);
  14165. else
  14166. paramVar->mValue = mBfIRBuilder->GetFakeVal();
  14167. if ((thisType->IsSplattable()) && (methodInstance->AllowsThisSplatting()))
  14168. {
  14169. if (!thisType->IsTypedPrimitive())
  14170. paramVar->mIsSplat = true;
  14171. }
  14172. else if ((!methodDef->mIsMutating) && (methodInstance->mCallingConvention == BfCallingConvention_Unspecified))
  14173. paramVar->mIsLowered = thisType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2) != BfTypeCode_None;
  14174. auto thisTypeInst = thisType->ToTypeInstance();
  14175. paramVar->mIsStruct = isThisStruct;
  14176. paramVar->mAddr = BfIRValue();
  14177. paramVar->mIsThis = true;
  14178. paramVar->mParamIdx = -1;
  14179. if ((methodDef->mMethodType == BfMethodType_Ctor) && (mCurTypeInstance->IsStruct()))
  14180. {
  14181. paramVar->mAssignedKind = BfLocalVarAssignKind_None;
  14182. }
  14183. else
  14184. {
  14185. paramVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  14186. }
  14187. paramVar->mReadFromId = -1;
  14188. paramVar->Init();
  14189. if (methodDeclaration == NULL)
  14190. UseDefaultSrcPos();
  14191. AddLocalVariableDef(paramVar);
  14192. if (!thisType->IsValuelessType())
  14193. {
  14194. if (wantsDIData)
  14195. {
  14196. BfType* thisPtrType = thisType;
  14197. auto diType = mBfIRBuilder->DbgGetType(thisPtrType);
  14198. if (!thisType->IsValueType())
  14199. diType = mBfIRBuilder->DbgCreateArtificialType(diType);
  14200. else if (!paramVar->mIsSplat)
  14201. diType = mBfIRBuilder->DbgCreatePointerType(diType);
  14202. diParams->push_back(diType);
  14203. }
  14204. if (paramVar->mIsSplat)
  14205. {
  14206. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  14207. }
  14208. else
  14209. {
  14210. argIdx++;
  14211. if (loweredTypeCode2 != BfTypeCode_None)
  14212. argIdx++;
  14213. }
  14214. }
  14215. }
  14216. if (argIdx == methodInstance->GetStructRetIdx())
  14217. argIdx++;
  14218. bool hadParams = false;
  14219. bool hasDefault = false;
  14220. int compositeVariableIdx = -1;
  14221. int paramIdx = 0;
  14222. for (paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  14223. {
  14224. // We already issues a type error for this param if we had one in declaration processing
  14225. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  14226. BfLocalVariable* paramVar = new BfLocalVariable();
  14227. BfTypeCode loweredTypeCode = BfTypeCode_None;
  14228. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  14229. bool isParamSkipped = methodInstance->IsParamSkipped(paramIdx);
  14230. auto resolvedType = methodInstance->GetParamType(paramIdx);
  14231. if (resolvedType == NULL)
  14232. {
  14233. AssertErrorState();
  14234. paramVar->mParamFailed = true;
  14235. }
  14236. prevIgnoreErrors.Restore();
  14237. PopulateType(resolvedType, BfPopulateType_Declaration);
  14238. paramVar->mResolvedType = resolvedType;
  14239. paramVar->mName = methodInstance->GetParamName(paramIdx);
  14240. paramVar->mNameNode = methodInstance->GetParamNameNode(paramIdx);
  14241. if (!isParamSkipped)
  14242. {
  14243. paramVar->mValue = mBfIRBuilder->GetArgument(argIdx);
  14244. if (resolvedType->IsMethodRef())
  14245. {
  14246. paramVar->mIsSplat = true;
  14247. }
  14248. else if (resolvedType->IsComposite() && resolvedType->IsSplattable())
  14249. {
  14250. if (methodInstance->AllowsSplatting())
  14251. {
  14252. int splatCount = resolvedType->GetSplatCount();
  14253. if (argIdx + splatCount <= mCompiler->mOptions.mMaxSplatRegs)
  14254. paramVar->mIsSplat = true;
  14255. }
  14256. }
  14257. }
  14258. else
  14259. {
  14260. paramVar->mIsSplat = true; // Treat skipped (valueless) as a splat
  14261. paramVar->mValue = mBfIRBuilder->GetFakeVal();
  14262. }
  14263. paramVar->mIsLowered = resolvedType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2) != BfTypeCode_None;
  14264. paramVar->mIsStruct = resolvedType->IsComposite() && !resolvedType->IsTypedPrimitive();
  14265. paramVar->mParamIdx = paramIdx;
  14266. paramVar->mIsImplicitParam = methodInstance->IsImplicitCapture(paramIdx);
  14267. paramVar->mReadFromId = 0;
  14268. if (resolvedType->IsRef())
  14269. {
  14270. auto refType = (BfRefType*)resolvedType;
  14271. paramVar->mAssignedKind = (refType->mRefKind != BfRefType::RefKind_Out) ? BfLocalVarAssignKind_Unconditional : BfLocalVarAssignKind_None;
  14272. }
  14273. else
  14274. {
  14275. paramVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  14276. if (methodDef->mMethodType != BfMethodType_Mixin)
  14277. paramVar->mIsReadOnly = true;
  14278. }
  14279. if (paramVar->mResolvedType->IsGenericParam())
  14280. {
  14281. auto genericParamInst = GetGenericParamInstance((BfGenericParamType*)paramVar->mResolvedType);
  14282. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  14283. {
  14284. auto typedVal = GetDefaultTypedValue(genericParamInst->mTypeConstraint, false, BfDefaultValueKind_Undef);
  14285. paramVar->mResolvedType = typedVal.mType;
  14286. paramVar->mConstValue = typedVal.mValue;
  14287. }
  14288. }
  14289. if (paramVar->mResolvedType->IsConstExprValue())
  14290. {
  14291. BfConstExprValueType* constExprValueType = (BfConstExprValueType*)paramVar->mResolvedType;
  14292. auto unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance);
  14293. auto unspecParamType = unspecializedMethodInstance->GetParamType(paramIdx);
  14294. BF_ASSERT(unspecParamType->IsGenericParam());
  14295. if (unspecParamType->IsGenericParam())
  14296. {
  14297. BfGenericParamType* genericParamType = (BfGenericParamType*)unspecParamType;
  14298. if (genericParamType->mGenericParamKind == BfGenericParamKind_Method)
  14299. {
  14300. auto genericParamInst = unspecializedMethodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  14301. if (genericParamInst->mTypeConstraint != NULL)
  14302. {
  14303. BfExprEvaluator exprEvaluator(this);
  14304. exprEvaluator.mExpectingType = genericParamInst->mTypeConstraint;
  14305. exprEvaluator.GetLiteral(NULL, constExprValueType->mValue);
  14306. auto checkType = genericParamInst->mTypeConstraint;
  14307. if (checkType->IsTypedPrimitive())
  14308. checkType = checkType->GetUnderlyingType();
  14309. if (exprEvaluator.mResult.mType == checkType)
  14310. {
  14311. paramVar->mResolvedType = genericParamInst->mTypeConstraint;
  14312. paramVar->mConstValue = exprEvaluator.mResult.mValue;
  14313. BF_ASSERT(paramVar->mConstValue.IsConst());
  14314. }
  14315. else
  14316. {
  14317. AssertErrorState();
  14318. paramVar->mResolvedType = genericParamInst->mTypeConstraint;
  14319. paramVar->mConstValue = GetDefaultValue(genericParamInst->mTypeConstraint);
  14320. }
  14321. }
  14322. }
  14323. }
  14324. //BF_ASSERT(!paramVar->mResolvedType->IsConstExprValue());
  14325. if (paramVar->mResolvedType->IsConstExprValue())
  14326. {
  14327. Fail("Invalid use of constant expression", methodInstance->GetParamTypeRef(paramIdx));
  14328. //AssertErrorState();
  14329. paramVar->mResolvedType = GetPrimitiveType(BfTypeCode_IntPtr);
  14330. paramVar->mConstValue = GetDefaultValue(paramVar->mResolvedType);
  14331. }
  14332. }
  14333. if (methodInstance->GetParamKind(paramIdx) == BfParamKind_DelegateParam)
  14334. {
  14335. if (compositeVariableIdx == -1)
  14336. {
  14337. compositeVariableIdx = (int)mCurMethodState->mLocals.size();
  14338. BfLocalVariable* localVar = new BfLocalVariable();
  14339. auto paramInst = &methodInstance->mParams[paramIdx];
  14340. auto paramDef = methodDef->mParams[paramInst->mParamDefIdx];
  14341. localVar->mName = paramDef->mName;
  14342. localVar->mResolvedType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_NoResolveGenericParam);
  14343. localVar->mCompositeCount = 0;
  14344. DoAddLocalVariable(localVar);
  14345. }
  14346. mCurMethodState->mLocals[compositeVariableIdx]->mCompositeCount++;
  14347. }
  14348. CheckVariableDef(paramVar);
  14349. paramVar->Init();
  14350. AddLocalVariableDef(paramVar);
  14351. if (!isParamSkipped)
  14352. {
  14353. if (wantsDIData)
  14354. diParams->push_back(mBfIRBuilder->DbgGetType(resolvedType));
  14355. if (paramVar->mIsSplat)
  14356. {
  14357. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  14358. }
  14359. else
  14360. {
  14361. argIdx++;
  14362. }
  14363. if (loweredTypeCode2 != BfTypeCode_None)
  14364. argIdx++;
  14365. }
  14366. }
  14367. // Try to find an ending delegate params composite
  14368. if ((compositeVariableIdx == -1) && (methodDef->mParams.size() > 0))
  14369. {
  14370. auto paramDef = methodDef->mParams.back();
  14371. if (paramDef->mParamKind == BfParamKind_Params)
  14372. {
  14373. auto paramsType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_NoResolveGenericParam);
  14374. if (paramsType == NULL)
  14375. {
  14376. AssertErrorState();
  14377. }
  14378. else if (paramsType->IsGenericParam())
  14379. {
  14380. auto genericParamInstance = GetGenericParamInstance((BfGenericParamType*)paramsType);
  14381. if (genericParamInstance->mTypeConstraint != NULL)
  14382. {
  14383. auto typeInstConstraint = genericParamInstance->mTypeConstraint->ToTypeInstance();
  14384. if ((genericParamInstance->mTypeConstraint->IsDelegate()) || (genericParamInstance->mTypeConstraint->IsFunction()) ||
  14385. ((typeInstConstraint != NULL) &&
  14386. ((typeInstConstraint->mTypeDef == mCompiler->mDelegateTypeDef) || (typeInstConstraint->mTypeDef == mCompiler->mFunctionTypeDef))))
  14387. {
  14388. BfLocalVariable* localVar = new BfLocalVariable();
  14389. localVar->mName = paramDef->mName;
  14390. localVar->mResolvedType = paramsType;
  14391. localVar->mCompositeCount = 0;
  14392. DoAddLocalVariable(localVar);
  14393. }
  14394. }
  14395. }
  14396. else if (paramsType->IsDelegate())
  14397. {
  14398. BfMethodInstance* invokeMethodInstance = GetRawMethodInstanceAtIdx(paramsType->ToTypeInstance(), 0, "Invoke");
  14399. if (invokeMethodInstance != NULL)
  14400. {
  14401. // This is only for the case where the delegate didn't actually have any params so the composite is zero-sized
  14402. // and wasn't cleared by the preceding loop
  14403. BF_ASSERT(invokeMethodInstance->GetParamCount() == 0);
  14404. BfLocalVariable* localVar = new BfLocalVariable();
  14405. localVar->mName = paramDef->mName;
  14406. localVar->mResolvedType = paramsType;
  14407. localVar->mCompositeCount = 0;
  14408. DoAddLocalVariable(localVar);
  14409. }
  14410. }
  14411. }
  14412. }
  14413. }
  14414. void BfModule::ProcessMethod_ProcessDeferredLocals(int startIdx)
  14415. {
  14416. // if (mCurMethodState->mPrevMethodState != NULL) // Re-entry
  14417. // return;
  14418. auto _ClearState = [&]()
  14419. {
  14420. mCurMethodState->mLocalMethods.Clear();
  14421. for (auto& local : mCurMethodState->mLocals)
  14422. delete local;
  14423. mCurMethodState->mLocals.Clear();
  14424. mCurMethodState->mLocalVarSet.Clear();
  14425. };
  14426. // 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
  14427. // we show errors in the capture phase. If we somehow pass the capture phase without error then this method WILL show any errors here,
  14428. // however (compiler bug), so this is the safest way
  14429. if (!mCurMethodState->mDeferredLocalMethods.IsEmpty())
  14430. {
  14431. for (int deferredLocalMethodIdx = 0; deferredLocalMethodIdx < (int)mCurMethodState->mDeferredLocalMethods.size(); deferredLocalMethodIdx++)
  14432. {
  14433. auto deferredLocalMethod = mCurMethodState->mDeferredLocalMethods[deferredLocalMethodIdx];
  14434. BfLogSysM("Processing deferred local method %p\n", deferredLocalMethod);
  14435. if (!mHadBuildError)
  14436. {
  14437. // Process as a closure - that allows us to look back and see the const locals and stuff
  14438. BfClosureState closureState;
  14439. mCurMethodState->mClosureState = &closureState;
  14440. closureState.mConstLocals = deferredLocalMethod->mConstLocals;
  14441. closureState.mReturnType = deferredLocalMethod->mMethodInstance->mReturnType;
  14442. closureState.mActiveDeferredLocalMethod = deferredLocalMethod;
  14443. closureState.mLocalMethod = deferredLocalMethod->mLocalMethod;
  14444. if (deferredLocalMethod->mMethodInstance->mMethodInfoEx != NULL)
  14445. closureState.mClosureInstanceInfo = deferredLocalMethod->mMethodInstance->mMethodInfoEx->mClosureInstanceInfo;
  14446. mCurMethodState->mMixinState = deferredLocalMethod->mLocalMethod->mDeclMixinState;
  14447. _ClearState();
  14448. for (auto& constLocal : deferredLocalMethod->mConstLocals)
  14449. {
  14450. auto localVar = new BfLocalVariable();
  14451. *localVar = constLocal;
  14452. DoAddLocalVariable(localVar);
  14453. }
  14454. mCurMethodState->mLocalMethods = deferredLocalMethod->mLocalMethods;
  14455. bool doProcess = !mCompiler->mCanceling;
  14456. if (doProcess)
  14457. {
  14458. BP_ZONE_F("ProcessMethod local %s", deferredLocalMethod->mMethodInstance->mMethodDef->mName.c_str());
  14459. ProcessMethod(deferredLocalMethod->mMethodInstance);
  14460. }
  14461. }
  14462. delete deferredLocalMethod;
  14463. mSystem->CheckLockYield();
  14464. }
  14465. }
  14466. for (auto& kv : mCurMethodState->mLocalMethodCache)
  14467. {
  14468. BF_ASSERT((kv.mValue->mMethodDef == NULL) || (kv.mKey == kv.mValue->mMethodDef->mName));
  14469. }
  14470. if ((!mCurMethodState->mDeferredLambdaInstances.IsEmpty()) && (!mHadBuildError))
  14471. {
  14472. for (int deferredLambdaIdx = 0; deferredLambdaIdx < (int)mCurMethodState->mDeferredLambdaInstances.size(); deferredLambdaIdx++)
  14473. {
  14474. auto lambdaInstance = mCurMethodState->mDeferredLambdaInstances[deferredLambdaIdx];
  14475. BfLogSysM("Processing deferred lambdaInstance %p\n", lambdaInstance);
  14476. BfClosureState closureState;
  14477. mCurMethodState->mClosureState = &closureState;
  14478. //closureState.mConstLocals = deferredLocalMethod->mConstLocals;
  14479. closureState.mReturnType = lambdaInstance->mMethodInstance->mReturnType;
  14480. if (lambdaInstance->mClosureTypeInstance != NULL)
  14481. closureState.mClosureType = lambdaInstance->mClosureTypeInstance;
  14482. else
  14483. closureState.mClosureType = lambdaInstance->mDelegateTypeInstance;
  14484. closureState.mClosureInstanceInfo = lambdaInstance->mMethodInstance->mMethodInfoEx->mClosureInstanceInfo;
  14485. closureState.mDeclaringMethodIsMutating = lambdaInstance->mDeclaringMethodIsMutating;
  14486. mCurMethodState->mMixinState = lambdaInstance->mDeclMixinState;
  14487. _ClearState();
  14488. for (auto& constLocal : lambdaInstance->mConstLocals)
  14489. {
  14490. //if (constLocal.mIsThis)
  14491. {
  14492. // Valueless 'this'
  14493. closureState.mConstLocals.Add(constLocal);
  14494. }
  14495. /*else
  14496. {
  14497. auto localVar = new BfLocalVariable();
  14498. *localVar = constLocal;
  14499. DoAddLocalVariable(localVar);
  14500. }*/
  14501. }
  14502. BfMethodInstanceGroup methodInstanceGroup;
  14503. methodInstanceGroup.mOwner = mCurTypeInstance;
  14504. methodInstanceGroup.mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  14505. bool doProcess = !mCompiler->mCanceling;
  14506. if (doProcess)
  14507. {
  14508. BP_ZONE_F("ProcessMethod lambdaInstance %s", lambdaInstance->mMethodInstance->mMethodDef->mName.c_str());
  14509. lambdaInstance->mMethodInstance->mMethodInstanceGroup = &methodInstanceGroup;
  14510. ProcessMethod(lambdaInstance->mMethodInstance);
  14511. if (lambdaInstance->mDtorMethodInstance != NULL)
  14512. {
  14513. lambdaInstance->mDtorMethodInstance->mMethodInstanceGroup = &methodInstanceGroup;
  14514. ProcessMethod(lambdaInstance->mDtorMethodInstance);
  14515. }
  14516. }
  14517. }
  14518. mSystem->CheckLockYield();
  14519. }
  14520. }
  14521. void BfModule::EmitGCMarkValue(BfTypedValue& thisValue, BfType* checkType, int memberDepth, int curOffset, HashSet<int>& objectOffsets, BfModuleMethodInstance markFromGCThreadMethodInstance)
  14522. {
  14523. if (checkType->IsComposite())
  14524. PopulateType(checkType, BfPopulateType_Data);
  14525. if (!checkType->WantsGCMarking())
  14526. return;
  14527. auto typeInstance = checkType->ToTypeInstance();
  14528. bool callMarkMethod = false;
  14529. // Call the actual marking method
  14530. if (memberDepth == 0)
  14531. {
  14532. // Don't call marking method on self
  14533. }
  14534. else if (checkType->IsObjectOrInterface())
  14535. {
  14536. if (!objectOffsets.Add(curOffset))
  14537. {
  14538. return;
  14539. }
  14540. callMarkMethod = true;
  14541. }
  14542. else if (checkType->IsSizedArray())
  14543. {
  14544. BfSizedArrayType* sizedArrayType = (BfSizedArrayType*)checkType;
  14545. if (sizedArrayType->mElementType->WantsGCMarking())
  14546. {
  14547. BfTypedValue arrayValue = thisValue;
  14548. if (thisValue.mType != checkType)
  14549. {
  14550. BfIRValue srcValue = thisValue.mValue;
  14551. if (curOffset != 0)
  14552. {
  14553. if (!thisValue.mType->IsPointer())
  14554. {
  14555. auto int8Type = GetPrimitiveType(BfTypeCode_UInt8);
  14556. auto int8PtrType = CreatePointerType(int8Type);
  14557. srcValue = mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(int8PtrType));
  14558. }
  14559. srcValue = mBfIRBuilder->CreateInBoundsGEP(srcValue, curOffset);
  14560. }
  14561. arrayValue = BfTypedValue(mBfIRBuilder->CreateBitCast(srcValue, mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(checkType))), checkType, BfTypedValueKind_Addr);
  14562. }
  14563. auto _SizedIndex = [&](BfIRValue target, BfIRValue index)
  14564. {
  14565. if (sizedArrayType->mElementType->IsSizeAligned())
  14566. {
  14567. auto ptrType = CreatePointerType(sizedArrayType->mElementType);
  14568. auto ptrValue = mBfIRBuilder->CreateBitCast(target, mBfIRBuilder->MapType(ptrType));
  14569. auto gepResult = mBfIRBuilder->CreateInBoundsGEP(ptrValue, index);
  14570. return BfTypedValue(gepResult, sizedArrayType->mElementType, BfTypedValueKind_Addr);
  14571. }
  14572. else
  14573. {
  14574. auto indexResult = CreateIndexedValue(sizedArrayType->mElementType, target, index);
  14575. return BfTypedValue(indexResult, sizedArrayType->mElementType, BfTypedValueKind_Addr);
  14576. }
  14577. };
  14578. if (sizedArrayType->mElementCount > 6)
  14579. {
  14580. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  14581. auto itr = CreateAlloca(intPtrType);
  14582. mBfIRBuilder->CreateStore(GetDefaultValue(intPtrType), itr);
  14583. auto loopBB = mBfIRBuilder->CreateBlock("loop", true);
  14584. auto bodyBB = mBfIRBuilder->CreateBlock("body", true);
  14585. auto doneBB = mBfIRBuilder->CreateBlock("done", true);
  14586. mBfIRBuilder->CreateBr(loopBB);
  14587. mBfIRBuilder->SetInsertPoint(loopBB);
  14588. auto loadedItr = mBfIRBuilder->CreateLoad(itr);
  14589. auto cmpRes = mBfIRBuilder->CreateCmpGTE(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)sizedArrayType->mElementCount), true);
  14590. mBfIRBuilder->CreateCondBr(cmpRes, doneBB, bodyBB);
  14591. mBfIRBuilder->SetInsertPoint(bodyBB);
  14592. BfTypedValue value = _SizedIndex(arrayValue.mValue, loadedItr);
  14593. EmitGCMarkValue(value, markFromGCThreadMethodInstance);
  14594. auto incValue = mBfIRBuilder->CreateAdd(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  14595. mBfIRBuilder->CreateStore(incValue, itr);
  14596. mBfIRBuilder->CreateBr(loopBB);
  14597. mBfIRBuilder->SetInsertPoint(doneBB);
  14598. }
  14599. else
  14600. {
  14601. for (int dataIdx = 0; dataIdx < sizedArrayType->mElementCount; dataIdx++)
  14602. {
  14603. BfTypedValue value = _SizedIndex(arrayValue.mValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, dataIdx));
  14604. HashSet<int> objectOffsets;
  14605. EmitGCMarkValue(value, markFromGCThreadMethodInstance);
  14606. }
  14607. }
  14608. }
  14609. }
  14610. else if (typeInstance != NULL)
  14611. {
  14612. typeInstance->mTypeDef->PopulateMemberSets();
  14613. BfMemberSetEntry* entry = NULL;
  14614. BfMethodDef* methodDef = NULL;
  14615. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(String(BF_METHODNAME_MARKMEMBERS), &entry))
  14616. {
  14617. methodDef = (BfMethodDef*)entry->mMemberDef;
  14618. if (methodDef->HasBody())
  14619. {
  14620. callMarkMethod = true;
  14621. }
  14622. }
  14623. }
  14624. if (callMarkMethod)
  14625. {
  14626. BfTypedValue markValue;
  14627. auto memberType = checkType;
  14628. if (memberType->IsObjectOrInterface())
  14629. memberType = mContext->mBfObjectType; // Just to avoid that extra cast for the call itself
  14630. auto memberPtrType = CreatePointerType(memberType);
  14631. if (curOffset == 0)
  14632. {
  14633. markValue = BfTypedValue(mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(memberPtrType)), memberType, true);
  14634. }
  14635. else
  14636. {
  14637. if (!thisValue.mType->IsPointer())
  14638. {
  14639. auto int8Type = GetPrimitiveType(BfTypeCode_UInt8);
  14640. auto int8PtrType = CreatePointerType(int8Type);
  14641. thisValue = BfTypedValue(mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(int8PtrType)), int8PtrType);
  14642. }
  14643. auto offsetValue = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, curOffset);
  14644. markValue = BfTypedValue(mBfIRBuilder->CreateBitCast(offsetValue, mBfIRBuilder->MapType(memberPtrType)), memberType, true);
  14645. }
  14646. EmitGCMarkValue(markValue, markFromGCThreadMethodInstance);
  14647. return;
  14648. }
  14649. auto methodDef = mCurMethodInstance->mMethodDef;
  14650. if (checkType->IsPayloadEnum())
  14651. {
  14652. for (auto& fieldInst : typeInstance->mFieldInstances)
  14653. {
  14654. if (!fieldInst.mIsEnumPayloadCase)
  14655. continue;
  14656. auto fieldDef = fieldInst.GetFieldDef();
  14657. EmitGCMarkValue(thisValue, fieldInst.mResolvedType, memberDepth + 1, curOffset, objectOffsets, markFromGCThreadMethodInstance);
  14658. }
  14659. return;
  14660. }
  14661. if (typeInstance == NULL)
  14662. return;
  14663. for (auto& fieldInst : typeInstance->mFieldInstances)
  14664. {
  14665. auto fieldDef = fieldInst.GetFieldDef();
  14666. if (fieldDef == NULL)
  14667. continue;
  14668. if (fieldDef->mIsStatic)
  14669. continue;
  14670. if (typeInstance == mCurTypeInstance)
  14671. {
  14672. // Note: we don't do method chaining when we are marking members of members. Theoretically this means
  14673. // we may be marking member values that can never contain a value anyway, but this is benign
  14674. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  14675. continue;
  14676. }
  14677. EmitGCMarkValue(thisValue, fieldInst.mResolvedType, memberDepth + 1, curOffset + fieldInst.mDataOffset, objectOffsets, markFromGCThreadMethodInstance);
  14678. }
  14679. if ((typeInstance->mBaseType != NULL) && (typeInstance->mBaseType != mContext->mBfObjectType))
  14680. {
  14681. EmitGCMarkValue(thisValue, typeInstance->mBaseType, memberDepth, curOffset, objectOffsets, markFromGCThreadMethodInstance);
  14682. }
  14683. }
  14684. void BfModule::EmitGCMarkMembers()
  14685. {
  14686. auto methodDef = mCurMethodInstance->mMethodDef;
  14687. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef, BfPopulateType_DataAndMethods);
  14688. BfModuleMethodInstance markFromGCThreadMethodInstance;
  14689. if (gcType != NULL)
  14690. markFromGCThreadMethodInstance = GetMethodByName(gcType->ToTypeInstance(), "Mark", 1);
  14691. if ((markFromGCThreadMethodInstance.mMethodInstance != NULL) && (!mCurMethodInstance->mIsUnspecialized))
  14692. {
  14693. if (mCurTypeInstance->IsBoxed())
  14694. {
  14695. // This already gets filled in by the normal boxed forwarding
  14696. }
  14697. else
  14698. {
  14699. auto thisValue = GetThis();
  14700. if (thisValue.IsSplat())
  14701. {
  14702. BfIRFunction func = mCurMethodInstance->mIRFunction;
  14703. int argIdx = 0;
  14704. std::function<void(BfType*)> checkTypeLambda = [&](BfType* checkType)
  14705. {
  14706. if (checkType->IsStruct())
  14707. {
  14708. auto checkTypeInstance = checkType->ToTypeInstance();
  14709. if (checkTypeInstance->mBaseType != NULL)
  14710. checkTypeLambda(checkTypeInstance->mBaseType);
  14711. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  14712. {
  14713. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  14714. if (fieldInstance->mDataIdx >= 0)
  14715. checkTypeLambda(fieldInstance->GetResolvedType());
  14716. }
  14717. }
  14718. else if (checkType->IsMethodRef())
  14719. {
  14720. BFMODULE_FATAL(this, "Not handled");
  14721. }
  14722. else if (checkType->WantsGCMarking())
  14723. {
  14724. BfTypedValue markValue(mBfIRBuilder->GetArgument(argIdx), checkType);
  14725. EmitGCMarkValue(markValue, markFromGCThreadMethodInstance);
  14726. argIdx++;
  14727. }
  14728. };
  14729. checkTypeLambda(thisValue.mType);
  14730. }
  14731. else if (!methodDef->mIsStatic)
  14732. {
  14733. if ((mCurTypeInstance->mBaseType != NULL) && (!mCurTypeInstance->IsTypedPrimitive()) && (mCurTypeInstance->mBaseType->WantsGCMarking()))
  14734. {
  14735. BfModuleMethodInstance moduleMethodInst = GetMethodByName(mCurTypeInstance->mBaseType, BF_METHODNAME_MARKMEMBERS, 0, true);
  14736. if (moduleMethodInst)
  14737. {
  14738. auto methodBaseType = moduleMethodInst.mMethodInstance->GetOwner();
  14739. if (methodBaseType != mContext->mBfObjectType)
  14740. {
  14741. auto thisValue = GetThis();
  14742. auto baseValue = Cast(NULL, thisValue, methodBaseType, BfCastFlags_Explicit);
  14743. SizedArray<BfIRValue, 1> args;
  14744. if (moduleMethodInst.mMethodInstance->GetParamIsSplat(-1))
  14745. {
  14746. BfExprEvaluator exprEvaluator(this);
  14747. exprEvaluator.SplatArgs(baseValue, args);
  14748. }
  14749. else
  14750. {
  14751. args.push_back(baseValue.mValue);
  14752. }
  14753. mBfIRBuilder->CreateCall(moduleMethodInst.mFunc, args);
  14754. }
  14755. }
  14756. }
  14757. }
  14758. if (!methodDef->mIsStatic)
  14759. {
  14760. HashSet<int> objectOffsets;
  14761. EmitGCMarkValue(thisValue, mCurTypeInstance, 0, 0, objectOffsets, markFromGCThreadMethodInstance);
  14762. }
  14763. else
  14764. {
  14765. for (auto& fieldInst : mCurTypeInstance->mFieldInstances)
  14766. {
  14767. if (thisValue.IsSplat())
  14768. break;
  14769. auto fieldDef = fieldInst.GetFieldDef();
  14770. if (fieldDef == NULL)
  14771. continue;
  14772. if (fieldInst.mIsThreadLocal)
  14773. continue;
  14774. if (fieldDef->mIsStatic == methodDef->mIsStatic)
  14775. {
  14776. // For extensions, only handle these fields in the appropriate extension
  14777. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  14778. continue;
  14779. if (!fieldInst.mFieldIncluded)
  14780. continue;
  14781. auto fieldTypeInst = fieldInst.mResolvedType->ToTypeInstance();
  14782. if (fieldTypeInst != NULL)
  14783. {
  14784. auto fieldDef = fieldInst.GetFieldDef();
  14785. BfTypedValue markVal;
  14786. if (fieldDef->mIsConst)
  14787. continue;
  14788. if ((!fieldTypeInst->IsObjectOrInterface()) && (!fieldTypeInst->IsComposite()))
  14789. continue;
  14790. mBfIRBuilder->PopulateType(fieldTypeInst);
  14791. if (fieldTypeInst->IsValuelessType())
  14792. continue;
  14793. if ((fieldDef->mIsStatic) && (!fieldDef->mIsConst))
  14794. {
  14795. StringT<128> staticVarName;
  14796. BfMangler::Mangle(staticVarName, mCompiler->GetMangleKind(), &fieldInst);
  14797. if (staticVarName.StartsWith('#'))
  14798. continue;
  14799. markVal = ReferenceStaticField(&fieldInst);
  14800. }
  14801. else if (!fieldDef->mIsStatic)
  14802. {
  14803. markVal = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInst.mDataIdx/*, fieldDef->mName*/), fieldInst.mResolvedType, true);
  14804. }
  14805. if (markVal)
  14806. EmitGCMarkValue(markVal, markFromGCThreadMethodInstance);
  14807. }
  14808. }
  14809. }
  14810. }
  14811. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  14812. CallChainedMethods(mCurMethodInstance, false);
  14813. }
  14814. }
  14815. }
  14816. void BfModule::EmitGCFindTLSMembers()
  14817. {
  14818. auto methodDef = mCurMethodInstance->mMethodDef;
  14819. auto gcTypeInst = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  14820. auto reportTLSMark = GetMethodByName(gcTypeInst, "ReportTLSMember", 2);
  14821. BF_ASSERT(reportTLSMark);
  14822. for (auto& fieldInst : mCurTypeInstance->mFieldInstances)
  14823. {
  14824. auto fieldDef = fieldInst.GetFieldDef();
  14825. if (fieldDef == NULL)
  14826. continue;
  14827. if (!fieldInst.mIsThreadLocal)
  14828. continue;
  14829. // For extensions, only handle these fields in the appropriate extension
  14830. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  14831. continue;
  14832. if (!fieldInst.mFieldIncluded)
  14833. continue;
  14834. if (fieldDef->mIsConst)
  14835. continue;
  14836. auto fieldType = fieldInst.mResolvedType;
  14837. if ((!fieldType->IsObjectOrInterface()) && (!fieldType->IsComposite()))
  14838. continue;
  14839. if (fieldType->IsValuelessType())
  14840. continue;
  14841. BfTypedValue markVal = ReferenceStaticField(&fieldInst);
  14842. if (markVal)
  14843. {
  14844. BfIRValue fieldRefPtr = mBfIRBuilder->CreateBitCast(markVal.mValue, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  14845. BfIRValue markFuncPtr = GetMarkFuncPtr(fieldType);
  14846. SizedArray<BfIRValue, 2> llvmArgs;
  14847. llvmArgs.push_back(fieldRefPtr);
  14848. llvmArgs.push_back(markFuncPtr);
  14849. mBfIRBuilder->CreateCall(reportTLSMark.mFunc, llvmArgs);
  14850. }
  14851. }
  14852. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  14853. CallChainedMethods(mCurMethodInstance, false);
  14854. }
  14855. void BfModule::ProcessMethod(BfMethodInstance* methodInstance, bool isInlineDup)
  14856. {
  14857. BP_ZONE_F("BfModule::ProcessMethod %s", BP_DYN_STR(methodInstance->mMethodDef->mName.c_str()));
  14858. if (mAwaitingInitFinish)
  14859. FinishInit();
  14860. if (!methodInstance->mIsReified)
  14861. BF_ASSERT(!mIsReified);
  14862. BF_ASSERT(!methodInstance->GetOwner()->IsUnspecializedTypeVariation());
  14863. if (methodInstance->mMethodInfoEx != NULL)
  14864. {
  14865. for (auto methodGenericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  14866. {
  14867. if (methodGenericArg->IsMethodRef())
  14868. {
  14869. auto methodRefType = (BfMethodRefType*)methodGenericArg;
  14870. BF_ASSERT(methodRefType->mOwnerRevision == methodRefType->mOwner->mRevision);
  14871. }
  14872. }
  14873. }
  14874. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mWantsIRIgnoreWrites || methodInstance->mIsUnspecialized);
  14875. bool ignoreWrites = mBfIRBuilder->mIgnoreWrites;
  14876. if ((HasCompiledOutput()) && (!mBfIRBuilder->mIgnoreWrites))
  14877. {
  14878. BF_ASSERT(!methodInstance->mIRFunction.IsFake() || (methodInstance->GetImportCallKind() != BfImportCallKind_None));
  14879. }
  14880. SetAndRestoreValue<BfSourceClassifier*> prevSourceClassifier;
  14881. if (((methodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend) || (methodInstance->mIsForeignMethodDef) || (methodInstance->IsSpecializedGenericMethod())) &&
  14882. (mCompiler->mResolvePassData != NULL))
  14883. {
  14884. // Don't classify on the CtorCalcAppend, just on the actual Ctor
  14885. prevSourceClassifier.Init(mCompiler->mResolvePassData->mSourceClassifier, NULL);
  14886. }
  14887. if (methodInstance->mHasBeenProcessed)
  14888. {
  14889. BfLogSysM("ProcessMethod %p HasBeenProcessed\n", methodInstance);
  14890. return;
  14891. }
  14892. if (methodInstance->mFailedConstraints)
  14893. {
  14894. // The only way this should be able to happen is if we fail our generic param check
  14895. BF_ASSERT(methodInstance->IsSpecializedGenericMethod());
  14896. BfLogSysM("Method instance marked as 'failed' at start of ProcessMethod %p\n", methodInstance);
  14897. methodInstance->mHasBeenProcessed = true;
  14898. return;
  14899. }
  14900. if (HasCompiledOutput())
  14901. {
  14902. BF_ASSERT(mIsModuleMutable);
  14903. }
  14904. BfMethodInstance* defaultMethodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  14905. BF_ASSERT(methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_NotSet);
  14906. if ((methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_AlwaysInclude) &&
  14907. (methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_Referenced))
  14908. {
  14909. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Referenced;
  14910. auto owningModule = methodInstance->GetOwner()->mModule;
  14911. if (owningModule->mIsScratchModule)
  14912. {
  14913. BF_ASSERT(owningModule->mOnDemandMethodCount == 0);
  14914. }
  14915. else
  14916. {
  14917. BF_ASSERT((owningModule->mOnDemandMethodCount > 0) || (!HasCompiledOutput()) || (owningModule->mExtensionCount > 0));
  14918. if (owningModule->mOnDemandMethodCount > 0)
  14919. owningModule->mOnDemandMethodCount--;
  14920. }
  14921. }
  14922. // We set mHasBeenProcessed to true immediately -- this helps avoid stack overflow during recursion for things like
  14923. // self-referencing append allocations in ctor@calcAppend
  14924. methodInstance->mHasBeenProcessed = true;
  14925. mIncompleteMethodCount--;
  14926. BF_ASSERT((mIsSpecialModule) || (mIncompleteMethodCount >= 0));
  14927. auto typeDef = methodInstance->mMethodInstanceGroup->mOwner->mTypeDef;
  14928. auto methodDef = methodInstance->mMethodDef;
  14929. auto methodDeclaration = methodDef->GetMethodDeclaration();
  14930. if ((methodInstance->mIsReified) && (methodInstance->mVirtualTableIdx != -1))
  14931. {
  14932. // If we reify a virtual method in a HotCompile then we need to make sure the type data gets written out
  14933. // so we get the new vdata for it
  14934. methodInstance->GetOwner()->mDirty = true;
  14935. }
  14936. int dependentGenericStartIdx = 0;
  14937. if (methodDef->mIsLocalMethod) // See DoMethodDeclaration for an explaination of dependentGenericStartIdx
  14938. dependentGenericStartIdx = (int)mCurMethodState->GetRootMethodState()->mMethodInstance->GetNumGenericArguments();
  14939. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  14940. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, methodInstance->mMethodInstanceGroup->mOwner);
  14941. SetAndRestoreValue<BfFilePosition> prevFilePos(mCurFilePosition);
  14942. SetAndRestoreValue<bool> prevHadBuildError(mHadBuildError, false);
  14943. SetAndRestoreValue<bool> prevHadWarning(mHadBuildWarning, false);
  14944. SetAndRestoreValue<bool> prevIgnoreWarnings(mIgnoreWarnings, false);
  14945. if ((methodInstance->mIsReified) &&
  14946. ((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorNoBody)))
  14947. {
  14948. mCurTypeInstance->mHasBeenInstantiated = true;
  14949. }
  14950. // Warnings are shown in the capture phase
  14951. if ((methodDef->mIsLocalMethod) || (mCurTypeInstance->IsClosure()))
  14952. mIgnoreWarnings = true;
  14953. if ((methodDeclaration == NULL) && (mCurMethodState == NULL))
  14954. UseDefaultSrcPos();
  14955. // We may not actually be populated in relatively rare autocompelte cases
  14956. PopulateType(mCurTypeInstance, BfPopulateType_DataAndMethods);
  14957. mBfIRBuilder->PopulateType(mCurTypeInstance, BfIRPopulateType_Full);
  14958. BfAstNode* nameNode = NULL;
  14959. if (methodDeclaration != NULL)
  14960. {
  14961. nameNode = methodDeclaration->mNameNode;
  14962. if (nameNode == NULL)
  14963. {
  14964. if (auto ctorDeclaration = BfNodeDynCast<BfConstructorDeclaration>(methodDeclaration))
  14965. nameNode = ctorDeclaration->mThisToken;
  14966. }
  14967. }
  14968. if ((mCompiler->mResolvePassData != NULL) && (methodDeclaration != NULL) && (nameNode != NULL) &&
  14969. (mCompiler->mResolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Method) && (methodDef->mIdx >= 0))
  14970. {
  14971. if (methodInstance->GetExplicitInterface() == NULL)
  14972. mCompiler->mResolvePassData->HandleMethodReference(nameNode, typeDef, methodDef);
  14973. else
  14974. {
  14975. for (auto& ifaceEntry : mCurTypeInstance->mInterfaces)
  14976. {
  14977. auto ifaceInst = ifaceEntry.mInterfaceType;
  14978. int startIdx = ifaceEntry.mStartInterfaceTableIdx;
  14979. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  14980. if (methodInstance->GetExplicitInterface() != ifaceInst)
  14981. continue;
  14982. ifaceInst->mTypeDef->PopulateMemberSets();
  14983. BfMethodDef* nextMethod = NULL;
  14984. BfMemberSetEntry* entry = NULL;
  14985. if (ifaceInst->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  14986. nextMethod = (BfMethodDef*)entry->mMemberDef;
  14987. while (nextMethod != NULL)
  14988. {
  14989. auto checkMethod = nextMethod;
  14990. nextMethod = nextMethod->mNextWithSameName;
  14991. BfMethodInstance* implMethodInst = mCurTypeInstance->mInterfaceMethodTable[startIdx + checkMethod->mIdx].mMethodRef;
  14992. if (implMethodInst == methodInstance)
  14993. {
  14994. auto ifaceMethodDef = ifaceInst->mTypeDef->mMethods[checkMethod->mIdx];
  14995. mCompiler->mResolvePassData->HandleMethodReference(nameNode, ifaceInst->mTypeDef, ifaceMethodDef);
  14996. }
  14997. }
  14998. }
  14999. }
  15000. if (methodDef->mIsOverride)
  15001. {
  15002. for (int virtIdx = 0; virtIdx < (int)mCurTypeInstance->mVirtualMethodTable.size(); virtIdx++)
  15003. {
  15004. auto& ventry = mCurTypeInstance->mVirtualMethodTable[virtIdx];
  15005. if (ventry.mDeclaringMethod.mMethodNum == -1)
  15006. continue;
  15007. BfMethodInstance* virtMethod = ventry.mImplementingMethod;
  15008. if (virtMethod != NULL)
  15009. {
  15010. if (virtMethod == methodInstance)
  15011. {
  15012. // Is matching method
  15013. if (virtIdx < (int)mCurTypeInstance->mBaseType->mVirtualMethodTable.size())
  15014. {
  15015. auto baseType = mCurTypeInstance->mBaseType;
  15016. if (baseType != NULL)
  15017. {
  15018. while ((baseType->mBaseType != NULL) && (virtIdx < baseType->mBaseType->mVirtualMethodTableSize))
  15019. baseType = baseType->mBaseType;
  15020. BfMethodInstance* baseVirtMethod = baseType->mVirtualMethodTable[virtIdx].mImplementingMethod;
  15021. mCompiler->mResolvePassData->HandleMethodReference(nameNode, baseType->mTypeDef, baseVirtMethod->mMethodDef);
  15022. }
  15023. }
  15024. break;
  15025. }
  15026. }
  15027. }
  15028. }
  15029. }
  15030. BfLogSysM("ProcessMethod %p Unspecialized: %d Module: %p IRFunction: %d Reified: %d\n", methodInstance, mCurTypeInstance->IsUnspecializedType(), this, methodInstance->mIRFunction.mId, methodInstance->mIsReified);
  15031. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  15032. {
  15033. if (mBfIRBuilder->mIgnoreWrites)
  15034. return;
  15035. BfLogSysM("DllImportGlobalVar processing %p\n", methodInstance);
  15036. if (!methodInstance->mIRFunction)
  15037. {
  15038. BfIRValue dllImportGlobalVar = CreateDllImportGlobalVar(methodInstance, true);
  15039. methodInstance->mIRFunction = mBfIRBuilder->GetFakeVal();
  15040. mFuncReferences[mCurMethodInstance] = dllImportGlobalVar;
  15041. }
  15042. if (HasCompiledOutput())
  15043. {
  15044. BfDllImportEntry dllImportEntry;
  15045. dllImportEntry.mFuncVar = methodInstance->mIRFunction;
  15046. dllImportEntry.mMethodInstance = mCurMethodInstance;
  15047. mDllImportEntries.push_back(dllImportEntry);
  15048. }
  15049. return;
  15050. }
  15051. StringT<128> mangledName;
  15052. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  15053. if (!methodInstance->mIRFunction)
  15054. {
  15055. bool isIntrinsic = false;
  15056. SetupIRFunction(methodInstance, mangledName, false, &isIntrinsic);
  15057. }
  15058. if (methodInstance->mIsIntrinsic)
  15059. return;
  15060. if (mCurTypeInstance->IsFunction())
  15061. return;
  15062. auto prevActiveFunction = mBfIRBuilder->GetActiveFunction();
  15063. mBfIRBuilder->SetActiveFunction(mCurMethodInstance->mIRFunction);
  15064. if (methodDef->mBody != NULL)
  15065. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  15066. else if (methodDeclaration != NULL)
  15067. UpdateSrcPos(methodDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  15068. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  15069. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  15070. if (mCurMethodState == NULL) // Only do initial classify for the 'outer' method state, not any local methods or lambdas
  15071. {
  15072. if ((mCompiler->mIsResolveOnly) && (methodDef->mBody != NULL) && (!mCurTypeInstance->IsBoxed()) &&
  15073. (methodDef->mBody->IsFromParser(mCompiler->mResolvePassData->mParser)) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  15074. {
  15075. mCompiler->mResolvePassData->mSourceClassifier->VisitChildNoRef(methodDef->mBody);
  15076. }
  15077. }
  15078. BfHotDataReferenceBuilder hotDataReferenceBuilder;
  15079. BfMethodState methodState;
  15080. if (mCurMethodState != NULL)
  15081. methodState.mClosureState = mCurMethodState->mClosureState;
  15082. if ((mCompiler->mOptions.mAllowHotSwapping) && (methodInstance->mIsReified) && (!methodInstance->mIsUnspecialized) && (!isInlineDup))
  15083. {
  15084. //BF_ASSERT(methodInstance->mHotMethod != NULL);
  15085. if (methodInstance->mHotMethod == NULL)
  15086. CheckHotMethod(methodInstance, mangledName);
  15087. methodState.mHotDataReferenceBuilder = &hotDataReferenceBuilder;
  15088. }
  15089. methodState.mPrevMethodState = mCurMethodState;
  15090. methodState.mMethodInstance = methodInstance;
  15091. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  15092. if (methodInstance->GetCustomAttributes() != NULL)
  15093. {
  15094. int typeOptionsIdx = GenerateTypeOptions(methodInstance->GetCustomAttributes(), mCurTypeInstance, false);
  15095. if (typeOptionsIdx != -1)
  15096. methodState.mMethodTypeOptions = mSystem->GetTypeOptions(typeOptionsIdx);
  15097. }
  15098. BfTypeState typeState(mCurTypeInstance);
  15099. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  15100. bool isGenericVariation = (methodInstance->mIsUnspecializedVariation) || (mCurTypeInstance->IsUnspecializedTypeVariation());
  15101. BfMethodInstance* unspecializedMethodInstance = NULL;
  15102. if ((prevMethodState.mPrevVal != NULL) &&
  15103. ((methodState.mClosureState == NULL) || (methodState.mClosureState->mActiveDeferredLocalMethod == NULL)))
  15104. {
  15105. // This is 'inner' (probably a closure) - use binding from outer function
  15106. methodState.mGenericTypeBindings = prevMethodState.mPrevVal->mGenericTypeBindings;
  15107. }
  15108. else if ((methodInstance->mIsUnspecialized) ||
  15109. ((mCurTypeInstance->IsUnspecializedType()) && (!isGenericVariation)))
  15110. {
  15111. methodState.mGenericTypeBindings = &methodInstance->GetMethodInfoEx()->mGenericTypeBindings;
  15112. }
  15113. else if ((((methodInstance->mMethodInfoEx != NULL) && ((int)methodInstance->mMethodInfoEx->mMethodGenericArguments.size() > dependentGenericStartIdx)) ||
  15114. ((mCurTypeInstance->IsGenericTypeInstance()) && (!isGenericVariation) && (!methodInstance->mMethodDef->mIsLocalMethod))))
  15115. {
  15116. unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance, !methodInstance->mMethodDef->mIsLocalMethod);
  15117. BF_ASSERT(unspecializedMethodInstance != methodInstance);
  15118. if (!unspecializedMethodInstance->mHasBeenProcessed)
  15119. {
  15120. // Make sure the unspecialized method is processed so we can take its bindings
  15121. // Clear mCurMethodState so we don't think we're in a local method
  15122. SetAndRestoreValue<BfMethodState*> prevMethodState_Unspec(mCurMethodState, prevMethodState.mPrevVal);
  15123. mContext->ProcessMethod(unspecializedMethodInstance);
  15124. }
  15125. methodState.mGenericTypeBindings = &unspecializedMethodInstance->GetMethodInfoEx()->mGenericTypeBindings;
  15126. }
  15127. if (methodDef->mMethodType == BfMethodType_Operator)
  15128. {
  15129. auto operatorDef = (BfOperatorDef*) methodDef;
  15130. BfAstNode* refNode = operatorDef->mOperatorDeclaration->mOperatorToken;
  15131. auto paramErrorRefNode = refNode;
  15132. if (operatorDef->mOperatorDeclaration->mOpenParen != NULL)
  15133. paramErrorRefNode = operatorDef->mOperatorDeclaration->mOpenParen;
  15134. if ((mCurMethodInstance->GetParamCount() > 0) && (mCurMethodInstance->GetParamTypeRef(0) != NULL))
  15135. paramErrorRefNode = mCurMethodInstance->GetParamTypeRef(0);
  15136. if (operatorDef->mOperatorDeclaration->mBinOp != BfBinaryOp_None)
  15137. {
  15138. if (methodDef->mParams.size() != 2)
  15139. {
  15140. Fail("Binary operators must declare two parameters", paramErrorRefNode);
  15141. }
  15142. else
  15143. {
  15144. if ((mCurMethodInstance->GetParamType(0) != mCurTypeInstance) && (!mCurMethodInstance->GetParamType(0)->IsSelf()) &&
  15145. (mCurMethodInstance->GetParamType(1) != mCurTypeInstance) && (!mCurMethodInstance->GetParamType(1)->IsSelf()))
  15146. {
  15147. Fail("At least one of the parameters of a binary operator must be the containing type", paramErrorRefNode);
  15148. }
  15149. }
  15150. BfType* wantType = NULL;
  15151. if (operatorDef->mOperatorDeclaration->mBinOp == BfBinaryOp_Compare)
  15152. {
  15153. wantType = GetPrimitiveType(BfTypeCode_IntPtr);
  15154. }
  15155. if ((wantType != NULL) && (methodInstance->mReturnType != wantType))
  15156. Fail(StrFormat("The return type for the '%s' operator must be '%s'", BfGetOpName(operatorDef->mOperatorDeclaration->mBinOp),
  15157. TypeToString(wantType).c_str()), operatorDef->mOperatorDeclaration->mReturnType);
  15158. }
  15159. else if (operatorDef->mOperatorDeclaration->mUnaryOp != BfUnaryOp_None)
  15160. {
  15161. if (methodDef->mIsStatic)
  15162. {
  15163. if (methodDef->mParams.size() != 1)
  15164. {
  15165. Fail("Unary operators must declare one parameter", paramErrorRefNode);
  15166. }
  15167. else if ((mCurMethodInstance->GetParamType(0) != mCurTypeInstance) && (!mCurMethodInstance->GetParamType(0)->IsSelf()))
  15168. {
  15169. Fail("The parameter of a unary operator must be the containing type", paramErrorRefNode);
  15170. }
  15171. if (((operatorDef->mOperatorDeclaration->mUnaryOp == BfUnaryOp_Increment) ||
  15172. (operatorDef->mOperatorDeclaration->mUnaryOp == BfUnaryOp_Decrement)) &&
  15173. (!TypeIsSubTypeOf(mCurMethodInstance->mReturnType->ToTypeInstance(), mCurTypeInstance)))
  15174. {
  15175. Fail("The return type for the '++' or '--' operator must match the parameter type or be derived from the parameter type", operatorDef->mOperatorDeclaration->mReturnType);
  15176. }
  15177. }
  15178. else
  15179. {
  15180. if (methodDef->mParams.size() != 0)
  15181. {
  15182. Fail("Non-static unary operators not declare any parameters", paramErrorRefNode);
  15183. }
  15184. if (!mCurMethodInstance->mReturnType->IsVoid())
  15185. {
  15186. Fail("The return type for non-static operator must be 'void'", operatorDef->mOperatorDeclaration->mReturnType);
  15187. }
  15188. }
  15189. }
  15190. else if (operatorDef->mOperatorDeclaration->mAssignOp != BfAssignmentOp_None)
  15191. {
  15192. if (methodDef->mParams.size() != 1)
  15193. {
  15194. Fail("Assignment operators must declare one parameter", paramErrorRefNode);
  15195. }
  15196. if (!mCurMethodInstance->mReturnType->IsVoid())
  15197. {
  15198. Fail("The return type for assignment operator must be 'void'", operatorDef->mOperatorDeclaration->mReturnType);
  15199. }
  15200. }
  15201. else // Conversion
  15202. {
  15203. if (!operatorDef->mOperatorDeclaration->mIsConvOperator)
  15204. {
  15205. if (operatorDef->mOperatorDeclaration->mReturnType != NULL)
  15206. Fail("Conversion operators must declare their target type after the 'operator' token, not before", operatorDef->mOperatorDeclaration->mReturnType);
  15207. }
  15208. if (methodDef->mParams.size() != 1)
  15209. {
  15210. auto refNode = paramErrorRefNode;
  15211. if (!operatorDef->mOperatorDeclaration->mCommas.empty())
  15212. refNode = operatorDef->mOperatorDeclaration->mCommas[0];
  15213. Fail("Conversion operators must declare one parameter", refNode);
  15214. }
  15215. else
  15216. {
  15217. if ((mCurMethodInstance->GetParamType(0) != mCurTypeInstance) && (!mCurMethodInstance->GetParamType(0)->IsSelf()) &&
  15218. (mCurMethodInstance->mReturnType != mCurTypeInstance) && (!mCurMethodInstance->mReturnType->IsSelf()))
  15219. Fail("User-defined conversion must convert to or from the enclosing type", paramErrorRefNode);
  15220. if (mCurMethodInstance->GetParamType(0) == mCurMethodInstance->mReturnType)
  15221. Fail("User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type", operatorDef->mOperatorDeclaration->mReturnType);
  15222. // On type lookup error we default to 'object', so don't do the 'base class' error if that may have
  15223. // happened here
  15224. if ((!mHadBuildError) || ((mCurMethodInstance->mReturnType != mContext->mBfObjectType) && (mCurMethodInstance->GetParamType(0) != mContext->mBfObjectType)))
  15225. {
  15226. auto isToBase = TypeIsSubTypeOf(mCurTypeInstance->mBaseType, mCurMethodInstance->mReturnType->ToTypeInstance());
  15227. bool isFromBase = TypeIsSubTypeOf(mCurTypeInstance->mBaseType, mCurMethodInstance->GetParamType(0)->ToTypeInstance());
  15228. if ((mCurTypeInstance->IsObject()) && (isToBase || isFromBase))
  15229. Fail("User-defined conversions to or from a base class are not allowed", paramErrorRefNode);
  15230. else if ((mCurTypeInstance->IsStruct()) && (isToBase))
  15231. Fail("User-defined conversions to a base struct are not allowed", paramErrorRefNode);
  15232. }
  15233. }
  15234. }
  15235. }
  15236. bool wantsDIData = (mBfIRBuilder->DbgHasInfo()) && (!methodDef->IsEmptyPartial()) && (!mCurMethodInstance->mIsUnspecialized) && (mHasFullDebugInfo);
  15237. if (methodDef->mMethodType == BfMethodType_Mixin)
  15238. wantsDIData = false;
  15239. if ((mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType != BfMethodType_Ctor))
  15240. wantsDIData = false;
  15241. bool wantsDIVariables = wantsDIData;
  15242. if (methodDef->mIsExtern)
  15243. wantsDIVariables = false;
  15244. SizedArray<BfIRMDNode, 8> diParams;
  15245. diParams.push_back(mBfIRBuilder->DbgGetType(methodInstance->mReturnType));
  15246. bool isThisStruct = mCurTypeInstance->IsStruct() && !mCurTypeInstance->IsTypedPrimitive();
  15247. BfType* thisType = NULL;
  15248. if (!methodDef->mIsStatic)
  15249. {
  15250. if ((methodState.mClosureState != NULL) && (methodState.mClosureState->mClosureType != NULL))
  15251. thisType = methodState.mClosureState->mClosureType;
  15252. else
  15253. thisType = mCurTypeInstance;
  15254. }
  15255. PopulateType(methodInstance->mReturnType, BfPopulateType_Data);
  15256. ProcessMethod_SetupParams(methodInstance, thisType, wantsDIData, &diParams);
  15257. //////////////////////////////////////////////////////////////////////////
  15258. //
  15259. {
  15260. if (methodDeclaration != NULL)
  15261. UpdateSrcPos(methodDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  15262. else if (methodDef->mBody != NULL)
  15263. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  15264. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  15265. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  15266. }
  15267. BfIRMDNode diFunction;
  15268. if (wantsDIData)
  15269. {
  15270. BP_ZONE("BfModule::BfMethodDeclaration.DISetup");
  15271. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParams);
  15272. int defLine = mCurFilePosition.mCurLine;
  15273. if (mDICompileUnit)
  15274. {
  15275. int flags = 0;
  15276. BfIRMDNode funcScope = mBfIRBuilder->DbgGetTypeInst(mCurTypeInstance);
  15277. if (methodDef->mProtection == BfProtection_Public)
  15278. flags = llvm::DINode::FlagPublic;
  15279. else if (methodDef->mProtection == BfProtection_Protected)
  15280. flags = llvm::DINode::FlagProtected;
  15281. else
  15282. flags = llvm::DINode::FlagPrivate;
  15283. if (methodDef->mIsOverride)
  15284. {
  15285. //flags |= llvm::DINode::FlagVirtual;
  15286. }
  15287. else if (methodDef->mIsVirtual)
  15288. flags |= llvm::DINode::FlagIntroducedVirtual;
  15289. if ((methodDef->mIsStatic) || (methodDef->mMethodType == BfMethodType_Mixin))
  15290. flags |= llvm::DINode::FlagStaticMember;
  15291. else
  15292. {
  15293. if ((mCurTypeInstance->IsValuelessType()) || (mCurTypeInstance->IsSplattable()))
  15294. flags |= llvm::DINode::FlagStaticMember;
  15295. }
  15296. flags |= llvm::DINode::FlagPrototyped;
  15297. if (methodDef->mMethodType == BfMethodType_Ctor)
  15298. {
  15299. flags |= llvm::DINode::FlagArtificial;
  15300. }
  15301. auto llvmFunction = methodInstance->mIRFunction;
  15302. SizedArray<BfIRMDNode, 1> genericArgs;
  15303. SizedArray<BfIRValue, 1> genericConstValueArgs;
  15304. String methodName;
  15305. if (methodInstance->GetForeignType() != NULL)
  15306. {
  15307. methodName += TypeToString(methodInstance->GetForeignType());
  15308. methodName += ".";
  15309. }
  15310. if (methodInstance->GetExplicitInterface() != NULL)
  15311. {
  15312. methodName += TypeToString(methodInstance->GetExplicitInterface());
  15313. methodName += ".";
  15314. }
  15315. methodName += methodDef->mName;
  15316. if (methodInstance->GetNumGenericArguments() != 0)
  15317. {
  15318. for (auto genericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  15319. {
  15320. if (genericArg->IsConstExprValue())
  15321. {
  15322. BfConstExprValueType* constExprValueType = (BfConstExprValueType*)genericArg;
  15323. while (genericConstValueArgs.size() < genericArgs.size())
  15324. genericConstValueArgs.push_back(BfIRValue());
  15325. genericConstValueArgs.push_back(mBfIRBuilder->CreateConst(BfTypeCode_UInt64, constExprValueType->mValue.mUInt64));
  15326. genericArgs.push_back(mBfIRBuilder->DbgGetType(GetPrimitiveType(BfTypeCode_Int64)));
  15327. }
  15328. else
  15329. genericArgs.push_back(mBfIRBuilder->DbgGetType(genericArg));
  15330. }
  15331. methodName += "<";
  15332. for (int i = 0; i < (int)methodInstance->mMethodInfoEx->mMethodGenericArguments.size(); i++)
  15333. {
  15334. if (i > 0)
  15335. methodName += ", ";
  15336. BfType* type = methodInstance->mMethodInfoEx->mMethodGenericArguments[i];
  15337. methodName += TypeToString(type);
  15338. }
  15339. methodName += ">";
  15340. }
  15341. if ((methodName.empty()) && (methodDeclaration != NULL))
  15342. {
  15343. if (auto operatorDecl = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  15344. {
  15345. methodName += "operator";
  15346. if (operatorDecl->mIsConvOperator)
  15347. {
  15348. methodName += " ";
  15349. methodName += TypeToString(methodInstance->mReturnType);
  15350. }
  15351. else if (operatorDecl->mOpTypeToken != NULL)
  15352. methodName += operatorDecl->mOpTypeToken->ToString();
  15353. }
  15354. }
  15355. if (methodDef->mCheckedKind == BfCheckedKind_Checked)
  15356. methodName += "$CHK";
  15357. else if (methodDef->mCheckedKind == BfCheckedKind_Unchecked)
  15358. methodName += "$UCHK";
  15359. methodState.mDIFile = mCurFilePosition.mFileInstance->mDIFile;
  15360. // diFunction = mBfIRBuilder->DbgCreateMethod(funcScope, methodName, mangledName, methodState.mDIFile,
  15361. // defLine + 1, diFuncType, false, true,
  15362. // (methodInstance->mVirtualTableIdx != -1) ? llvm::dwarf::DW_VIRTUALITY_virtual : llvm::dwarf::DW_VIRTUALITY_none,
  15363. // (methodInstance->mVirtualTableIdx != -1) ? methodInstance->DbgGetVirtualMethodNum() : 0,
  15364. // nullptr, flags, IsOptimized(), llvmFunction, genericArgs, genericConstValueArgs);
  15365. diFunction = mBfIRBuilder->DbgCreateMethod(funcScope, methodName, mangledName, methodState.mDIFile,
  15366. defLine + 1, diFuncType, false, true,
  15367. llvm::dwarf::DW_VIRTUALITY_none,
  15368. 0,
  15369. BfIRMDNode(), flags, IsOptimized(), llvmFunction, genericArgs, genericConstValueArgs);
  15370. }
  15371. }
  15372. //////////////////////////////////////////////////////////////////////////
  15373. // Head and Init get rolled into Entry afterwards.
  15374. methodState.mIRFunction = methodInstance->mIRFunction;
  15375. methodState.mIRHeadBlock = mBfIRBuilder->CreateBlock("head", true);
  15376. methodState.mIRInitBlock = mBfIRBuilder->CreateBlock("init", true);
  15377. methodState.mIREntryBlock = mBfIRBuilder->CreateBlock("entry", true);
  15378. methodState.mCurScope->mDIScope = diFunction;
  15379. auto llvmEntryBlock = methodState.mIREntryBlock;
  15380. mBfIRBuilder->SetInsertPoint(llvmEntryBlock);
  15381. if (methodDef->mName == "__MALFORMED")
  15382. {
  15383. auto newBlock = mBfIRBuilder->CreateBlock("malformed", true);
  15384. mBfIRBuilder->SetInsertPoint(newBlock);
  15385. }
  15386. if (methodDef->mBody != NULL)
  15387. {
  15388. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  15389. }
  15390. else if ((mHasFullDebugInfo) && (diFunction) && (typeDef->mTypeDeclaration != NULL))
  15391. {
  15392. // We want to be able to step into delegate invokes -- we actually step over them
  15393. if (methodDef->mName != "Invoke")
  15394. {
  15395. UpdateSrcPos(typeDef->mTypeDeclaration);
  15396. mBfIRBuilder->DbgCreateAnnotation(diFunction, "StepOver", GetConstValue32(1));
  15397. }
  15398. }
  15399. // Clear out DebugLoc - to mark the ".addr" code as part of prologue
  15400. mBfIRBuilder->ClearDebugLocation();
  15401. bool isTypedPrimitiveFunc = mCurTypeInstance->IsTypedPrimitive() && (methodDef->mMethodType != BfMethodType_Ctor);
  15402. int irParamCount = methodInstance->GetIRFunctionParamCount(this);
  15403. if (methodInstance->GetImportKind() != BfImportKind_Import_Dynamic)
  15404. {
  15405. int localIdx = 0;
  15406. int argIdx = 0;
  15407. Array<BfIRValue> splatAddrValues;
  15408. for ( ; argIdx < irParamCount; localIdx++)
  15409. {
  15410. bool isThis = ((localIdx == 0) && (!mCurMethodInstance->mMethodDef->mIsStatic));
  15411. if ((isThis) && (thisType->IsValuelessType()))
  15412. isThis = false;
  15413. if (methodInstance->GetStructRetIdx() == argIdx)
  15414. {
  15415. argIdx++;
  15416. if (argIdx == irParamCount)
  15417. break;
  15418. }
  15419. BfLocalVariable* paramVar = NULL;
  15420. while (true)
  15421. {
  15422. BF_ASSERT(localIdx < methodState.mLocals.size());
  15423. paramVar = methodState.mLocals[localIdx];
  15424. if ((paramVar->mCompositeCount == -1) &&
  15425. ((!paramVar->mResolvedType->IsValuelessType()) || (paramVar->mResolvedType->IsMethodRef())))
  15426. break;
  15427. localIdx++;
  15428. }
  15429. if ((isThis) && (mCurTypeInstance->IsValueType()) && (methodDef->mMethodType != BfMethodType_Ctor) && (!methodDef->HasNoThisSplat()))
  15430. {
  15431. paramVar->mIsReadOnly = true;
  15432. }
  15433. bool wantsAddr = (wantsDIVariables) || (!paramVar->mIsReadOnly) || (paramVar->mResolvedType->GetLoweredType(BfTypeUsage_Parameter));
  15434. if (paramVar->mResolvedType->IsMethodRef())
  15435. wantsAddr = false;
  15436. // if ((methodDef->mHasAppend) && (argIdx == 1))
  15437. // {
  15438. // BF_ASSERT(paramVar->mName == "appendIdx");
  15439. // wantsAddr = true;
  15440. // }
  15441. if (paramVar->mIsSplat)
  15442. {
  15443. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  15444. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  15445. BfTypeUtils::SplatIterate([&](BfType* checkType)
  15446. {
  15447. BfIRType splatIRType;
  15448. if (checkType->IsComposite())
  15449. splatIRType = mBfIRBuilder->MapType(CreatePointerType(checkType));
  15450. else
  15451. splatIRType = mBfIRBuilder->MapType(checkType);
  15452. auto allocaInst = mBfIRBuilder->CreateAlloca(splatIRType);
  15453. mBfIRBuilder->SetAllocaAlignment(allocaInst, checkType->mAlign);
  15454. if (!paramVar->mAddr)
  15455. paramVar->mAddr = allocaInst;
  15456. if (WantsLifetimes())
  15457. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  15458. splatAddrValues.push_back(allocaInst);
  15459. }, paramVar->mResolvedType);
  15460. mBfIRBuilder->SetInsertPoint(prevInsert);
  15461. }
  15462. else if (isThis)
  15463. {
  15464. if (wantsAddr)
  15465. {
  15466. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  15467. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  15468. BfIRType thisAddrType = mBfIRBuilder->MapType(thisType);
  15469. if (paramVar->mIsSplat)
  15470. {
  15471. //
  15472. }
  15473. else
  15474. {
  15475. bool wantPtr = (thisType->IsComposite()) && (!paramVar->mIsLowered);
  15476. if ((thisType->IsTypedPrimitive()) && (methodDef->HasNoThisSplat()))
  15477. wantPtr = true;
  15478. if (wantPtr)
  15479. {
  15480. thisAddrType = mBfIRBuilder->MapTypeInstPtr(thisType->ToTypeInstance());
  15481. }
  15482. auto allocaInst = mBfIRBuilder->CreateAlloca(thisAddrType);
  15483. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  15484. mBfIRBuilder->SetAllocaAlignment(allocaInst, mSystem->mPtrSize);
  15485. paramVar->mAddr = allocaInst;
  15486. if (WantsLifetimes())
  15487. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  15488. }
  15489. mBfIRBuilder->SetInsertPoint(prevInsert);
  15490. }
  15491. }
  15492. else if ((!isThis) && ((paramVar->mIsStruct) || (paramVar->mResolvedType->IsRef())))
  15493. {
  15494. // Address doesn't change so we don't have to alloca it
  15495. BfIRType allocType;
  15496. int alignSize = mSystem->mPtrSize;
  15497. if (paramVar->mResolvedType->IsRef())
  15498. {
  15499. allocType = mBfIRBuilder->MapType(paramVar->mResolvedType);
  15500. }
  15501. else if ((paramVar->mIsSplat) || (paramVar->mIsLowered))
  15502. {
  15503. allocType = mBfIRBuilder->MapType(paramVar->mResolvedType);
  15504. alignSize = paramVar->mResolvedType->mAlign;
  15505. }
  15506. else
  15507. {
  15508. paramVar->mHasLocalStructBacking = true;
  15509. auto typeInst = paramVar->mResolvedType->ToTypeInstance();
  15510. if (typeInst != NULL)
  15511. allocType = mBfIRBuilder->MapTypeInstPtr(paramVar->mResolvedType->ToTypeInstance());
  15512. else
  15513. allocType = mBfIRBuilder->MapType(CreatePointerType(paramVar->mResolvedType));
  15514. }
  15515. if (wantsAddr)
  15516. {
  15517. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  15518. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  15519. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  15520. auto allocaInst = mBfIRBuilder->CreateAlloca(allocType);
  15521. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  15522. mBfIRBuilder->SetAllocaAlignment(allocaInst, alignSize);
  15523. paramVar->mAddr = allocaInst;
  15524. mBfIRBuilder->SetInsertPoint(prevInsert);
  15525. if (WantsLifetimes())
  15526. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  15527. }
  15528. }
  15529. else if (wantsAddr)
  15530. {
  15531. auto allocaInst = CreateAlloca(paramVar->mResolvedType);
  15532. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  15533. paramVar->mAddr = allocaInst;
  15534. }
  15535. if (paramVar->mIsSplat)
  15536. {
  15537. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  15538. }
  15539. else if (paramVar->mIsLowered)
  15540. {
  15541. BfTypeCode loweredTypeCode = BfTypeCode_None;
  15542. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  15543. paramVar->mResolvedType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2);
  15544. argIdx++;
  15545. if (loweredTypeCode2 != BfTypeCode_None)
  15546. argIdx++;
  15547. }
  15548. else
  15549. {
  15550. argIdx++;
  15551. }
  15552. }
  15553. if (methodDef->mBody != NULL)
  15554. UpdateSrcPos(methodDef->mBody);
  15555. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  15556. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration);
  15557. localIdx = 0;
  15558. argIdx = 0;
  15559. int splatAddrIdx = 0;
  15560. while (localIdx < (int)methodState.mLocals.size())
  15561. {
  15562. if (argIdx == methodInstance->GetStructRetIdx())
  15563. argIdx++;
  15564. int curLocalIdx = localIdx++;
  15565. BfLocalVariable* paramVar = methodState.mLocals[curLocalIdx];
  15566. if (!paramVar->IsParam())
  15567. continue;
  15568. if (paramVar->mCompositeCount != -1)
  15569. continue;
  15570. bool isThis = ((curLocalIdx == 0) && (!mCurMethodInstance->mMethodDef->mIsStatic));
  15571. if ((isThis) && (thisType->IsValuelessType()))
  15572. isThis = false;
  15573. if (paramVar->mValue.IsArg())
  15574. BF_ASSERT(paramVar->mValue.mId == argIdx);
  15575. BfIRMDNode diVariable;
  15576. if (wantsDIData)
  15577. {
  15578. String paramName = paramVar->mName;
  15579. BfIRMDNode diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  15580. if (isThis)
  15581. {
  15582. if ((mCurMethodState->mClosureState != NULL) && (mCurMethodState->mClosureState->mClosureType != NULL))
  15583. paramName = "__closure";
  15584. if ((paramVar->mResolvedType->IsValueType()) && (!paramVar->mIsSplat) && (!paramVar->mIsLowered))
  15585. {
  15586. diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  15587. bool wantRef = paramVar->mResolvedType->IsComposite();
  15588. if ((paramVar->mResolvedType->IsTypedPrimitive()) && (methodDef->HasNoThisSplat()))
  15589. wantRef = true;
  15590. if (wantRef)
  15591. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  15592. }
  15593. else if (!paramVar->mResolvedType->IsValueType())
  15594. {
  15595. diType = mBfIRBuilder->DbgCreateArtificialType(diType);
  15596. }
  15597. }
  15598. else
  15599. {
  15600. if ((paramVar->mResolvedType->IsComposite()) && (!paramVar->mIsSplat) && (!paramVar->mIsLowered))
  15601. {
  15602. diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  15603. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  15604. diType = mBfIRBuilder->DbgCreateConstType(diType);
  15605. }
  15606. }
  15607. if (!paramVar->mIsSplat)
  15608. {
  15609. if (paramVar->mResolvedType->IsValuelessType())
  15610. {
  15611. diVariable = mBfIRBuilder->DbgCreateAutoVariable(diFunction,
  15612. paramName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  15613. }
  15614. else if (paramVar->mIsImplicitParam)
  15615. {
  15616. // Annotate this specially?
  15617. diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  15618. paramName, argIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, true, 0);
  15619. }
  15620. else
  15621. {
  15622. diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  15623. paramName, argIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, true, 0);
  15624. }
  15625. paramVar->mDbgVarInst = diVariable;
  15626. }
  15627. else if ((paramVar->mIsSplat) && (paramVar->mResolvedType->GetSplatCount() == 0))
  15628. {
  15629. // if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables))
  15630. // {
  15631. // // Only add this placeholder if we don't have any values
  15632. // auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  15633. // paramName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  15634. // mBfIRBuilder->DbgInsertValueIntrinsic(GetConstValue(0), diVariable);
  15635. // }
  15636. }
  15637. }
  15638. bool isTypedPrimCtor = mCurTypeInstance->IsTypedPrimitive() && (methodDef->mMethodType == BfMethodType_Ctor);
  15639. if ((!paramVar->mParamFailed) && (paramVar->mAddr))
  15640. {
  15641. // Write our argument value into the .addr
  15642. mBfIRBuilder->ClearDebugLocation();
  15643. if (paramVar->mIsSplat)
  15644. {
  15645. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  15646. //
  15647. }
  15648. else
  15649. {
  15650. bool handled = false;
  15651. if (paramVar->mIsLowered)
  15652. {
  15653. BfTypeCode loweredTypeCode = BfTypeCode_None;
  15654. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  15655. if (paramVar->mResolvedType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2))
  15656. {
  15657. // We have a lowered type coming in, so we have to cast the .addr before storing
  15658. auto primType = mBfIRBuilder->GetPrimitiveType(loweredTypeCode);
  15659. auto primPtrType = mBfIRBuilder->GetPointerTo(primType);
  15660. auto primPtrVal = mBfIRBuilder->CreateBitCast(paramVar->mAddr, primPtrType);
  15661. mBfIRBuilder->CreateStore(paramVar->mValue, primPtrVal);
  15662. if (loweredTypeCode2 != BfTypeCode_None)
  15663. {
  15664. auto primType2 = mBfIRBuilder->GetPrimitiveType(loweredTypeCode2);
  15665. auto primPtrType2 = mBfIRBuilder->GetPointerTo(primType2);
  15666. BfIRValue primPtrVal2;
  15667. if (mBfIRBuilder->GetSize(loweredTypeCode) < mBfIRBuilder->GetSize(loweredTypeCode2))
  15668. primPtrVal2 = mBfIRBuilder->CreateInBoundsGEP(mBfIRBuilder->CreateBitCast(primPtrVal, primPtrType2), 1);
  15669. else
  15670. primPtrVal2 = mBfIRBuilder->CreateBitCast(mBfIRBuilder->CreateInBoundsGEP(primPtrVal, 1), primPtrType2);
  15671. mBfIRBuilder->CreateStore(mBfIRBuilder->GetArgument(argIdx + 1), primPtrVal2);
  15672. }
  15673. // We don't want to allow directly using value
  15674. paramVar->mValue = BfIRValue();
  15675. handled = true;
  15676. }
  15677. else
  15678. {
  15679. BF_ASSERT("Expected lowered");
  15680. }
  15681. }
  15682. if (!handled)
  15683. mBfIRBuilder->CreateAlignedStore(paramVar->mValue, paramVar->mAddr, paramVar->mResolvedType->mAlign);
  15684. }
  15685. }
  15686. if (methodDef->mBody != NULL)
  15687. UpdateSrcPos(methodDef->mBody);
  15688. else if (methodDef->mDeclaringType->mTypeDeclaration != NULL)
  15689. UpdateSrcPos(methodDef->mDeclaringType->mTypeDeclaration);
  15690. else if (methodDeclaration == NULL)
  15691. UseDefaultSrcPos();
  15692. // Write our argument value into the .addr
  15693. if (paramVar->mIsSplat)
  15694. {
  15695. int splatComponentIdx = 0;
  15696. auto curArgIdx = argIdx;
  15697. auto _FinishSplats = [&] (BfType* checkType, const StringImpl& name)
  15698. {
  15699. BfIRValue splatAddrValue = splatAddrValues[splatAddrIdx++];
  15700. methodState.mSplatDecompAddrs.push_back(splatAddrValue);
  15701. auto storeInst = mBfIRBuilder->CreateAlignedStore(mBfIRBuilder->GetArgument(curArgIdx), splatAddrValue, checkType->mAlign);
  15702. mBfIRBuilder->ClearDebugLocation(storeInst);
  15703. if (wantsDIData)
  15704. {
  15705. BfIRMDNode diType;
  15706. if (checkType->IsComposite())
  15707. diType = mBfIRBuilder->DbgGetType(CreateRefType(checkType));
  15708. else
  15709. diType = mBfIRBuilder->DbgGetType(checkType);
  15710. auto diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  15711. name, curArgIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  15712. if (wantsDIVariables)
  15713. {
  15714. mBfIRBuilder->DbgInsertDeclare(splatAddrValue, diVariable);
  15715. }
  15716. }
  15717. curArgIdx++;
  15718. splatComponentIdx++;
  15719. };
  15720. std::function<void(BfType*, const StringImpl&)> _FinishSplatsIterate = [&](BfType* checkType, const StringImpl& name)
  15721. {
  15722. if (checkType->IsStruct())
  15723. {
  15724. auto checkTypeInstance = checkType->ToTypeInstance();
  15725. if (checkTypeInstance->mBaseType != NULL)
  15726. {
  15727. _FinishSplatsIterate(checkTypeInstance->mBaseType, name + "$b");
  15728. }
  15729. if (checkTypeInstance->mIsUnion)
  15730. {
  15731. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  15732. if (!unionInnerType->IsValuelessType())
  15733. {
  15734. _FinishSplatsIterate(unionInnerType, name + "$u");
  15735. }
  15736. if (checkTypeInstance->IsEnum())
  15737. {
  15738. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  15739. _FinishSplatsIterate(dscrType, name + "$d");
  15740. }
  15741. }
  15742. else
  15743. {
  15744. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  15745. {
  15746. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  15747. auto fieldDef = fieldInstance->GetFieldDef();
  15748. if (fieldInstance->mDataIdx >= 0)
  15749. {
  15750. _FinishSplatsIterate(fieldInstance->GetResolvedType(), name + "$m$" + fieldDef->mName);
  15751. }
  15752. }
  15753. }
  15754. }
  15755. else if (checkType->IsMethodRef())
  15756. {
  15757. auto methodRefType = (BfMethodRefType*)checkType;
  15758. BfMethodInstance* methodInstance = methodRefType->mMethodRef;
  15759. // int implicitParamCount = methodInstance->GetImplicitParamCount();
  15760. // for (int implicitParamIdx = methodInstance->HasThis() ? -1 : 0; implicitParamIdx < implicitParamCount; implicitParamIdx++)
  15761. // {
  15762. // auto paramType = methodInstance->GetParamType(implicitParamIdx);
  15763. // if (!paramType->IsValuelessType())
  15764. // _FinishSplats(paramType, name + "$m$" + methodInstance->GetParamName(implicitParamIdx));
  15765. // }
  15766. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  15767. {
  15768. int paramIdx = methodRefType->GetParamIdxFromDataIdx(dataIdx);
  15769. String paramName = methodInstance->GetParamName(paramIdx);
  15770. if (paramName == "this")
  15771. paramName = "__this";
  15772. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  15773. {
  15774. _FinishSplatsIterate(methodRefType->GetCaptureType(dataIdx), name + "$m$" + paramName);
  15775. }
  15776. else
  15777. {
  15778. _FinishSplats(methodRefType->GetCaptureType(dataIdx), name + "$m$" + paramName);
  15779. }
  15780. }
  15781. }
  15782. else if (!checkType->IsValuelessType())
  15783. {
  15784. _FinishSplats(checkType, name);
  15785. }
  15786. };
  15787. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  15788. if (!paramVar->mConstValue)
  15789. _FinishSplatsIterate(paramVar->mResolvedType, "$" + paramVar->mName);
  15790. }
  15791. BfIRValue declareCall;
  15792. if (diVariable)
  15793. {
  15794. if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables))
  15795. {
  15796. if (!paramVar->mAddr)
  15797. {
  15798. if ((!paramVar->mValue) || (paramVar->mValue.IsFake()))
  15799. {
  15800. if ((!paramVar->mIsThis) && (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU)) // DWARF chokes on this:
  15801. {
  15802. // We don't need to set the location for this
  15803. mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  15804. }
  15805. }
  15806. else
  15807. declareCall = mBfIRBuilder->DbgInsertDeclare(paramVar->mValue, diVariable);
  15808. }
  15809. else
  15810. {
  15811. declareCall = mBfIRBuilder->DbgInsertDeclare(paramVar->mAddr, diVariable);
  15812. }
  15813. }
  15814. }
  15815. if ((isThis) && (!paramVar->mIsSplat) && (paramVar->mAddr))
  15816. {
  15817. // We don't allow actually assignment to "this", so we just do a single load
  15818. // Keep in mind we don't use the ACTUAL mValue value because that's a register, but
  15819. // we need to store it in the stack frame for debugging purposes
  15820. auto loadedThis = mBfIRBuilder->CreateLoad(paramVar->mAddr/*, "this"*/);
  15821. mBfIRBuilder->ClearDebugLocation(loadedThis);
  15822. paramVar->mValue = loadedThis;
  15823. }
  15824. if ((wantsDIData) && (declareCall))
  15825. mBfIRBuilder->UpdateDebugLocation(declareCall);
  15826. if (paramVar->mIsSplat)
  15827. {
  15828. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  15829. }
  15830. else if (paramVar->mIsLowered)
  15831. {
  15832. argIdx++;
  15833. BfTypeCode loweredTypeCode = BfTypeCode_None;
  15834. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  15835. paramVar->mResolvedType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2);
  15836. if (loweredTypeCode2 != BfTypeCode_None)
  15837. argIdx++;
  15838. }
  15839. else if (!paramVar->mResolvedType->IsValuelessType())
  15840. {
  15841. argIdx++;
  15842. }
  15843. }
  15844. if (wantsDIData)
  15845. {
  15846. BF_ASSERT(splatAddrIdx == (int)splatAddrValues.size());
  15847. }
  15848. }
  15849. for (int varIdx = 0; varIdx < (int)mCurMethodState->mLocals.size(); varIdx++)
  15850. {
  15851. auto paramVar = mCurMethodState->mLocals[varIdx];
  15852. // 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
  15853. // splat member. If the "splat" is valueless then we do create a placeholder, but further up in this method
  15854. // if (paramVar->mIsSplat)
  15855. // {
  15856. // if (wantsDIVariables)
  15857. // {
  15858. // auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(diFunction, paramVar->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(paramVar->mResolvedType));
  15859. // mBfIRBuilder->DbgInsertValueIntrinsic(mBfIRBuilder->CreateConst(BfTypeCode_Int64, 0), diVariable);
  15860. // }
  15861. // }
  15862. if (paramVar->mResolvedType->IsValuelessType())
  15863. {
  15864. if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables) && (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU)) // DWARF chokes on this:
  15865. {
  15866. // Only add this placeholder if we don't have any values
  15867. auto diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  15868. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  15869. paramVar->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  15870. mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  15871. }
  15872. }
  15873. }
  15874. if (IsTargetingBeefBackend())
  15875. mCurMethodState->mCurScope->mValueScopeStart = mBfIRBuilder->CreateValueScopeStart();
  15876. if (methodState.mClosureState != NULL)
  15877. {
  15878. for (auto& constLocal : methodState.mClosureState->mConstLocals)
  15879. {
  15880. BfLocalVariable* localVar = new BfLocalVariable();
  15881. *localVar = constLocal;
  15882. AddLocalVariableDef(localVar, true);
  15883. }
  15884. }
  15885. bool wantsRemoveBody = false;
  15886. bool skipBody = false;
  15887. bool skipUpdateSrcPos = false;
  15888. bool skipEndChecks = false;
  15889. bool hasExternSpecifier = (methodDeclaration != NULL) && (methodDeclaration->mExternSpecifier != NULL) && (methodInstance->GetImportKind() != BfImportKind_Import_Dynamic);
  15890. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  15891. if ((methodDef != NULL) && (propertyDeclaration != NULL) && (propertyDeclaration->mExternSpecifier != NULL))
  15892. hasExternSpecifier = true;
  15893. // Allocate, clear, set classVData
  15894. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mIsStatic))
  15895. {
  15896. CreateStaticCtor();
  15897. }
  15898. else if ((mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType != BfMethodType_Ctor) && (methodDef->mName != BF_METHODNAME_DYNAMICCAST) && (methodDef->mName != BF_METHODNAME_DYNAMICCAST_INTERFACE))
  15899. {
  15900. skipBody = true;
  15901. skipEndChecks = true;
  15902. if (HasCompiledOutput())
  15903. {
  15904. // Clear out DebugLoc - to mark the ".addr" code as part of prologue
  15905. mBfIRBuilder->ClearDebugLocation();
  15906. BfBoxedType* boxedType = (BfBoxedType*) mCurTypeInstance;
  15907. BfTypeInstance* innerType = boxedType->mElementType->ToTypeInstance();
  15908. PopulateType(innerType, BfPopulateType_DataAndMethods);
  15909. mBfIRBuilder->PopulateType(mCurTypeInstance);
  15910. BfGetMethodInstanceFlags flags = BfGetMethodInstanceFlag_None;
  15911. if (methodInstance->mIsForeignMethodDef)
  15912. {
  15913. flags = BfGetMethodInstanceFlag_ForeignMethodDef;
  15914. }
  15915. BfTypeVector methodGenericArguments;
  15916. if (methodInstance->mMethodInfoEx != NULL)
  15917. methodGenericArguments = methodInstance->mMethodInfoEx->mMethodGenericArguments;
  15918. auto innerMethodInstance = GetMethodInstance(innerType, methodDef, methodGenericArguments, flags, methodInstance->GetForeignType());
  15919. if (innerMethodInstance.mMethodInstance->IsSkipCall())
  15920. {
  15921. if (!methodInstance->mReturnType->IsValuelessType())
  15922. {
  15923. auto retVal = GetDefaultValue(methodInstance->mReturnType);
  15924. CreateReturn(retVal);
  15925. }
  15926. else
  15927. mBfIRBuilder->CreateRetVoid();
  15928. }
  15929. else
  15930. {
  15931. BF_ASSERT(innerMethodInstance.mMethodInstance->mMethodDef == methodDef);
  15932. SizedArray<BfIRValue, 8> innerParams;
  15933. BfExprEvaluator exprEvaluator(this);
  15934. if (!innerType->IsValuelessType())
  15935. {
  15936. BfIRValue thisValue = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, 1);
  15937. BfTypedValue innerVal(thisValue, innerType, true);
  15938. if (boxedType->IsBoxedStructPtr())
  15939. {
  15940. innerVal = LoadValue(innerVal);
  15941. innerVal = BfTypedValue(innerVal.mValue, innerType, true);
  15942. }
  15943. exprEvaluator.PushThis(NULL, innerVal, innerMethodInstance.mMethodInstance, innerParams);
  15944. }
  15945. for (int i = 1; i < (int)mCurMethodState->mLocals.size(); i++)
  15946. {
  15947. BfLocalVariable* localVar = mCurMethodState->mLocals[i];
  15948. BfTypedValue localVal = exprEvaluator.LoadLocal(localVar, true);
  15949. exprEvaluator.PushArg(localVal, innerParams);
  15950. }
  15951. if (!innerMethodInstance.mFunc)
  15952. {
  15953. BF_ASSERT(innerType->IsUnspecializedType());
  15954. }
  15955. else if (methodInstance->GetStructRetIdx() != -1)
  15956. {
  15957. mBfIRBuilder->PopulateType(methodInstance->mReturnType);
  15958. auto returnType = BfTypedValue(mBfIRBuilder->GetArgument(methodInstance->GetStructRetIdx()), methodInstance->mReturnType, true);
  15959. exprEvaluator.mReceivingValue = &returnType;
  15960. auto retVal = exprEvaluator.CreateCall(innerMethodInstance.mMethodInstance, innerMethodInstance.mFunc, true, innerParams, NULL, true);
  15961. BF_ASSERT(exprEvaluator.mReceivingValue == NULL); // Ensure it was actually used
  15962. mBfIRBuilder->CreateRetVoid();
  15963. }
  15964. else
  15965. {
  15966. mBfIRBuilder->PopulateType(methodInstance->mReturnType);
  15967. auto retVal = exprEvaluator.CreateCall(innerMethodInstance.mMethodInstance, innerMethodInstance.mFunc, true, innerParams, NULL, true);
  15968. if (mCurMethodInstance->mReturnType->IsValueType())
  15969. retVal = LoadValue(retVal);
  15970. CreateReturn(retVal.mValue);
  15971. }
  15972. }
  15973. }
  15974. mCurMethodState->SetHadReturn(true);
  15975. mCurMethodState->mLeftBlockUncond = true;
  15976. }
  15977. else if (methodDef->mMethodType == BfMethodType_CtorClear)
  15978. {
  15979. SetIllegalSrcPos();
  15980. mBfIRBuilder->ClearDebugLocation();
  15981. PopulateType(mCurTypeInstance, BfPopulateType_Data);
  15982. auto thisVal = GetThis();
  15983. int prevSize = mContext->mBfObjectType->mInstSize;
  15984. int curSize = mCurTypeInstance->mInstSize;
  15985. if (curSize > prevSize)
  15986. {
  15987. auto int8PtrType = CreatePointerType(GetPrimitiveType(BfTypeCode_Int8));
  15988. auto int8PtrVal = mBfIRBuilder->CreateBitCast(thisVal.mValue, mBfIRBuilder->MapType(int8PtrType));
  15989. int8PtrVal = mBfIRBuilder->CreateInBoundsGEP(int8PtrVal, GetConstValue(prevSize));
  15990. mBfIRBuilder->CreateMemSet(int8PtrVal, GetConstValue8(0), GetConstValue(curSize - prevSize), GetConstValue(mCurTypeInstance->mInstAlign));
  15991. }
  15992. skipUpdateSrcPos = true;
  15993. }
  15994. else if (((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorNoBody)) && (!hasExternSpecifier))
  15995. {
  15996. EmitCtorBody(skipBody);
  15997. }
  15998. else if ((methodDef->mMethodType == BfMethodType_Dtor) && (!hasExternSpecifier))
  15999. {
  16000. EmitDtorBody();
  16001. skipBody = true;
  16002. }
  16003. if ((!mCurTypeInstance->IsBoxed()) && (methodDeclaration != NULL) && (methodDeclaration->mHadYield) && (methodDef->mBody != NULL))
  16004. {
  16005. EmitIteratorBlock(skipBody);
  16006. }
  16007. if (methodDef->mName == BF_METHODNAME_MARKMEMBERS)
  16008. {
  16009. // We need to be able to mark deleted objects
  16010. mCurMethodState->mIgnoreObjectAccessCheck = true;
  16011. }
  16012. auto customAttributes = methodInstance->GetCustomAttributes();
  16013. if (customAttributes != NULL)
  16014. {
  16015. if (customAttributes->Contains(mCompiler->mDisableObjectAccessChecksAttributeTypeDef))
  16016. mCurMethodState->mIgnoreObjectAccessCheck = true;
  16017. if (customAttributes->Contains(mCompiler->mDisableChecksAttributeTypeDef))
  16018. mCurMethodState->mDisableChecks = true;
  16019. }
  16020. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) && (!methodDef->mIsStatic) &&
  16021. ((methodInstance->mChainType == BfMethodChainType_ChainHead) || (methodInstance->mChainType == BfMethodChainType_None)))
  16022. {
  16023. // We chain even non-default ctors to the default ctors
  16024. auto defaultCtor = methodInstance;
  16025. if (defaultCtor->mChainType == BfMethodChainType_ChainHead)
  16026. CallChainedMethods(defaultCtor, false);
  16027. }
  16028. auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody);
  16029. if (methodDef->mBody == NULL)
  16030. {
  16031. if (methodDeclaration != NULL)
  16032. {
  16033. if (auto operatorDeclaration = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  16034. {
  16035. if (operatorDeclaration->mIsConvOperator)
  16036. wantsRemoveBody = true;
  16037. }
  16038. }
  16039. bool isDllImport = false;
  16040. if (methodInstance->GetImportKind() == BfImportKind_Import_Static)
  16041. {
  16042. for (auto customAttr : methodInstance->GetCustomAttributes()->mAttributes)
  16043. {
  16044. if (customAttr.mType->mTypeDef->mFullName.ToString() == "System.ImportAttribute")
  16045. {
  16046. if (customAttr.mCtorArgs.size() == 1)
  16047. {
  16048. auto fileNameArg = customAttr.mCtorArgs[0];
  16049. int strNum = 0;
  16050. auto constant = mCurTypeInstance->mConstHolder->GetConstant(fileNameArg);
  16051. if (constant != NULL)
  16052. {
  16053. if (constant->IsNull())
  16054. continue; // Invalid
  16055. strNum = constant->mInt32;
  16056. }
  16057. else
  16058. {
  16059. strNum = GetStringPoolIdx(fileNameArg, mCurTypeInstance->mConstHolder);
  16060. }
  16061. if (!mImportFileNames.Contains(strNum))
  16062. mImportFileNames.Add(strNum);
  16063. }
  16064. }
  16065. }
  16066. //mImportFileNames
  16067. }
  16068. else if (methodInstance->GetImportKind() == BfImportKind_Import_Dynamic)
  16069. {
  16070. CreateDllImportMethod();
  16071. }
  16072. else if (((mCurTypeInstance->mTypeDef->mIsDelegate) || (mCurTypeInstance->mTypeDef->mIsFunction)) &&
  16073. (methodDef->mName == "Invoke") && (methodDef->mMethodType == BfMethodType_Normal))
  16074. {
  16075. if (mCurTypeInstance->mTypeDef->mIsFunction)
  16076. {
  16077. // Emit nothing
  16078. }
  16079. else
  16080. {
  16081. CreateDelegateInvokeMethod();
  16082. mCurMethodState->SetHadReturn(true);
  16083. mCurMethodState->mLeftBlockUncond = true;
  16084. }
  16085. }
  16086. else if ((methodDef->mName == BF_METHODNAME_DYNAMICCAST) || (methodDef->mName == BF_METHODNAME_DYNAMICCAST_INTERFACE))
  16087. {
  16088. if (mCurTypeInstance->IsObject())
  16089. {
  16090. CreateDynamicCastMethod();
  16091. }
  16092. else
  16093. {
  16094. mBfIRBuilder->CreateRet(GetDefaultValue(methodInstance->mReturnType));
  16095. mCurMethodState->mHadReturn = true;
  16096. }
  16097. }
  16098. else if ((methodDef->mName == BF_METHODNAME_ENUM_HASFLAG) && (mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()))
  16099. {
  16100. BfIRValue ret;
  16101. if (mCurMethodState->mLocals[1]->mResolvedType != mCurTypeInstance)
  16102. {
  16103. // This can happen if we provide an invalid name
  16104. AssertErrorState();
  16105. ret = mBfIRBuilder->CreateRet(GetDefaultValue(GetPrimitiveType(BfTypeCode_Boolean)));
  16106. }
  16107. else
  16108. {
  16109. // Unfortunate DebugLoc shenanigans-
  16110. // 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,
  16111. // so we only set the loc on the CreateRet which gets inlined out
  16112. mBfIRBuilder->SaveDebugLocation();
  16113. mBfIRBuilder->ClearDebugLocation();
  16114. BfIRValue fromBool;
  16115. if (!mCurTypeInstance->IsTypedPrimitive())
  16116. {
  16117. fromBool = GetDefaultValue(methodInstance->mReturnType);
  16118. }
  16119. else
  16120. {
  16121. auto andResult = mBfIRBuilder->CreateAnd(mCurMethodState->mLocals[0]->mValue, mCurMethodState->mLocals[1]->mValue);
  16122. auto toBool = mBfIRBuilder->CreateCmpNE(andResult, GetDefaultValue(mCurMethodState->mLocals[0]->mResolvedType));
  16123. fromBool = mBfIRBuilder->CreateNumericCast(toBool, false, BfTypeCode_Boolean);
  16124. }
  16125. mBfIRBuilder->RestoreDebugLocation();
  16126. ret = mBfIRBuilder->CreateRet(fromBool);
  16127. //ExtendLocalLifetimes(0);
  16128. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  16129. }
  16130. mCurMethodState->SetHadReturn(true);
  16131. mCurMethodState->mLeftBlockUncond = true;
  16132. }
  16133. else if (((methodDef->mName == BF_METHODNAME_ENUM_GETUNDERLYINGREF) || (methodDef->mName == BF_METHODNAME_ENUM_GETUNDERLYING)) &&
  16134. (mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()))
  16135. {
  16136. BfIRValue ret;
  16137. // Unfortunate DebugLoc shenanigans-
  16138. // 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,
  16139. // so we only set the loc on the CreateRet which gets inlined out
  16140. mBfIRBuilder->SaveDebugLocation();
  16141. mBfIRBuilder->ClearDebugLocation();
  16142. BfIRValue fromBool;
  16143. mBfIRBuilder->RestoreDebugLocation();
  16144. ret = mBfIRBuilder->CreateRet(GetThis().mValue);
  16145. //ExtendLocalLifetimes(0);
  16146. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  16147. mCurMethodState->SetHadReturn(true);
  16148. mCurMethodState->mLeftBlockUncond = true;
  16149. }
  16150. else if ((mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()) && (methodDef->mName == BF_METHODNAME_TO_STRING))
  16151. {
  16152. auto enumType = ResolveTypeDef(mCompiler->mEnumTypeDef);
  16153. if (HasCompiledOutput())
  16154. {
  16155. EmitEnumToStringBody();
  16156. }
  16157. mBfIRBuilder->CreateRetVoid();
  16158. mCurMethodState->SetHadReturn(true);
  16159. mCurMethodState->mLeftBlockUncond = true;
  16160. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  16161. }
  16162. else if ((mCurTypeInstance->IsTuple()) && (!mCurTypeInstance->IsBoxed()) && (methodDef->mName == BF_METHODNAME_TO_STRING))
  16163. {
  16164. auto enumType = ResolveTypeDef(mCompiler->mEnumTypeDef);
  16165. if (HasCompiledOutput())
  16166. {
  16167. EmitTupleToStringBody();
  16168. }
  16169. mBfIRBuilder->CreateRetVoid();
  16170. mCurMethodState->SetHadReturn(true);
  16171. mCurMethodState->mLeftBlockUncond = true;
  16172. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  16173. }
  16174. else if (methodDef->mName == BF_METHODNAME_DEFAULT_EQUALS)
  16175. {
  16176. CreateValueTypeEqualsMethod(false);
  16177. skipBody = true;
  16178. skipEndChecks = true;
  16179. }
  16180. else if (methodDef->mName == BF_METHODNAME_DEFAULT_STRICT_EQUALS)
  16181. {
  16182. CreateValueTypeEqualsMethod(true);
  16183. skipBody = true;
  16184. skipEndChecks = true;
  16185. }
  16186. else if ((methodDef->mName == BF_METHODNAME_EQUALS) && (typeDef == mCompiler->mValueTypeTypeDef))
  16187. {
  16188. CreateValueTypeEqualsMethod(false);
  16189. skipBody = true;
  16190. skipEndChecks = true;
  16191. }
  16192. else
  16193. {
  16194. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  16195. if ((propertyDeclaration != NULL) && (!typeDef->HasAutoProperty(propertyDeclaration)))
  16196. {
  16197. if ((!mCurTypeInstance->IsInterface()) && (!hasExternSpecifier))
  16198. Fail("Body expected", methodDef->mBody);
  16199. }
  16200. else if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  16201. {
  16202. if (methodInstance->mReturnType->IsValuelessType())
  16203. {
  16204. mBfIRBuilder->CreateRetVoid();
  16205. }
  16206. else if (HasCompiledOutput())
  16207. {
  16208. String autoPropName = typeDef->GetAutoPropertyName(propertyDeclaration);
  16209. BfFieldInstance* fieldInstance = GetFieldByName(mCurTypeInstance, autoPropName);
  16210. BfFieldDef* fieldDef = NULL;
  16211. if (fieldInstance != NULL)
  16212. fieldDef = fieldInstance->GetFieldDef();
  16213. BfType* retType = methodInstance->mReturnType;
  16214. if (retType->IsRef())
  16215. retType = retType->GetUnderlyingType();
  16216. if ((fieldInstance != NULL) && (fieldInstance->GetResolvedType() == retType) &&
  16217. ((fieldInstance->mDataIdx >= 0) || (fieldDef->IsNonConstStatic())))
  16218. {
  16219. BfTypedValue lookupValue;
  16220. if (fieldDef->IsNonConstStatic())
  16221. lookupValue = ReferenceStaticField(fieldInstance);
  16222. else if (mCurTypeInstance->IsObject())
  16223. lookupValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(GetThis().mValue, 0, fieldInstance->mDataIdx), fieldInstance->mResolvedType, true);
  16224. else
  16225. lookupValue = ExtractValue(GetThis(), fieldInstance, fieldInstance->mDataIdx);
  16226. lookupValue = LoadOrAggregateValue(lookupValue);
  16227. CreateReturn(lookupValue.mValue);
  16228. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  16229. }
  16230. else
  16231. {
  16232. // This can happen if we have two properties with the same name but different types
  16233. CreateReturn(GetDefaultValue(mCurMethodInstance->mReturnType));
  16234. EmitDefaultReturn();
  16235. }
  16236. }
  16237. else
  16238. {
  16239. CreateReturn(GetDefaultValue(mCurMethodInstance->mReturnType));
  16240. EmitDefaultReturn();
  16241. }
  16242. mCurMethodState->SetHadReturn(true);
  16243. }
  16244. else if (methodDef->mMethodType == BfMethodType_PropertySetter)
  16245. {
  16246. if ((!methodDef->mIsMutating) && (mCurTypeInstance->IsValueType()))
  16247. {
  16248. Fail("Auto-setter must be marked as 'mut'", methodDef->GetRefNode(), true);
  16249. }
  16250. else if (!mCompiler->IsAutocomplete())
  16251. {
  16252. String autoPropName = typeDef->GetAutoPropertyName(propertyDeclaration);
  16253. BfFieldInstance* fieldInstance = GetFieldByName(mCurTypeInstance, autoPropName);
  16254. auto fieldDef = fieldInstance->GetFieldDef();
  16255. auto& lastParam = mCurMethodState->mLocals.back();
  16256. if ((fieldInstance != NULL) && (fieldInstance->GetResolvedType() == lastParam->mResolvedType) &&
  16257. ((fieldInstance->mDataIdx >= 0) || (fieldDef->IsNonConstStatic())))
  16258. {
  16259. BfIRValue lookupAddr;
  16260. if (fieldDef->IsNonConstStatic())
  16261. lookupAddr = ReferenceStaticField(fieldInstance).mValue;
  16262. else
  16263. {
  16264. auto thisValue = GetThis();
  16265. if (thisValue.IsSplat())
  16266. {
  16267. BFMODULE_FATAL(this, "Should not happen");
  16268. }
  16269. if (mCurTypeInstance->IsObject())
  16270. thisValue = LoadValue(thisValue);
  16271. lookupAddr = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInstance->mDataIdx);
  16272. }
  16273. BfExprEvaluator exprEvaluator(this);
  16274. auto localVal = exprEvaluator.LoadLocal(lastParam);
  16275. localVal = LoadOrAggregateValue(localVal);
  16276. mBfIRBuilder->CreateStore(localVal.mValue, lookupAddr);
  16277. }
  16278. else if (!fieldInstance->mResolvedType->IsValuelessType())
  16279. {
  16280. // This can happen if we have two properties with the same name but different types
  16281. AssertErrorState();
  16282. }
  16283. }
  16284. }
  16285. else if ((methodDef->mName == BF_METHODNAME_MARKMEMBERS) || (methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC))
  16286. {
  16287. if (mCompiler->mOptions.mEnableRealtimeLeakCheck)
  16288. {
  16289. if (HasCompiledOutput())
  16290. EmitGCMarkMembers();
  16291. }
  16292. else if (!mCurTypeInstance->IsObject())
  16293. {
  16294. }
  16295. }
  16296. else if (methodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS)
  16297. {
  16298. if (mCompiler->mOptions.mEnableRealtimeLeakCheck)
  16299. {
  16300. if (HasCompiledOutput())
  16301. EmitGCFindTLSMembers();
  16302. }
  16303. }
  16304. }
  16305. }
  16306. else if (!skipBody)
  16307. {
  16308. bool isEmptyBodied = BfNodeDynCast<BfTokenNode>(methodDef->mBody) != NULL;
  16309. if ((!mCurMethodInstance->mReturnType->IsValuelessType()) && (!isEmptyBodied))
  16310. {
  16311. mBfIRBuilder->PopulateType(mCurMethodInstance->mReturnType);
  16312. if (mCurMethodInstance->GetStructRetIdx() != -1)
  16313. {
  16314. auto ptrType = CreatePointerType(mCurMethodInstance->mReturnType);
  16315. auto allocaInst = AllocLocalVariable(ptrType, "__return.addr", false);
  16316. auto storeInst = mBfIRBuilder->CreateStore(mBfIRBuilder->GetArgument(mCurMethodInstance->GetStructRetIdx()), allocaInst);
  16317. mBfIRBuilder->ClearDebugLocation(storeInst);
  16318. mCurMethodState->mRetValAddr = allocaInst;
  16319. }
  16320. else
  16321. {
  16322. auto allocaInst = AllocLocalVariable(mCurMethodInstance->mReturnType, "__return", false);
  16323. mCurMethodState->mRetVal = BfTypedValue(allocaInst, mCurMethodInstance->mReturnType, true);
  16324. }
  16325. }
  16326. if (methodDef->mMethodType == BfMethodType_CtorCalcAppend)
  16327. {
  16328. mBfIRBuilder->CreateStore(GetConstValue(0), mCurMethodState->mRetVal.mValue);
  16329. BfGetSymbolReferenceKind prevSymbolKind;
  16330. BfAutoComplete* prevAutoComplete;
  16331. if (mCompiler->mResolvePassData != NULL)
  16332. {
  16333. prevSymbolKind = mCompiler->mResolvePassData->mGetSymbolReferenceKind;
  16334. prevAutoComplete = mCompiler->mResolvePassData->mAutoComplete;
  16335. mCompiler->mResolvePassData->mGetSymbolReferenceKind = BfGetSymbolReferenceKind_None;
  16336. }
  16337. EmitCtorCalcAppend();
  16338. if (mCompiler->mResolvePassData != NULL)
  16339. {
  16340. mCompiler->mResolvePassData->mGetSymbolReferenceKind = prevSymbolKind;
  16341. mCompiler->mResolvePassData->mAutoComplete = prevAutoComplete;
  16342. }
  16343. }
  16344. else if (!isEmptyBodied)
  16345. {
  16346. if (!mCurMethodState->mIRExitBlock)
  16347. mCurMethodState->mIRExitBlock = mBfIRBuilder->CreateBlock("exit", true);
  16348. bool isExpressionBody = false;
  16349. if (methodDeclaration != NULL)
  16350. {
  16351. if (methodDeclaration->mFatArrowToken != NULL)
  16352. isExpressionBody = true;
  16353. }
  16354. else if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  16355. {
  16356. auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration();
  16357. if ((propertyMethodDeclaration != NULL) && (propertyMethodDeclaration->mFatArrowToken != NULL))
  16358. isExpressionBody = true;
  16359. if (auto propBodyExpr = BfNodeDynCast<BfPropertyBodyExpression>(propertyDeclaration->mDefinitionBlock))
  16360. {
  16361. isExpressionBody = true;
  16362. }
  16363. }
  16364. else
  16365. {
  16366. if (auto block = BfNodeDynCast<BfBlock>(methodDef->mBody))
  16367. {
  16368. if (!block->mChildArr.IsEmpty())
  16369. {
  16370. if (auto exprStmt = BfNodeDynCast<BfExpressionStatement>(block->mChildArr.GetLast()))
  16371. {
  16372. if (exprStmt->mTrailingSemicolon == NULL)
  16373. isExpressionBody = true;
  16374. }
  16375. }
  16376. }
  16377. else
  16378. isExpressionBody = true;
  16379. }
  16380. if (auto fieldDtorBody = BfNodeDynCast<BfFieldDtorDeclaration>(methodDef->mBody))
  16381. {
  16382. while (fieldDtorBody != NULL)
  16383. {
  16384. VisitEmbeddedStatement(fieldDtorBody->mBody);
  16385. fieldDtorBody = fieldDtorBody->mNextFieldDtor;
  16386. }
  16387. }
  16388. else if (!isExpressionBody)
  16389. {
  16390. auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody);
  16391. mCurMethodState->mHeadScope.mAstBlock = bodyBlock;
  16392. mCurMethodState->mHeadScope.mCloseNode = bodyBlock->mCloseBrace;
  16393. VisitCodeBlock(bodyBlock);
  16394. }
  16395. else if (auto expressionBody = BfNodeDynCast<BfExpression>(methodDef->mBody))
  16396. {
  16397. // if ((methodDef->mMethodType != BfMethodType_Normal) && (propertyDeclaration == NULL))
  16398. // {
  16399. // BF_ASSERT(methodDeclaration->mFatArrowToken != NULL);
  16400. // Fail("Only normal methods can have expression bodies", methodDeclaration->mFatArrowToken);
  16401. // }
  16402. auto expectingType = mCurMethodInstance->mReturnType;
  16403. // What was this error for?
  16404. // if ((expectingType->IsVoid()) && (IsInSpecializedSection()))
  16405. // {
  16406. // Warn(0, "Using a 'void' return with an expression-bodied method isn't needed. Consider removing '=>' token", methodDeclaration->mFatArrowToken);
  16407. // }
  16408. BfEvalExprFlags exprEvalFlags = BfEvalExprFlags_AllowRefExpr;
  16409. if (expectingType->IsVoid())
  16410. {
  16411. exprEvalFlags = (BfEvalExprFlags)(exprEvalFlags | BfEvalExprFlags_NoCast);
  16412. bool wasReturnGenericParam = false;
  16413. if ((mCurMethodState->mClosureState != NULL) && (mCurMethodState->mClosureState->mReturnType != NULL))
  16414. {
  16415. wasReturnGenericParam = mCurMethodState->mClosureState->mReturnType->IsGenericParam();
  16416. }
  16417. else
  16418. {
  16419. auto unspecializedMethodInstance = GetUnspecializedMethodInstance(mCurMethodInstance);
  16420. if ((unspecializedMethodInstance != NULL) && (unspecializedMethodInstance->mReturnType->IsGenericParam()))
  16421. wasReturnGenericParam = true;
  16422. }
  16423. // If we the void return was from a generic specialization, allow us to return a void result,
  16424. // otherwise treat expression as though it must be a statement
  16425. bool isStatement = expressionBody->VerifyIsStatement(mCompiler->mPassInstance, wasReturnGenericParam);
  16426. if (isStatement)
  16427. expectingType = NULL;
  16428. }
  16429. UpdateSrcPos(expressionBody);
  16430. auto retVal = CreateValueFromExpression(expressionBody, expectingType, exprEvalFlags);
  16431. if ((retVal) && (!retVal.mType->IsVar()) && (expectingType != NULL))
  16432. {
  16433. mCurMethodState->mHadReturn = true;
  16434. retVal = LoadOrAggregateValue(retVal);
  16435. EmitReturn(retVal.mValue);
  16436. }
  16437. }
  16438. }
  16439. }
  16440. BF_ASSERT(mCurMethodState->mCurScope == &mCurMethodState->mHeadScope);
  16441. if (skipUpdateSrcPos)
  16442. {
  16443. // Skip
  16444. }
  16445. else if ((bodyBlock != NULL) && (bodyBlock->mCloseBrace != NULL))
  16446. UpdateSrcPos(bodyBlock->mCloseBrace);
  16447. else if (methodDef->mBody != NULL)
  16448. UpdateSrcPos(methodDef->mBody);
  16449. else if (methodDeclaration != NULL)
  16450. UpdateSrcPos(methodDeclaration);
  16451. else if (methodDef->mDeclaringType->mTypeDeclaration != NULL)
  16452. UpdateSrcPos(methodDef->mDeclaringType->mTypeDeclaration);
  16453. else
  16454. UseDefaultSrcPos();
  16455. if (methodDef->mMethodType == BfMethodType_CtorCalcAppend)
  16456. {
  16457. if (mCurMethodState->mRetVal)
  16458. {
  16459. mCurMethodState->SetHadReturn(true);
  16460. auto retVal = mBfIRBuilder->CreateLoad(mCurMethodState->mRetVal.mValue);
  16461. mBfIRBuilder->CreateRet(retVal);
  16462. }
  16463. else
  16464. AssertErrorState();
  16465. }
  16466. if (!mCurMethodState->mHadReturn)
  16467. {
  16468. // Clear off the stackallocs that have occurred after a scopeData break
  16469. EmitDeferredScopeCalls(false, &mCurMethodState->mHeadScope, mCurMethodState->mIRExitBlock);
  16470. }
  16471. if (mCurMethodState->mIRExitBlock)
  16472. {
  16473. for (auto preExitBlock : mCurMethodState->mHeadScope.mAtEndBlocks)
  16474. mBfIRBuilder->MoveBlockToEnd(preExitBlock);
  16475. mBfIRBuilder->MoveBlockToEnd(mCurMethodState->mIRExitBlock);
  16476. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRExitBlock);
  16477. if (!mCurMethodState->mDIRetVal)
  16478. CreateDIRetVal();
  16479. }
  16480. for (auto localVar : mCurMethodState->mLocals)
  16481. {
  16482. if ((skipEndChecks) || (methodDef->mBody == NULL))
  16483. break;
  16484. LocalVariableDone(localVar, true);
  16485. }
  16486. if (mCurMethodState->mIRExitBlock)
  16487. {
  16488. if ((mCurMethodState->mRetVal) && (mCurMethodInstance->GetStructRetIdx() == -1))
  16489. {
  16490. auto loadedVal = mBfIRBuilder->CreateLoad(mCurMethodState->mRetVal.mValue);
  16491. CreateReturn(loadedVal);
  16492. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  16493. if (mCurMethodState->mDIRetVal)
  16494. mBfIRBuilder->DbgLifetimeEnd(mCurMethodState->mDIRetVal);
  16495. }
  16496. else
  16497. {
  16498. // Have something on the last line to step onto
  16499. if (mHasFullDebugInfo)
  16500. {
  16501. if ((bodyBlock != NULL) && (bodyBlock->mCloseBrace != NULL))
  16502. UpdateSrcPos(bodyBlock->mCloseBrace);
  16503. EmitEnsureInstructionAt();
  16504. if ((irParamCount == 0) && (!IsTargetingBeefBackend()) && (mCompiler->mOptions.mAllowHotSwapping))
  16505. {
  16506. // This may be a case where we only emit 4 bytes, whereas we need 5 for a hot replace jump
  16507. mBfIRBuilder->EnsureFunctionPatchable();
  16508. }
  16509. }
  16510. mBfIRBuilder->CreateRetVoid();
  16511. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  16512. if (mCurMethodState->mDIRetVal)
  16513. mBfIRBuilder->DbgLifetimeEnd(mCurMethodState->mDIRetVal);
  16514. }
  16515. }
  16516. if ((mCurMethodInstance->mReturnType == NULL) || (mCurMethodInstance->mReturnType->IsValuelessType()))
  16517. {
  16518. if ((!mCurMethodState->mHadReturn) && (!mCurMethodState->mIRExitBlock))
  16519. {
  16520. if ((irParamCount == 0) && (!IsTargetingBeefBackend()) && (mCompiler->mOptions.mAllowHotSwapping))
  16521. {
  16522. // This may be a case where we only emit 4 bytes, whereas we need 5 for a hot replace jump
  16523. mBfIRBuilder->EnsureFunctionPatchable();
  16524. }
  16525. mBfIRBuilder->CreateRetVoid();
  16526. }
  16527. }
  16528. else
  16529. {
  16530. if (!mCurMethodState->mHadReturn)
  16531. {
  16532. auto refNode = mCurMethodInstance->mMethodDef->GetRefNode();
  16533. if (bodyBlock != NULL)
  16534. {
  16535. if (bodyBlock->mCloseBrace != NULL)
  16536. {
  16537. BfAstNode* target = bodyBlock->mCloseBrace;
  16538. Fail("Method must return value", target);
  16539. }
  16540. else
  16541. {
  16542. // It's possible to not have a closing brace if the method ends in an EOF
  16543. AssertErrorState();
  16544. }
  16545. }
  16546. }
  16547. }
  16548. // Move 'init' into 'entry'
  16549. mBfIRBuilder->MergeBlockDown(mCurMethodState->mIRInitBlock, mCurMethodState->mIREntryBlock);
  16550. mBfIRBuilder->MergeBlockDown(mCurMethodState->mIRHeadBlock, mCurMethodState->mIREntryBlock);
  16551. if ((mCurMethodInstance->mIsUnspecialized) /*|| (typeDef->mIsFunction)*/ || (mCurTypeInstance->IsUnspecializedType()))
  16552. {
  16553. // Don't keep instructions for unspecialized types
  16554. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  16555. }
  16556. if ((hasExternSpecifier) && (!skipBody))
  16557. {
  16558. // If we hot swap, we want to make sure at least one method refers to this extern method so it gets pulled in
  16559. // incase it gets called later by some hot-loaded coded
  16560. if ((mCompiler->mOptions.mAllowHotSwapping) && (mCurMethodInstance->mIRFunction) && (!mCurMethodInstance->mIRFunction.IsFake()))
  16561. CreateFakeCallerMethod(mangledName);
  16562. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  16563. }
  16564. else if ((methodInstance->GetImportKind() == BfImportKind_Import_Dynamic) && (!mCompiler->IsHotCompile()))
  16565. {
  16566. // We only need the DLL stub when we may be hot swapping
  16567. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  16568. }
  16569. else if (wantsRemoveBody)
  16570. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  16571. // We don't want to hold on to pointers to LLVMFunctions of unspecialized types.
  16572. // This allows us to delete the mScratchModule LLVM module without rebuilding all
  16573. // unspecialized types
  16574. if ((mCurTypeInstance->IsUnspecializedType()) || (mCurTypeInstance->IsInterface()))
  16575. {
  16576. BfLogSysM("ProcessMethod Clearing IRFunction: %p\n", methodInstance);
  16577. methodInstance->mIRFunction = BfIRFunction();
  16578. }
  16579. CheckAddFailType();
  16580. if (mHadBuildError)
  16581. prevHadBuildError.CancelRestore();
  16582. if (mHadBuildWarning)
  16583. prevHadWarning.CancelRestore();
  16584. if (!methodDef->mIsLocalMethod)
  16585. ProcessMethod_ProcessDeferredLocals();
  16586. mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  16587. if (methodState.mHotDataReferenceBuilder != NULL)
  16588. {
  16589. AddHotDataReferences(&hotDataReferenceBuilder);
  16590. }
  16591. else
  16592. {
  16593. if ((methodInstance->mHotMethod != NULL) && (!methodInstance->mIsReified))
  16594. {
  16595. // Remove the hot method data
  16596. auto hotMethod = methodInstance->mHotMethod;
  16597. auto prevMethod = hotMethod->mPrevVersion;
  16598. if (prevMethod != NULL)
  16599. {
  16600. // If there's a prev method then pull its data into the main HotMethod.
  16601. // This, in effect, removes the 'hotMethod' data and rebases 'prevMethod'
  16602. // over to the main HotMethod definition to keep the HotMethod address
  16603. // invariant
  16604. for (auto ref : hotMethod->mReferences)
  16605. ref->Deref();
  16606. hotMethod->mReferences.Clear();
  16607. BF_ASSERT(prevMethod->mRefCount == 1);
  16608. hotMethod->mReferences = prevMethod->mReferences;
  16609. if (hotMethod->mSrcTypeVersion != NULL)
  16610. hotMethod->mSrcTypeVersion->Deref();
  16611. hotMethod->mSrcTypeVersion = prevMethod->mSrcTypeVersion;
  16612. prevMethod->mSrcTypeVersion = NULL;
  16613. prevMethod->mReferences.Clear();
  16614. hotMethod->mPrevVersion = prevMethod->mPrevVersion;
  16615. prevMethod->mPrevVersion = NULL;
  16616. prevMethod->Deref();
  16617. }
  16618. hotMethod->Deref();
  16619. methodInstance->mHotMethod = NULL;
  16620. }
  16621. }
  16622. }
  16623. String BfModule::GetLocalMethodName(const StringImpl& baseName, BfAstNode* anchorNode, BfMethodState* declMethodState, BfMixinState* declMixinState)
  16624. {
  16625. String name;
  16626. bool found = false;
  16627. auto checkMethodState = mCurMethodState;
  16628. while (checkMethodState != NULL)
  16629. {
  16630. if (checkMethodState->mClosureState == NULL)
  16631. break;
  16632. if (checkMethodState->mClosureState->mClosureMethodDef != NULL)
  16633. {
  16634. found = true;
  16635. name += checkMethodState->mClosureState->mClosureMethodDef->mName;
  16636. break;
  16637. }
  16638. checkMethodState = checkMethodState->mPrevMethodState;
  16639. }
  16640. if (!found)
  16641. name += mCurMethodInstance->mMethodDef->mName;
  16642. int prevSepPos = (int)name.LastIndexOf('$');
  16643. if (prevSepPos != -1)
  16644. {
  16645. name.RemoveToEnd(prevSepPos);
  16646. }
  16647. name += "@";
  16648. name += baseName;
  16649. HashContext hashCtx;
  16650. if (anchorNode != NULL)
  16651. {
  16652. hashCtx.Mixin(anchorNode->GetStartCharId());
  16653. }
  16654. //
  16655. {
  16656. auto checkMethodState = declMethodState;
  16657. auto checkMixinState = declMixinState;
  16658. while (checkMethodState != NULL)
  16659. {
  16660. if (checkMixinState != NULL)
  16661. {
  16662. hashCtx.Mixin(checkMixinState->mSource->GetStartCharId());
  16663. }
  16664. checkMethodState = checkMethodState->mPrevMethodState;
  16665. if (checkMethodState != NULL)
  16666. checkMixinState = checkMethodState->mMixinState;
  16667. }
  16668. }
  16669. auto rootMethodState = mCurMethodState->GetRootMethodState();
  16670. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  16671. {
  16672. for (auto methodGenericArg : rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  16673. {
  16674. StringT<128> genericTypeName;
  16675. BfMangler::Mangle(genericTypeName, mCompiler->GetMangleKind(), methodGenericArg);
  16676. hashCtx.MixinStr(genericTypeName);
  16677. }
  16678. }
  16679. uint64 hashVal = hashCtx.Finish64();
  16680. name += "$";
  16681. name += BfTypeUtils::HashEncode64(hashVal);
  16682. return name;
  16683. }
  16684. BfMethodDef* BfModule::GetLocalMethodDef(BfLocalMethod* localMethod)
  16685. {
  16686. if (localMethod->mMethodDef != NULL)
  16687. return localMethod->mMethodDef;
  16688. auto rootMethodState = mCurMethodState->GetRootMethodState();
  16689. auto declMethodState = localMethod->mDeclMethodState;
  16690. auto declMixinState = localMethod->mDeclMixinState;
  16691. auto typeInst = mCurTypeInstance;
  16692. BfAstNode* body = NULL;
  16693. BfAstNode* anchorNode = NULL;
  16694. auto _AllocDirectTypeRef = [&](BfType* type)
  16695. {
  16696. BfDirectTypeReference* directTypeRef = localMethod->mDirectTypeRefs.Alloc();
  16697. directTypeRef->Init(type);
  16698. return directTypeRef;
  16699. };
  16700. auto methodDeclaration = localMethod->mMethodDeclaration;
  16701. if (methodDeclaration != NULL)
  16702. {
  16703. body = methodDeclaration->mBody;
  16704. anchorNode = methodDeclaration->mOpenParen;
  16705. }
  16706. else
  16707. {
  16708. body = localMethod->mLambdaBindExpr->mBody;
  16709. anchorNode = localMethod->mLambdaBindExpr->mFatArrowToken;
  16710. }
  16711. BF_ASSERT(rootMethodState->mCurLocalVarId >= 0);
  16712. int methodLocalIdx = rootMethodState->mCurLocalVarId++;
  16713. BfMethodDef* methodDef;
  16714. BfMethodDef* outerMethodDef = NULL;
  16715. if (localMethod->mOuterLocalMethod != NULL)
  16716. outerMethodDef = localMethod->mOuterLocalMethod->mMethodDef;
  16717. else
  16718. outerMethodDef = rootMethodState->mMethodInstance->mMethodDef;
  16719. if (methodDeclaration != NULL)
  16720. {
  16721. BfDefBuilder defBuilder(mCompiler->mSystem);
  16722. defBuilder.mCurSource = localMethod->mMethodDeclaration->GetParser();
  16723. defBuilder.mPassInstance = mCompiler->mPassInstance;
  16724. defBuilder.mCurTypeDef = mCurMethodInstance->mMethodDef->mDeclaringType;
  16725. methodDef = defBuilder.CreateMethodDef(methodDeclaration, outerMethodDef);
  16726. }
  16727. else
  16728. {
  16729. auto invokeMethod = localMethod->mLambdaInvokeMethodInstance;
  16730. methodDef = new BfMethodDef();
  16731. methodDef->mName = localMethod->mMethodName;
  16732. methodDef->mDeclaringType = mCurMethodInstance->mMethodDef->mDeclaringType;
  16733. methodDef->mReturnTypeRef = _AllocDirectTypeRef(invokeMethod->mReturnType);
  16734. methodDef->mBody = body;
  16735. for (int paramIdx = 0; paramIdx < invokeMethod->GetParamCount(); paramIdx++)
  16736. {
  16737. auto paramType = invokeMethod->GetParamType(paramIdx);
  16738. String paramName;
  16739. if (paramIdx < (int)localMethod->mLambdaBindExpr->mParams.size())
  16740. paramName = localMethod->mLambdaBindExpr->mParams[paramIdx]->ToString();
  16741. else
  16742. paramName = invokeMethod->GetParamName(paramIdx);
  16743. auto paramDef = new BfParameterDef();
  16744. paramDef->mTypeRef = _AllocDirectTypeRef(paramType);
  16745. paramDef->mName = paramName;
  16746. methodDef->mParams.Add(paramDef);
  16747. }
  16748. if (outerMethodDef != NULL)
  16749. {
  16750. for (auto genericParam : outerMethodDef->mGenericParams)
  16751. {
  16752. auto* copiedGenericParamDef = new BfGenericParamDef();
  16753. *copiedGenericParamDef = *genericParam;
  16754. methodDef->mGenericParams.Add(copiedGenericParamDef);
  16755. }
  16756. }
  16757. }
  16758. methodDef->mIdx = ~methodLocalIdx;
  16759. BF_ASSERT(!localMethod->mExpectedFullName.IsEmpty());
  16760. methodDef->mName = localMethod->mExpectedFullName;
  16761. // methodDef->mName = GetLocalMethodName(methodDef->mName, anchorNode, declMethodState, declMixinState);
  16762. //
  16763. // if (!localMethod->mExpectedFullName.IsEmpty())
  16764. // BF_ASSERT(methodDef->mName == localMethod->mExpectedFullName);
  16765. methodDef->mIsStatic = true;
  16766. methodDef->mIsLocalMethod = true;
  16767. methodDef->mIsVirtual = false;
  16768. localMethod->mMethodDef = methodDef;
  16769. auto methodInstanceGroup = new BfMethodInstanceGroup();
  16770. localMethod->mMethodInstanceGroup = methodInstanceGroup;
  16771. methodInstanceGroup->mMethodIdx = -1;
  16772. methodInstanceGroup->mOwner = mCurTypeInstance;
  16773. methodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  16774. if ((declMethodState->mMixinState != NULL) && (declMethodState->mMixinState->mTarget))
  16775. {
  16776. methodInstanceGroup->mOwner = declMethodState->mMixinState->mTarget.mType->ToTypeInstance();
  16777. BF_ASSERT(methodInstanceGroup->mOwner != NULL);
  16778. }
  16779. if ((mCompiler->mResolvePassData != NULL) && (methodDeclaration != NULL))
  16780. {
  16781. mCompiler->mResolvePassData->HandleLocalReference(methodDeclaration->mNameNode, typeInst->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, methodLocalIdx);
  16782. auto autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  16783. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(methodDeclaration->mNameNode)))
  16784. {
  16785. autoComplete->SetDefinitionLocation(methodDeclaration->mNameNode);
  16786. autoComplete->mInsertStartIdx = methodDeclaration->mNameNode->GetSrcStart();
  16787. autoComplete->mInsertEndIdx = methodDeclaration->mNameNode->GetSrcEnd();
  16788. autoComplete->mDefType = typeInst->mTypeDef;
  16789. autoComplete->mDefMethod = rootMethodState->mMethodInstance->mMethodDef;
  16790. autoComplete->mReplaceLocalId = methodLocalIdx;
  16791. }
  16792. }
  16793. return localMethod->mMethodDef;
  16794. }
  16795. BfModuleMethodInstance BfModule::GetLocalMethodInstance(BfLocalMethod* localMethod, const BfTypeVector& methodGenericArguments, BfMethodInstance* methodInstance, bool force)
  16796. {
  16797. BP_ZONE_F("GetLocalMethodInstance %s", localMethod->mMethodName.c_str());
  16798. BfLogSysM("GetLocalMethodInstance %p\n", localMethod);
  16799. auto rootMethodState = mCurMethodState->GetRootMethodState();
  16800. auto declMethodState = localMethod->mDeclMethodState;
  16801. auto declMixinState = localMethod->mDeclMixinState;
  16802. auto callerMethodState = mCurMethodState;
  16803. auto typeInst = mCurTypeInstance;
  16804. if (mCurMethodState->mMixinState != NULL)
  16805. {
  16806. typeInst = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  16807. }
  16808. auto methodDef = GetLocalMethodDef(localMethod);
  16809. BfAstNode* body = NULL;
  16810. auto methodDeclaration = localMethod->mMethodDeclaration;
  16811. if (methodDeclaration != NULL)
  16812. {
  16813. body = methodDeclaration->mBody;
  16814. }
  16815. else
  16816. {
  16817. body = localMethod->mLambdaBindExpr->mBody;
  16818. }
  16819. bool hadConcreteInterfaceGenericArgument = false;
  16820. BfTypeVector sanitizedMethodGenericArguments;
  16821. // Ignore the outermost method's generic method arguments for the purpose of determining if we are the 'default' (ie: unspecialized)
  16822. // version of this method for this pass through the outermost method
  16823. int dependentGenericStartIdx = 0;
  16824. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  16825. dependentGenericStartIdx = (int)rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  16826. BfMethodInstance* outerMethodInstance = mCurMethodInstance;
  16827. if (methodGenericArguments.size() == 0)
  16828. {
  16829. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  16830. sanitizedMethodGenericArguments = rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments;
  16831. }
  16832. else
  16833. {
  16834. int genericArgIdx = 0;
  16835. // for (; genericArgIdx < (int)outerMethodInstance->mMethodGenericArguments.size(); genericArgIdx++)
  16836. // {
  16837. // BF_ASSERT(methodGenericArguments[genericArgIdx] == outerMethodInstance->mMethodGenericArguments[genericArgIdx]);
  16838. // sanitizedMethodGenericArguments.push_back(methodGenericArguments[genericArgIdx]);
  16839. // }
  16840. for (; genericArgIdx < (int)methodGenericArguments.size(); genericArgIdx++)
  16841. {
  16842. auto genericArgType = methodGenericArguments[genericArgIdx];
  16843. BF_ASSERT(!genericArgType->IsRef());
  16844. if (genericArgType->IsConcreteInterfaceType())
  16845. {
  16846. hadConcreteInterfaceGenericArgument = true;
  16847. auto concreteInterfaceType = (BfConcreteInterfaceType*)genericArgType;
  16848. genericArgType = concreteInterfaceType->mInterface;
  16849. }
  16850. sanitizedMethodGenericArguments.push_back(genericArgType);
  16851. }
  16852. }
  16853. bool wantPrematureMethodInstance = false;
  16854. if (!force)
  16855. {
  16856. wantPrematureMethodInstance = (callerMethodState->mClosureState != NULL) && (callerMethodState->mClosureState->mCaptureVisitingBody);
  16857. }
  16858. auto methodInstGroup = localMethod->mMethodInstanceGroup;
  16859. bool isDefaultPass = true;
  16860. BfTypeVector lookupMethodGenericArguments;
  16861. for (int genericArgIdx = dependentGenericStartIdx; genericArgIdx < (int)methodGenericArguments.size(); genericArgIdx++)
  16862. {
  16863. auto genericArgType = methodGenericArguments[genericArgIdx];
  16864. BF_ASSERT(!genericArgType->IsRef());
  16865. lookupMethodGenericArguments.Add(genericArgType);
  16866. if (genericArgType->IsGenericParam())
  16867. {
  16868. auto genericParam = (BfGenericParamType*)genericArgType;
  16869. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  16870. isDefaultPass = false;
  16871. }
  16872. else
  16873. {
  16874. isDefaultPass = false;
  16875. }
  16876. }
  16877. bool hadExistingMethodInstance = false;
  16878. if (methodInstance != NULL)
  16879. {
  16880. hadExistingMethodInstance = true;
  16881. }
  16882. else
  16883. {
  16884. if (isDefaultPass)
  16885. {
  16886. methodInstance = methodInstGroup->mDefault;
  16887. if (methodInstance != NULL)
  16888. {
  16889. hadExistingMethodInstance = true;
  16890. }
  16891. else
  16892. {
  16893. methodInstance = new BfMethodInstance();
  16894. methodInstGroup->mDefault = methodInstance;
  16895. }
  16896. }
  16897. else
  16898. {
  16899. BF_ASSERT(sanitizedMethodGenericArguments.size() != 0);
  16900. if (methodInstGroup->mMethodSpecializationMap == NULL)
  16901. methodInstGroup->mMethodSpecializationMap = new BfMethodInstanceGroup::MapType();
  16902. BfMethodInstance** methodInstancePtr = NULL;
  16903. if (!methodInstGroup->mMethodSpecializationMap->TryAdd(lookupMethodGenericArguments, NULL, &methodInstancePtr))
  16904. {
  16905. methodInstance = *methodInstancePtr;
  16906. hadExistingMethodInstance = true;
  16907. }
  16908. else
  16909. {
  16910. methodInstance = new BfMethodInstance();
  16911. *methodInstancePtr = methodInstance;
  16912. }
  16913. }
  16914. }
  16915. if (hadExistingMethodInstance)
  16916. {
  16917. if ((!methodInstance->mDisallowCalling) ||
  16918. ((wantPrematureMethodInstance) && (methodInstance->mDisallowCalling)))
  16919. return BfModuleMethodInstance(methodInstance);
  16920. BF_ASSERT((methodInstance->mMethodInfoEx == NULL) || (methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState == NULL));
  16921. }
  16922. else
  16923. {
  16924. auto methodInfoEx = methodInstance->GetMethodInfoEx();
  16925. methodInfoEx->mClosureInstanceInfo = new BfClosureInstanceInfo();
  16926. methodInfoEx->mClosureInstanceInfo->mLocalMethod = localMethod;
  16927. methodInstance->mIsReified = mCurMethodInstance->mIsReified;
  16928. methodInstance->mIsAutocompleteMethod = mCurMethodInstance->mIsAutocompleteMethod;
  16929. methodInstance->mMethodDef = methodDef;
  16930. methodInstance->mMethodInstanceGroup = localMethod->mMethodInstanceGroup;
  16931. if (hadConcreteInterfaceGenericArgument)
  16932. methodInstance->mIgnoreBody = true;
  16933. methodInfoEx->mMethodGenericArguments = sanitizedMethodGenericArguments;
  16934. for (auto genericArg : sanitizedMethodGenericArguments)
  16935. {
  16936. if (genericArg->IsPrimitiveType())
  16937. genericArg = GetWrappedStructType(genericArg);
  16938. AddDependency(genericArg, typeInst, BfDependencyMap::DependencyFlag_MethodGenericArg);
  16939. }
  16940. for (int genericParamIdx = (int)sanitizedMethodGenericArguments.size(); genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  16941. {
  16942. auto genericParamType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  16943. methodInfoEx->mMethodGenericArguments.push_back(genericParamType);
  16944. }
  16945. SetupMethodIdHash(methodInstance);
  16946. }
  16947. auto _SetupMethodInstance = [&]()
  16948. {
  16949. BF_ASSERT(methodInstance->GetNumGenericParams() == 0);
  16950. // Generic constraints
  16951. for (int genericParamIdx = 0; genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  16952. {
  16953. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, genericParamIdx);
  16954. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  16955. }
  16956. };
  16957. //////////////////////////////////////////////////////////////////////////
  16958. auto _VisitLambdaBody = [&]()
  16959. {
  16960. if (localMethod->mDeclOnly)
  16961. return;
  16962. if (mCompiler->mCanceling)
  16963. return;
  16964. if (auto blockBody = BfNodeDynCast<BfBlock>(body))
  16965. {
  16966. VisitCodeBlock(blockBody);
  16967. }
  16968. else if (auto bodyExpr = BfNodeDynCast<BfExpression>(body))
  16969. CreateValueFromExpression(bodyExpr);
  16970. };
  16971. auto _SafeResolveTypeRef = [&](BfTypeReference* typeRef)
  16972. {
  16973. SetAndRestoreValue<bool> prevIgnoreError(mIgnoreErrors, true);
  16974. auto result = ResolveTypeRef(typeRef);
  16975. if (result == NULL)
  16976. result = mContext->mBfObjectType;
  16977. return result;
  16978. };
  16979. BfTypeInstance* outerClosure = NULL;
  16980. if ((declMethodState->mClosureState != NULL) && (!declMethodState->mClosureState->mCapturing))
  16981. outerClosure = declMethodState->mClosureState->mClosureType;
  16982. BfMethodState methodState;
  16983. methodState.mPrevMethodState = declMethodState;//mCurMethodState;
  16984. BfIRFunctionType funcType;
  16985. auto voidType = GetPrimitiveType(BfTypeCode_None);
  16986. SizedArray<BfIRType, 0> paramTypes;
  16987. funcType = mBfIRBuilder->CreateFunctionType(mBfIRBuilder->MapType(voidType), paramTypes, methodInstance->IsVarArgs());
  16988. mBfIRBuilder->SaveDebugLocation();
  16989. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  16990. auto prevActiveFunction = mBfIRBuilder->GetActiveFunction();
  16991. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  16992. BfDeferredLocalAssignData deferredLocalAssignData;
  16993. //TODO: Why did we do this? It can cause us to pull in local variables that don't belong to us...
  16994. /*if (declMethodState->mDeferredLocalAssignData != NULL)
  16995. deferredLocalAssignData.ExtendFrom(declMethodState->mDeferredLocalAssignData);*/
  16996. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  16997. methodState.mIRHeadBlock = mBfIRBuilder->CreateBlock("head", true);
  16998. methodState.mIRInitBlock = mBfIRBuilder->CreateBlock("init", true);
  16999. methodState.mIREntryBlock = mBfIRBuilder->CreateBlock("entry", true);
  17000. methodState.mCurScope->mDIScope = localMethod->mDeclDIScope; //declMethodState->mCurScope->mDIScope ;
  17001. //methodState.mCurLocalVarId = declMethodState->mCurLocalVarId;
  17002. methodState.mIRFunction = declMethodState->mIRFunction;
  17003. methodState.mDeferredLocalAssignData = &deferredLocalAssignData;
  17004. if (auto blockBody = BfNodeDynCast<BfBlock>(body))
  17005. {
  17006. methodState.mCurScope->mAstBlock = blockBody;
  17007. methodState.mCurScope->mCloseNode = blockBody->mCloseBrace;
  17008. }
  17009. mBfIRBuilder->SetInsertPoint(methodState.mIREntryBlock);
  17010. BfClosureState closureState;
  17011. if (methodDef->mMethodType == BfMethodType_Mixin)
  17012. {
  17013. if (declMethodState != NULL)
  17014. {
  17015. if ((declMethodState->mClosureState != NULL) && (declMethodState->mClosureState->mReturnType != NULL))
  17016. closureState.mReturnType = declMethodState->mClosureState->mReturnType;
  17017. else if (declMethodState->mMethodInstance != NULL)
  17018. closureState.mReturnType = declMethodState->mMethodInstance->mReturnType;
  17019. }
  17020. }
  17021. if (closureState.mReturnType == NULL)
  17022. closureState.mReturnType = _SafeResolveTypeRef(methodDef->mReturnTypeRef);
  17023. closureState.mCapturing = true;
  17024. closureState.mLocalMethod = localMethod;
  17025. closureState.mClosureInstanceInfo = methodInstance->mMethodInfoEx->mClosureInstanceInfo;
  17026. closureState.mDeclaringMethodIsMutating = mCurMethodInstance->mMethodDef->mIsMutating;
  17027. methodState.mClosureState = &closureState;
  17028. closureState.mClosureType = outerClosure;
  17029. int outerLocalsCount = (int)methodState.mLocals.size();
  17030. if (!hadExistingMethodInstance)
  17031. {
  17032. BfLogSysM("LocalMethod %p premature DoMethodDeclaration %p (Source:%p)\n", localMethod, methodInstance, (methodDeclaration != NULL) ? methodDeclaration->GetSourceData() : NULL);
  17033. SetAndRestoreValue<bool> prevIgnoreWrites(mWantsIRIgnoreWrites, true);
  17034. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  17035. // Prematurely do declaration. We will have to undo this later, so don't write this one and don't throw errors
  17036. auto declareModule = this;
  17037. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  17038. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  17039. BF_ASSERT(declareModule != NULL);
  17040. methodInstance->mDeclModule = declareModule;
  17041. _SetupMethodInstance();
  17042. declareModule->DoMethodDeclaration(localMethod->mMethodDef->GetMethodDeclaration(), false, false);
  17043. methodInstance->mDisallowCalling = true; // Don't allow us to ACTUALLY call until we add the captures
  17044. }
  17045. if (wantPrematureMethodInstance)
  17046. {
  17047. // Return a premature methodInstance -- since we are partway through determining the capture of a local method, we can't rely on its
  17048. // capture information. This returned method instance can only be used for method matching, but we will visit it later to create
  17049. // its true method instance
  17050. //auto moduleMethodInstance = _CheckReturnedMethod(methodInstance);
  17051. //BF_ASSERT(moduleMethodInstance);
  17052. return BfModuleMethodInstance(methodInstance);
  17053. }
  17054. auto checkInsertBlock = mBfIRBuilder->GetInsertBlock();
  17055. BF_ASSERT(methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState == NULL);
  17056. closureState.mCaptureStartAccessId = mCurMethodState->GetRootMethodState()->mCurAccessId;
  17057. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState = &closureState;
  17058. closureState.mClosureMethodDef = methodDef;
  17059. bool wantsVisitBody = true;
  17060. if ((methodDef->mMethodType == BfMethodType_Mixin) && (!methodGenericArguments.IsEmpty()))
  17061. wantsVisitBody = false;
  17062. if (methodInstance->IsOrInUnspecializedVariation())
  17063. wantsVisitBody = false;
  17064. if (wantsVisitBody)
  17065. {
  17066. BP_ZONE("VisitLambdaBody");
  17067. // For generic methods, we capture for each specialization, so make sure mIsStatic is set to 'true' for
  17068. // this capture stage for each of those times
  17069. SetAndRestoreValue<bool> prevWasStatis(methodDef->mIsStatic, true);
  17070. /*
  17071. // Only generate errors once. Also there are some errors that will occur during this scanning phase
  17072. // that will not occur during the actual lambda method generation, for example: returning a value
  17073. // when our current method is a 'void' method. This shouldn't affect capture scanning since all
  17074. // our AST nodes will still be visited
  17075. SetAndRestoreValue<bool> ignoreError(mIgnoreErrors, true);
  17076. */
  17077. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  17078. //SetAndRestoreValue<bool> wantsIgnoreWrites(mWantsISIgnoreWrites, true);
  17079. mBfIRBuilder->SaveDebugLocation();
  17080. closureState.mCaptureVisitingBody = true;
  17081. BF_ASSERT(methodInstance->mMethodInfoEx != NULL);
  17082. methodState.mGenericTypeBindings = &methodInstance->mMethodInfoEx->mGenericTypeBindings;
  17083. methodState.mMethodInstance = methodInstance;
  17084. NewScopeState();
  17085. ProcessMethod_SetupParams(methodInstance, NULL, false, NULL);
  17086. if (methodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)
  17087. {
  17088. // Allow assigning to arguments when we're capturing - which may or may not be legal at the injection site (we throw error there)
  17089. for (auto localDef : methodState.mLocals)
  17090. {
  17091. if (localDef->mResolvedType->IsVar())
  17092. continue;
  17093. localDef->mAddr = CreateAlloca(localDef->mResolvedType);
  17094. }
  17095. }
  17096. // Keep outs for being marked as assigned
  17097. auto rootMethodState = mCurMethodState->GetRootMethodState();
  17098. BfDeferredLocalAssignData deferredLocalAssignData(rootMethodState->mCurScope);
  17099. deferredLocalAssignData.mVarIdBarrier = rootMethodState->mCurLocalVarId;
  17100. SetAndRestoreValue<BfDeferredLocalAssignData*> prevDLA(rootMethodState->mDeferredLocalAssignData, &deferredLocalAssignData);
  17101. if (!mIgnoreErrors)
  17102. localMethod->mDidBodyErrorPass = true;
  17103. _VisitLambdaBody();
  17104. RestoreScopeState();
  17105. closureState.mCaptureVisitingBody = false;
  17106. mBfIRBuilder->RestoreDebugLocation();
  17107. }
  17108. // If we ended up being called by a method with a lower captureStartAccessId, propagate that to whoever is calling us, too...
  17109. if ((methodState.mPrevMethodState->mClosureState != NULL) && (methodState.mPrevMethodState->mClosureState->mCapturing))
  17110. {
  17111. auto prevClosureState = methodState.mPrevMethodState->mClosureState;
  17112. if (closureState.mCaptureStartAccessId < prevClosureState->mCaptureStartAccessId)
  17113. prevClosureState->mCaptureStartAccessId = closureState.mCaptureStartAccessId;
  17114. }
  17115. // Actually get the referenced local methods. It's important we wait until after visiting the body, because then our own capture information
  17116. // can be used by these methods (which will be necessary if any of these methods call us directly or indirectly)
  17117. closureState.mClosureMethodDef = NULL;
  17118. for (auto methodInstance : closureState.mLocalMethodRefs)
  17119. {
  17120. GetLocalMethodInstance(methodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod, BfTypeVector(), methodInstance);
  17121. }
  17122. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState = NULL;
  17123. prevIgnoreWrites.Restore();
  17124. std::multiset<BfClosureCapturedEntry> capturedEntries;
  17125. //
  17126. {
  17127. auto varMethodState = declMethodState;
  17128. while (varMethodState != NULL)
  17129. {
  17130. if ((varMethodState->mMixinState != NULL) && (varMethodState->mMixinState->mLastTargetAccessId >= closureState.mCaptureStartAccessId))
  17131. {
  17132. BF_ASSERT(methodInstance->GetOwner() == varMethodState->mMixinState->mTarget.mType);
  17133. methodDef->mIsStatic = false;
  17134. if (rootMethodState->mMethodInstance->mMethodDef->mIsMutating)
  17135. methodDef->mIsMutating = true;
  17136. }
  17137. bool copyOuterCaptures = false;
  17138. for (int localIdx = 0; localIdx < varMethodState->mLocals.size(); localIdx++)
  17139. {
  17140. auto localVar = varMethodState->mLocals[localIdx];
  17141. if ((localVar->mReadFromId >= closureState.mCaptureStartAccessId) || (localVar->mWrittenToId >= closureState.mCaptureStartAccessId))
  17142. {
  17143. if (localVar->mIsThis)
  17144. {
  17145. // We can only set mutating if our owning type is mutating
  17146. if (localVar->mWrittenToId >= closureState.mCaptureStartAccessId)
  17147. {
  17148. if (typeInst->IsValueType())
  17149. {
  17150. if (rootMethodState->mMethodInstance->mMethodDef->mIsMutating)
  17151. methodDef->mIsMutating = true;
  17152. }
  17153. }
  17154. methodDef->mIsStatic = false;
  17155. continue;
  17156. }
  17157. if ((localVar->mIsThis) && (outerClosure != NULL))
  17158. {
  17159. continue;
  17160. }
  17161. if ((localVar->mConstValue) || (localVar->mResolvedType->IsValuelessType()))
  17162. {
  17163. closureState.mConstLocals.push_back(*localVar);
  17164. continue;
  17165. }
  17166. BfClosureCapturedEntry capturedEntry;
  17167. auto capturedType = localVar->mResolvedType;
  17168. bool captureByRef = false;
  17169. if (!capturedType->IsRef())
  17170. {
  17171. if (localVar->mIsThis)
  17172. {
  17173. if ((localVar->mResolvedType->IsValueType()) && (mCurMethodInstance->mMethodDef->HasNoThisSplat()))
  17174. captureByRef = true;
  17175. }
  17176. else if ((!localVar->mIsReadOnly) && (localVar->mWrittenToId >= closureState.mCaptureStartAccessId))
  17177. captureByRef = true;
  17178. }
  17179. else
  17180. {
  17181. if (localVar->mWrittenToId < closureState.mCaptureStartAccessId)
  17182. {
  17183. capturedType = ((BfRefType*)capturedType)->mElementType;
  17184. }
  17185. }
  17186. if (captureByRef)
  17187. {
  17188. //capturedEntry.mIsByReference = true;
  17189. capturedType = CreateRefType(capturedType);
  17190. }
  17191. else
  17192. {
  17193. //capturedEntry.mIsByReference = false;
  17194. }
  17195. capturedEntry.mNameNode = localVar->mNameNode;
  17196. capturedEntry.mType = capturedType;
  17197. capturedEntry.mName = localVar->mName;
  17198. //capturedEntry.mLocalVarDef = localVar;
  17199. capturedEntries.insert(capturedEntry);
  17200. }
  17201. }
  17202. varMethodState = varMethodState->mPrevMethodState;
  17203. if ((varMethodState == NULL) ||
  17204. (varMethodState->mMixinState != NULL) ||
  17205. ((varMethodState->mClosureState != NULL) && (!varMethodState->mClosureState->mCapturing)))
  17206. break;
  17207. }
  17208. }
  17209. for (auto& copyField : closureState.mReferencedOuterClosureMembers)
  17210. {
  17211. auto fieldDef = copyField->GetFieldDef();
  17212. BfClosureCapturedEntry capturedEntry;
  17213. capturedEntry.mName = copyField->GetFieldDef()->mName;
  17214. capturedEntry.mType = copyField->mResolvedType;
  17215. if (capturedEntry.mType->IsRef())
  17216. {
  17217. // Keep by ref
  17218. }
  17219. else if (!fieldDef->mIsReadOnly)
  17220. {
  17221. capturedEntry.mType = CreateRefType(capturedEntry.mType);
  17222. }
  17223. capturedEntries.insert(capturedEntry);
  17224. }
  17225. int captureIdx = 0;
  17226. for (auto& capturedEntry : capturedEntries)
  17227. {
  17228. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries.Add(capturedEntry);
  17229. }
  17230. /*if (isDefaultPass)
  17231. {
  17232. // Insert captured members a params at the start. If we added at the end then it would screw up varargs methods
  17233. int captureIdx = 0;
  17234. for (auto& capturedEntry : capturedEntries)
  17235. {
  17236. methodInstance->mClosureInstanceInfo->mCaptureNodes.Add(BfNodeDynCast<BfIdentifierNode>(capturedEntry.mNameNode));
  17237. BfParameterDef* paramDef = new BfParameterDef();
  17238. paramDef->mName = capturedEntry.mName;
  17239. BfDirectTypeReference* directTypeRef = new BfDirectTypeReference();
  17240. directTypeRef->mType = capturedEntry.mType;
  17241. typeInst->mTypeDef->mDirectAllocNodes.push_back(directTypeRef);
  17242. paramDef->mTypeRef = directTypeRef;
  17243. paramDef->mParamKind = BfParamKind_ImplicitCapture;
  17244. methodDef->mParams.Insert(captureIdx, paramDef);
  17245. captureIdx++;
  17246. }
  17247. }
  17248. else
  17249. {
  17250. auto defaultMethodInstance = methodInstGroup->mDefault;
  17251. methodInstance->mClosureInstanceInfo->mCaptureNodes = defaultMethodInstance->mClosureInstanceInfo->mCaptureNodes;
  17252. }*/
  17253. methodState.Reset();
  17254. closureState.mCapturing = false;
  17255. //////////////////////////////////////////////////////////////////////////
  17256. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, false);
  17257. if (methodInstance->mReturnType != NULL)
  17258. {
  17259. BF_ASSERT(methodInstance->mDisallowCalling);
  17260. // We did a premature declaration (without captures)
  17261. methodInstance->UndoDeclaration();
  17262. methodInstance->mDisallowCalling = false;
  17263. BfLogSysM("LocalMethod %p UndoingDeclaration %p\n", localMethod, methodInstance);
  17264. }
  17265. auto declareModule = this;
  17266. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  17267. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  17268. BF_ASSERT(declareModule != NULL);
  17269. methodInstance->mDeclModule = declareModule;
  17270. _SetupMethodInstance();
  17271. BfLogSysM("LocalMethod %p DoMethodDeclaration %p\n", localMethod, methodInstance);
  17272. declareModule->DoMethodDeclaration(localMethod->mMethodDef->GetMethodDeclaration(), false, false);
  17273. closureState.mReturnType = methodInstance->mReturnType;
  17274. mCompiler->mStats.mMethodsQueued++;
  17275. mCompiler->UpdateCompletion();
  17276. declareModule->mIncompleteMethodCount++;
  17277. mCompiler->mStats.mMethodsProcessed++;
  17278. if (!methodInstance->mIsReified)
  17279. mCompiler->mStats.mUnreifiedMethodsProcessed++;
  17280. auto deferMethodState = rootMethodState;
  17281. // 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)
  17282. if ((!localMethod->mDeclOnly) && (!methodInstance->IsOrInUnspecializedVariation()) &&
  17283. (methodDef->mMethodType != BfMethodType_Mixin) &&
  17284. ((!mWantsIRIgnoreWrites) || (!localMethod->mDidBodyErrorPass)))
  17285. {
  17286. BP_ZONE("BfDeferredLocalMethod:create");
  17287. BfDeferredLocalMethod* deferredLocalMethod = new BfDeferredLocalMethod();
  17288. deferredLocalMethod->mLocalMethod = localMethod;
  17289. deferredLocalMethod->mConstLocals = closureState.mConstLocals;
  17290. deferredLocalMethod->mMethodInstance = methodInstance;
  17291. auto checkMethodState = declMethodState;
  17292. while (checkMethodState != NULL)
  17293. {
  17294. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mActiveDeferredLocalMethod != NULL))
  17295. {
  17296. for (auto& mixinRecord : checkMethodState->mClosureState->mActiveDeferredLocalMethod->mMixinStateRecords)
  17297. deferredLocalMethod->mMixinStateRecords.Add(mixinRecord);
  17298. }
  17299. if (checkMethodState->mMixinState != NULL)
  17300. {
  17301. BfMixinRecord mixinRecord;
  17302. mixinRecord.mSource = checkMethodState->mMixinState->mSource;
  17303. deferredLocalMethod->mMixinStateRecords.Add(mixinRecord);
  17304. }
  17305. checkMethodState = checkMethodState->mPrevMethodState;
  17306. }
  17307. rootMethodState->mDeferredLocalMethods.Add(deferredLocalMethod);
  17308. }
  17309. mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  17310. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  17311. mBfIRBuilder->RestoreDebugLocation();
  17312. if (methodInstance == localMethod->mMethodInstanceGroup->mDefault)
  17313. {
  17314. auto checkMethodState = mCurMethodState;
  17315. while (checkMethodState != NULL)
  17316. {
  17317. BfLocalMethod* nextLocalMethod = NULL;
  17318. if (checkMethodState->mLocalMethodMap.TryGetValue(localMethod->mMethodName, &nextLocalMethod))
  17319. {
  17320. while (nextLocalMethod != NULL)
  17321. {
  17322. auto checkLocalMethod = nextLocalMethod;
  17323. nextLocalMethod = nextLocalMethod->mNextWithSameName;
  17324. if (checkLocalMethod == localMethod)
  17325. continue;
  17326. if (checkLocalMethod->mMethodInstanceGroup == NULL)
  17327. continue;
  17328. auto checkMethodInstance = checkLocalMethod->mMethodInstanceGroup->mDefault;
  17329. if (checkMethodInstance == NULL)
  17330. continue; // Not generated yet
  17331. if (CompareMethodSignatures(localMethod->mMethodInstanceGroup->mDefault, checkMethodInstance))
  17332. {
  17333. auto bfError = Fail("Method already declared with the same parameter types", methodInstance->mMethodDef->GetRefNode(), true);
  17334. if (bfError != NULL)
  17335. mCompiler->mPassInstance->MoreInfo("First declaration", checkMethodInstance->mMethodDef->GetRefNode());
  17336. }
  17337. }
  17338. }
  17339. checkMethodState = checkMethodState->mPrevMethodState;
  17340. }
  17341. }
  17342. return BfModuleMethodInstance(methodInstance);
  17343. }
  17344. int BfModule::GetLocalInferrableGenericArgCount(BfMethodDef* methodDef)
  17345. {
  17346. if ((!methodDef->mIsLocalMethod) || (methodDef->mGenericParams.size() == 0))
  17347. return 0;
  17348. auto rootMethodState = mCurMethodState->GetRootMethodState();
  17349. int rootMethodGenericParamCount = 0;
  17350. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  17351. rootMethodGenericParamCount = (int)rootMethodState->mMethodInstance->mMethodInfoEx->mGenericParams.size();
  17352. if (mCurMethodInstance == NULL)
  17353. return rootMethodGenericParamCount;
  17354. if ((mCurMethodInstance->mMethodInfoEx == NULL) || (mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo == NULL))
  17355. return rootMethodGenericParamCount;
  17356. BfLocalMethod* callerLocalMethod = mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod;
  17357. if (callerLocalMethod == NULL)
  17358. return rootMethodGenericParamCount;
  17359. BfLocalMethod* calledLocalMethod = NULL;
  17360. rootMethodState->mLocalMethodCache.TryGetValue(methodDef->mName, &calledLocalMethod);
  17361. while ((calledLocalMethod != NULL) && (callerLocalMethod != NULL))
  17362. {
  17363. if (calledLocalMethod->mOuterLocalMethod == callerLocalMethod)
  17364. return (int)callerLocalMethod->mMethodDef->mGenericParams.size();
  17365. callerLocalMethod = calledLocalMethod->mOuterLocalMethod;
  17366. }
  17367. return rootMethodGenericParamCount;
  17368. }
  17369. void BfModule::GetMethodCustomAttributes(BfMethodInstance* methodInstance)
  17370. {
  17371. auto methodDef = methodInstance->mMethodDef;
  17372. auto customAttributes = methodInstance->GetCustomAttributes();
  17373. if (customAttributes != NULL)
  17374. return;
  17375. auto methodDeclaration = methodDef->GetMethodDeclaration();
  17376. auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration();
  17377. auto typeInstance = methodInstance->GetOwner();
  17378. BfTypeState typeState(typeInstance);
  17379. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  17380. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  17381. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  17382. BfAttributeTargets attrTarget = ((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend)) ? BfAttributeTargets_Constructor : BfAttributeTargets_Method;
  17383. BfAttributeDirective* attributeDirective = NULL;
  17384. if (methodDeclaration != NULL)
  17385. attributeDirective = methodDeclaration->mAttributes;
  17386. else if (propertyMethodDeclaration != NULL)
  17387. {
  17388. attributeDirective = propertyMethodDeclaration->mAttributes;
  17389. if (auto exprBody = BfNodeDynCast<BfPropertyBodyExpression>(propertyMethodDeclaration->mPropertyDeclaration->mDefinitionBlock))
  17390. {
  17391. attributeDirective = propertyMethodDeclaration->mPropertyDeclaration->mAttributes;
  17392. attrTarget = (BfAttributeTargets)(BfAttributeTargets_Property | BfAttributeTargets_Method);
  17393. }
  17394. }
  17395. if (attributeDirective != NULL)
  17396. {
  17397. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes == NULL)
  17398. methodInstance->mMethodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  17399. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes = GetCustomAttributes(attributeDirective, attrTarget);
  17400. }
  17401. customAttributes = methodInstance->GetCustomAttributes();
  17402. if (customAttributes == NULL)
  17403. {
  17404. auto owner = methodInstance->GetOwner();
  17405. if ((owner->IsDelegate()) || (owner->IsFunction()))
  17406. customAttributes = owner->mCustomAttributes;
  17407. }
  17408. methodInstance->mCallingConvention = methodDef->mCallingConvention;
  17409. if (customAttributes != NULL)
  17410. {
  17411. auto linkNameAttr = customAttributes->Get(typeInstance->mModule->mCompiler->mCallingConventionAttributeTypeDef);
  17412. if (linkNameAttr != NULL)
  17413. {
  17414. if (linkNameAttr->mCtorArgs.size() == 1)
  17415. {
  17416. auto constant = typeInstance->mConstHolder->GetConstant(linkNameAttr->mCtorArgs[0]);
  17417. if (constant != NULL)
  17418. methodInstance->mCallingConvention = (BfCallingConvention)constant->mInt32;
  17419. }
  17420. }
  17421. }
  17422. }
  17423. void BfModule::SetupIRFunction(BfMethodInstance* methodInstance, StringImpl& mangledName, bool isTemporaryFunc, bool* outIsIntrinsic)
  17424. {
  17425. if (methodInstance->GetImportCallKind() == BfImportCallKind_GlobalVar)
  17426. {
  17427. // Don't create a func
  17428. return;
  17429. }
  17430. auto typeInstance = methodInstance->GetOwner();
  17431. auto methodDef = methodInstance->mMethodDef;
  17432. BfIRFunctionType funcType = mBfIRBuilder->MapMethod(methodInstance);
  17433. // Don't set these pointers during resolve pass because they may become invalid if it's just a temporary autocomplete method
  17434. if (mCompiler->mResolvePassData == NULL)
  17435. {
  17436. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mIsStatic))
  17437. {
  17438. typeInstance->mHasStaticInitMethod = true;
  17439. }
  17440. if ((methodDef->mMethodType == BfMethodType_Dtor) && (methodDef->mIsStatic))
  17441. {
  17442. typeInstance->mHasStaticDtorMethod = true;
  17443. }
  17444. if ((methodDef->mMethodType == BfMethodType_Normal) && (methodDef->mIsStatic) && (methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC))
  17445. {
  17446. typeInstance->mHasStaticMarkMethod = true;
  17447. }
  17448. if ((methodDef->mMethodType == BfMethodType_Normal) && (methodDef->mIsStatic) && (methodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS))
  17449. {
  17450. typeInstance->mHasTLSFindMethod = true;
  17451. }
  17452. }
  17453. if (isTemporaryFunc)
  17454. {
  17455. BF_ASSERT(((mCompiler->mIsResolveOnly) && (mCompiler->mResolvePassData->mAutoComplete != NULL)) ||
  17456. (methodInstance->GetOwner()->mDefineState < BfTypeDefineState_Defined));
  17457. mangledName = "autocomplete_tmp";
  17458. }
  17459. if (!mBfIRBuilder->mIgnoreWrites)
  17460. {
  17461. BfIRFunction prevFunc;
  17462. // Remove old version (if we have one)
  17463. prevFunc = mBfIRBuilder->GetFunction(mangledName);
  17464. if (prevFunc)
  17465. {
  17466. if (methodDef->mIsExtern)
  17467. {
  17468. // Allow this
  17469. BfLogSysM("Function collision allowed multiple extern functions for %p: %d\n", methodInstance, prevFunc.mId);
  17470. }
  17471. else if (typeInstance->IsIRFuncUsed(prevFunc))
  17472. {
  17473. // We can have a collision of names when we have generic methods that differ only in
  17474. // their constraints, but they should only collide in their unspecialized form
  17475. // since only one will be chosen for a given concrete type
  17476. mCurMethodInstance->mMangleWithIdx = true;
  17477. mangledName.Clear();
  17478. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  17479. prevFunc = mBfIRBuilder->GetFunction(mangledName);
  17480. BfLogSysM("Function collision forced mangleWithIdx for %p: %d\n", methodInstance, prevFunc.mId);
  17481. }
  17482. else
  17483. {
  17484. BfLogSysM("Function collision erased prevFunc %p: %d\n", methodInstance, prevFunc.mId);
  17485. mBfIRBuilder->Func_EraseFromParent(prevFunc);
  17486. }
  17487. }
  17488. }
  17489. if (typeInstance != mContext->mBfObjectType)
  17490. {
  17491. // Only allow attributes on System.Object methods that can be handled inside the DefBuilder
  17492. GetMethodCustomAttributes(methodInstance);
  17493. }
  17494. // if (prevFunc)
  17495. // {
  17496. // if (methodDef->mIsExtern)
  17497. // {
  17498. // BfLogSysM("Reusing function for %p: %d\n", methodInstance, prevFunc.mId);
  17499. // methodInstance->mIRFunction = prevFunc;
  17500. // }
  17501. // else
  17502. // {
  17503. // if ((methodInstance->IsSpecializedByAutoCompleteMethod()) ||
  17504. // ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mResolveType >= BfResolveType_GoToDefinition)))
  17505. // {
  17506. // // If we're doing re-pass over the methods for something like BfResolveType_ShowFileSymbolReferences, then allow this collision
  17507. // BfLogSysM("Ignoring function name collision\n");
  17508. // }
  17509. // else
  17510. // {
  17511. // if (methodDef->mMethodDeclaration == NULL)
  17512. // {
  17513. // AssertErrorState();
  17514. // }
  17515. // else
  17516. // {
  17517. // BF_ASSERT(mIsSpecialModule);
  17518. // if ((mCompiler->mRevision == 1) && (HasCompiledOutput()))
  17519. // {
  17520. // // We shouldn't have name collisions on the first run!
  17521. // AssertErrorState();
  17522. // }
  17523. // }
  17524. // }
  17525. // BfLogSysM("Before erase\n");
  17526. // mBfIRBuilder->Func_EraseFromParent(prevFunc);
  17527. // }
  17528. // }
  17529. bool isIntrinsic = false;
  17530. if (!methodInstance->mIRFunction)
  17531. {
  17532. BfIRFunction func;
  17533. bool wantsLLVMFunc = ((!typeInstance->IsUnspecializedType()) && (!methodDef->IsEmptyPartial())) && (funcType);
  17534. /*if (mCurTypeInstance->mTypeDef->mName->ToString() == "ClassA")
  17535. {
  17536. if (!mIsReified)
  17537. wantsLLVMFunc = false;
  17538. }*/
  17539. if (wantsLLVMFunc)
  17540. {
  17541. func = GetIntrinsic(methodInstance, true);
  17542. if (func)
  17543. {
  17544. isIntrinsic = true;
  17545. }
  17546. else
  17547. {
  17548. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, mangledName);
  17549. BfLogSysM("Creating FuncId:%d %s in module %p\n", func.mId, mangledName.c_str(), this);
  17550. if (methodInstance->mAlwaysInline)
  17551. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_AlwaysInline);
  17552. // if (prevFunc)
  17553. // BfLogSysM("Removing Func %d, replacing with %d\n", prevFunc.mId, func.mId);
  17554. }
  17555. methodInstance->mIRFunction = func;
  17556. //if (!ignoreWrites)
  17557. //BF_ASSERT(!func.IsFake());
  17558. }
  17559. }
  17560. if (outIsIntrinsic != NULL)
  17561. *outIsIntrinsic = isIntrinsic;
  17562. if (!isIntrinsic)
  17563. SetupIRMethod(methodInstance, methodInstance->mIRFunction, methodInstance->mAlwaysInline);
  17564. }
  17565. void BfModule::CheckHotMethod(BfMethodInstance* methodInstance, const StringImpl& inMangledName)
  17566. {
  17567. if (methodInstance->mHotMethod != NULL)
  17568. return;
  17569. if ((mCompiler->mOptions.mAllowHotSwapping) && (!methodInstance->mIsUnspecialized))
  17570. {
  17571. auto srcTypeInst = methodInstance->GetOwner();
  17572. StringT<128> mangledName = inMangledName;
  17573. if (mangledName.IsEmpty())
  17574. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  17575. // We always keep the current primary method at the same address
  17576. BfHotMethod* hotMethod;
  17577. BfHotMethod** hotMethodPtr;
  17578. if (mCompiler->mHotData->mMethodMap.TryAdd(mangledName, NULL, &hotMethodPtr))
  17579. {
  17580. hotMethod = new BfHotMethod();
  17581. *hotMethodPtr = hotMethod;
  17582. hotMethod->mRefCount = 1;
  17583. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  17584. #ifdef BF_DBG_HOTMETHOD_IDX
  17585. static int sMethodIdx = 0;
  17586. hotMethod->mMethodIdx = sMethodIdx++;
  17587. #endif
  17588. BfLogSysM("HotMethodData %p created for method %p %s - %s\n", hotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  17589. }
  17590. else
  17591. {
  17592. hotMethod = *hotMethodPtr;
  17593. if ((hotMethod->mFlags & BfHotDepDataFlag_IsBound) != 0)
  17594. {
  17595. // This is a duplicate mangled name - we link to this new entry via a 'BfHotDupMethod'
  17596. auto prevHotMethod = *hotMethodPtr;
  17597. hotMethod = new BfHotMethod();
  17598. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  17599. BfHotDupMethod* hotDupMethod = new BfHotDupMethod(hotMethod);
  17600. hotDupMethod->mRefCount++;
  17601. prevHotMethod->mReferences.Add(hotDupMethod);
  17602. prevHotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_HasDup);
  17603. BfLogSysM("HotMethodData %p (duplicate of %p) created for method %p %s - %s\n", hotMethod, prevHotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  17604. }
  17605. else if (mCompiler->IsHotCompile())
  17606. {
  17607. // Link the previous version into the mPrevVersion
  17608. BfHotMethod* prevMethod = new BfHotMethod();
  17609. prevMethod->mRefCount = 1;
  17610. prevMethod->mPrevVersion = hotMethod->mPrevVersion;
  17611. hotMethod->mPrevVersion = prevMethod;
  17612. prevMethod->mSrcTypeVersion = hotMethod->mSrcTypeVersion;
  17613. hotMethod->mSrcTypeVersion = NULL;
  17614. prevMethod->mFlags = hotMethod->mFlags;
  17615. hotMethod->mFlags = BfHotDepDataFlag_IsBound;
  17616. hotMethod->mReferences.MoveTo(prevMethod->mReferences);
  17617. #ifdef BF_DBG_HOTMETHOD_NAME
  17618. prevMethod->mMangledName = hotMethod->mMangledName;
  17619. #endif
  17620. BfLogSysM("HotMethodData %p created for prevmethod of %p for method %p %s\n", prevMethod, hotMethod, methodInstance, MethodToString(methodInstance).c_str());
  17621. }
  17622. else
  17623. {
  17624. BfLogSysM("HotMethodData %p used for method %p %s - %s\n", hotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  17625. hotMethod->Clear(true);
  17626. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  17627. }
  17628. }
  17629. if (methodInstance->mIsClosure)
  17630. {
  17631. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_RetainMethodWithoutBinding);
  17632. }
  17633. hotMethod->mSrcTypeVersion = srcTypeInst->mHotTypeData->GetLatestVersion();
  17634. hotMethod->mSrcTypeVersion->mRefCount++;
  17635. hotMethod->mRefCount++;
  17636. #ifdef BF_DBG_HOTMETHOD_NAME
  17637. hotMethod->mMangledName = mangledName;
  17638. #endif
  17639. if ((methodInstance->mMethodInstanceGroup->IsImplemented()) && (!mCompiler->IsHotCompile()))
  17640. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsOriginalBuild);
  17641. methodInstance->mHotMethod = hotMethod;
  17642. }
  17643. }
  17644. static void StackOverflow()
  17645. {
  17646. int i = 0;
  17647. if (i == 0)
  17648. StackOverflow();
  17649. }
  17650. // methodDeclaration is NULL for default constructors
  17651. void BfModule::DoMethodDeclaration(BfMethodDeclaration* methodDeclaration, bool isTemporaryFunc, bool addToWorkList)
  17652. {
  17653. BP_ZONE("BfModule::BfMethodDeclaration");
  17654. // We could trigger a DoMethodDeclaration from a const resolver or other location, so we reset it here
  17655. // to effectively make mIgnoreWrites method-scoped
  17656. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mWantsIRIgnoreWrites || mCurMethodInstance->mIsUnspecialized || mCurTypeInstance->mResolvingVarField);
  17657. SetAndRestoreValue<bool> prevIsCapturingMethodMatchInfo;
  17658. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, NULL);
  17659. if (mCompiler->IsAutocomplete())
  17660. prevIsCapturingMethodMatchInfo.Init(mCompiler->mResolvePassData->mAutoComplete->mIsCapturingMethodMatchInfo, false);
  17661. if (mCurMethodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference)
  17662. mCurMethodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingReference;
  17663. // If we are doing this then we may end up creating methods when var types are unknown still, failing on splat/zero-sized info
  17664. BF_ASSERT((!mCurTypeInstance->mResolvingVarField) || (mBfIRBuilder->mIgnoreWrites));
  17665. bool ignoreWrites = mBfIRBuilder->mIgnoreWrites;
  17666. if ((!isTemporaryFunc) && (mCurTypeInstance->mDefineState < BfTypeDefineState_Defined))
  17667. {
  17668. BF_ASSERT(mContext->mResolvingVarField);
  17669. isTemporaryFunc = true;
  17670. }
  17671. if (mAwaitingInitFinish)
  17672. FinishInit();
  17673. auto typeInstance = mCurTypeInstance;
  17674. auto typeDef = typeInstance->mTypeDef;
  17675. auto methodDef = mCurMethodInstance->mMethodDef;
  17676. BF_ASSERT(methodDef->mName != "__ASSERTNAME");
  17677. if (methodDef->mName == "__FATALERRORNAME")
  17678. BFMODULE_FATAL(this, "__FATALERRORNAME");
  17679. if (methodDef->mName == "__STACKOVERFLOW")
  17680. StackOverflow();
  17681. if (typeInstance->IsClosure())
  17682. {
  17683. if (methodDef->mName == "Invoke")
  17684. return;
  17685. }
  17686. auto methodInstance = mCurMethodInstance;
  17687. if ((methodInstance->IsSpecializedByAutoCompleteMethod()) || (mCurTypeInstance->IsFunction()))
  17688. addToWorkList = false;
  17689. bool hasNonGenericParams = false;
  17690. bool hasGenericParams = false;
  17691. int dependentGenericStartIdx = 0;
  17692. if (methodDef->mIsLocalMethod)
  17693. {
  17694. // If we're a local generic method inside an outer generic method, we can still be considered unspecialized
  17695. // if our outer method's generic args are specialized but ours are unspecialized. This is because locals get
  17696. // instantiated uniquely for each specialized or unspecialized pass through the outer method, but the local
  17697. // method still 'inherits' the outer's generic arguments -- but we still need to make an unspecialized pass
  17698. // over the local method each time
  17699. auto rootMethodInstance = prevMethodState.mPrevVal->GetRootMethodState()->mMethodInstance;
  17700. dependentGenericStartIdx = 0;
  17701. if (rootMethodInstance->mMethodInfoEx != NULL)
  17702. dependentGenericStartIdx = (int)rootMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  17703. methodInstance->mIsUnspecialized = rootMethodInstance->mIsUnspecialized;
  17704. methodInstance->mIsUnspecializedVariation = rootMethodInstance->mIsUnspecializedVariation;
  17705. }
  17706. for (int genericArgIdx = dependentGenericStartIdx; genericArgIdx < (int) methodInstance->GetNumGenericArguments(); genericArgIdx++)
  17707. {
  17708. auto genericArgType = methodInstance->mMethodInfoEx->mMethodGenericArguments[genericArgIdx];
  17709. if (genericArgType->IsGenericParam())
  17710. {
  17711. hasGenericParams = true;
  17712. auto genericParam = (BfGenericParamType*)genericArgType;
  17713. methodInstance->mIsUnspecialized = true;
  17714. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  17715. methodInstance->mIsUnspecializedVariation = true;
  17716. }
  17717. else
  17718. {
  17719. hasNonGenericParams = true;
  17720. if (genericArgType->IsUnspecializedType())
  17721. {
  17722. methodInstance->mIsUnspecialized = true;
  17723. methodInstance->mIsUnspecializedVariation = true;
  17724. }
  17725. }
  17726. }
  17727. if ((hasGenericParams) && (hasNonGenericParams))
  17728. {
  17729. methodInstance->mIsUnspecializedVariation = true;
  17730. }
  17731. if (typeInstance->IsUnspecializedType())
  17732. {
  17733. // A specialized method within an unspecialized type is considered an unspecialized variation -- in the sense that we don't
  17734. // actually want to do method processing on it
  17735. if ((!methodInstance->mIsUnspecialized) && (methodInstance->GetNumGenericArguments() != 0))
  17736. methodInstance->mIsUnspecializedVariation = true;
  17737. methodInstance->mIsUnspecialized = true;
  17738. }
  17739. //methodInstance->mIsUnspecializedVariation |= typeInstance->IsUnspecializedTypeVariation();
  17740. for (auto genericParamDef : methodDef->mGenericParams)
  17741. {
  17742. if (mCompiler->IsAutocomplete())
  17743. {
  17744. auto autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  17745. //autoComplete->CheckTypeRef()
  17746. }
  17747. }
  17748. if (methodInstance->mIsUnspecializedVariation)
  17749. {
  17750. }
  17751. if (methodInstance->mIsUnspecializedVariation)
  17752. BF_ASSERT(methodInstance->mIsUnspecialized);
  17753. if (methodDef->mMethodType == BfMethodType_Mixin)
  17754. methodInstance->mIsUnspecialized = true;
  17755. if (methodInstance->mIsUnspecialized)
  17756. {
  17757. //BF_ASSERT(methodInstance->mDeclModule == methodInstance->GetOwner()->mModule);
  17758. }
  17759. BfAutoComplete* bfAutocomplete = NULL;
  17760. if (mCompiler->mResolvePassData != NULL)
  17761. bfAutocomplete = mCompiler->mResolvePassData->mAutoComplete;
  17762. if (methodInstance->mMethodInfoEx != NULL)
  17763. {
  17764. BfTypeInstance* unspecializedTypeInstance = NULL;
  17765. for (int genericParamIdx = 0; genericParamIdx < (int)methodInstance->mMethodInfoEx->mGenericParams.size(); genericParamIdx++)
  17766. {
  17767. auto genericParam = methodInstance->mMethodInfoEx->mGenericParams[genericParamIdx];
  17768. if (genericParamIdx < (int)methodDef->mGenericParams.size())
  17769. {
  17770. genericParam->mExternType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  17771. }
  17772. else
  17773. {
  17774. auto externConstraintDef = genericParam->GetExternConstraintDef();
  17775. // if (unspecializedTypeInstance == NULL)
  17776. // unspecializedTypeInstance = GetUnspecializedTypeInstance(mCurTypeInstance);
  17777. //
  17778. // // Resolve in the unspecialized type, then resolve the generic later. This fixes ambiguity where the type is specialized by a method generic arg
  17779. // {
  17780. // SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, unspecializedTypeInstance);
  17781. // genericParam->mExternType = ResolveTypeRef(externConstraintDef->mTypeRef);
  17782. // }
  17783. genericParam->mExternType = ResolveTypeRef(externConstraintDef->mTypeRef);
  17784. auto autoComplete = mCompiler->GetAutoComplete();
  17785. if (autoComplete != NULL)
  17786. autoComplete->CheckTypeRef(externConstraintDef->mTypeRef, false);
  17787. if (genericParam->mExternType != NULL)
  17788. {
  17789. //
  17790. }
  17791. else
  17792. genericParam->mExternType = GetPrimitiveType(BfTypeCode_Var);
  17793. }
  17794. ResolveGenericParamConstraints(genericParam, methodInstance->mIsUnspecialized);
  17795. if (genericParamIdx < (int)methodDef->mGenericParams.size())
  17796. {
  17797. auto genericParamDef = methodDef->mGenericParams[genericParamIdx];
  17798. if (bfAutocomplete != NULL)
  17799. {
  17800. for (auto nameNode : genericParamDef->mNameNodes)
  17801. {
  17802. HandleMethodGenericParamRef(nameNode, typeDef, methodDef, genericParamIdx);
  17803. }
  17804. }
  17805. }
  17806. }
  17807. for (auto genericParam : methodInstance->mMethodInfoEx->mGenericParams)
  17808. {
  17809. for (auto constraintTypeInst : genericParam->mInterfaceConstraints)
  17810. AddDependency(constraintTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  17811. if (genericParam->mTypeConstraint != NULL)
  17812. AddDependency(genericParam->mTypeConstraint, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  17813. }
  17814. }
  17815. if ((methodInstance->mIsAutocompleteMethod) && (methodDeclaration != NULL) && (!methodInstance->IsSpecializedGenericMethod()) && (methodDef->mIdx >= 0))
  17816. {
  17817. auto autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  17818. BfAstNode* nameNode = methodDeclaration->mNameNode;
  17819. if (nameNode == NULL)
  17820. {
  17821. if (auto ctorDeclaration = BfNodeDynCast<BfConstructorDeclaration>(methodDeclaration))
  17822. nameNode = ctorDeclaration->mThisToken;
  17823. }
  17824. if (autoComplete->IsAutocompleteNode(nameNode))
  17825. {
  17826. autoComplete->mInsertStartIdx = nameNode->GetSrcStart();
  17827. autoComplete->mInsertEndIdx = nameNode->GetSrcEnd();
  17828. autoComplete->mDefType = typeDef;
  17829. autoComplete->mDefMethod = methodDef;
  17830. autoComplete->SetDefinitionLocation(nameNode);
  17831. if (methodDef->mIsOverride)
  17832. {
  17833. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  17834. {
  17835. auto& ventry = typeInstance->mVirtualMethodTable[virtIdx];
  17836. if (ventry.mDeclaringMethod.mMethodNum == -1)
  17837. continue;
  17838. BfMethodInstance* virtMethod = ventry.mImplementingMethod;
  17839. if (virtMethod != NULL)
  17840. {
  17841. auto virtMethodDeclaration = virtMethod->mMethodDef->GetMethodDeclaration();
  17842. if ((virtMethod->GetOwner() == typeInstance) && (virtMethodDeclaration != NULL) &&
  17843. (virtMethodDeclaration->GetSrcStart() == methodDeclaration->GetSrcStart()))
  17844. {
  17845. // Is matching method
  17846. if (virtIdx < (int)typeInstance->mBaseType->mVirtualMethodTable.size())
  17847. {
  17848. auto baseType = typeInstance->mBaseType;
  17849. if (baseType != NULL)
  17850. {
  17851. while ((baseType->mBaseType != NULL) && (virtIdx < baseType->mBaseType->mVirtualMethodTableSize))
  17852. baseType = baseType->mBaseType;
  17853. BfMethodInstance* baseVirtMethod = baseType->mVirtualMethodTable[virtIdx].mImplementingMethod;
  17854. autoComplete->SetDefinitionLocation(baseVirtMethod->mMethodDef->GetRefNode(), true);
  17855. autoComplete->mDefType = baseType->mTypeDef;
  17856. autoComplete->mDefMethod = baseVirtMethod->mMethodDef;
  17857. }
  17858. }
  17859. break;
  17860. }
  17861. }
  17862. }
  17863. }
  17864. }
  17865. }
  17866. bool reportErrors = true;
  17867. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  17868. reportErrors = true;
  17869. // Only the defining contexts needs to report errors here
  17870. SetAndRestoreValue<bool> prevReporErrors(mReportErrors, reportErrors);
  17871. if (methodDef->mMethodType == BfMethodType_Dtor)
  17872. {
  17873. if (methodDef->mIsStatic)
  17874. {
  17875. }
  17876. else
  17877. {
  17878. if ((typeInstance->IsStruct()) || (typeInstance->IsTypedPrimitive()))
  17879. {
  17880. BfAstNode* refNode = methodDeclaration;
  17881. if (refNode == NULL)
  17882. {
  17883. // Whatever caused this ctor to be generated should have caused another failure
  17884. // But that failure might not be generated until the ctor is generated
  17885. }
  17886. else
  17887. {
  17888. auto dtorDecl = BfNodeDynCast<BfDestructorDeclaration>(methodDeclaration);
  17889. if (dtorDecl != NULL)
  17890. refNode = dtorDecl->mThisToken;
  17891. Fail("Structs cannot have destructors", refNode);
  17892. }
  17893. }
  17894. auto methodDeclaration = methodDef->GetMethodDeclaration();
  17895. if ((methodDeclaration != NULL) && (methodDeclaration->mVirtualSpecifier != NULL) &&
  17896. (mCurTypeInstance != mContext->mBfObjectType))
  17897. {
  17898. Fail("Virtual specifier is not required, all destructors are implicitly virtual.", methodDeclaration->mVirtualSpecifier);
  17899. }
  17900. }
  17901. }
  17902. BfType* resolvedReturnType = NULL;
  17903. if (((methodDef->mMethodType == BfMethodType_Normal) || (methodDef->mMethodType == BfMethodType_Extension) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend) ||
  17904. (methodDef->mMethodType == BfMethodType_PropertyGetter) || (methodDef->mMethodType == BfMethodType_Operator)) &&
  17905. (methodDef->mReturnTypeRef != NULL))
  17906. {
  17907. SetAndRestoreValue<bool> prevIngoreErrors(mIgnoreErrors, mIgnoreErrors || (methodDef->GetPropertyDeclaration() != NULL));
  17908. resolvedReturnType = ResolveTypeRef(methodDef->mReturnTypeRef, BfPopulateType_Declaration,
  17909. (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_AllowRef | BfResolveTypeRefFlag_AllowRefGeneric));
  17910. if ((resolvedReturnType != NULL) && (resolvedReturnType->IsVar()) && (methodDef->mMethodType != BfMethodType_Mixin))
  17911. {
  17912. Fail("Cannot declare var return types", methodDef->mReturnTypeRef);
  17913. resolvedReturnType = GetPrimitiveType(BfTypeCode_Var);
  17914. }
  17915. if (resolvedReturnType == NULL)
  17916. resolvedReturnType = GetPrimitiveType(BfTypeCode_Var);
  17917. }
  17918. else
  17919. {
  17920. resolvedReturnType = ResolveTypeDef(mSystem->mTypeVoid);
  17921. }
  17922. BF_ASSERT(resolvedReturnType != NULL);
  17923. mCurMethodInstance->mReturnType = resolvedReturnType;
  17924. //TODO: We used to NOT add the return value dependency for specialized methods, but when we have types that are
  17925. // specialized based on the method's generic param then they can get deleted if no one else has referred to them (yet)
  17926. //if (!methodInstance->IsSpecializedGenericMethod())
  17927. AddDependency(resolvedReturnType, typeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  17928. if (methodDef->mExplicitInterface != NULL)
  17929. {
  17930. auto autoComplete = mCompiler->GetAutoComplete();
  17931. if (autoComplete != NULL)
  17932. autoComplete->CheckTypeRef(methodDef->mExplicitInterface, false);
  17933. auto explicitType = ResolveTypeRef(methodDef->mExplicitInterface, BfPopulateType_Declaration);
  17934. BfTypeInstance* explicitInterface = NULL;
  17935. if (explicitType != NULL)
  17936. explicitInterface = explicitType->ToTypeInstance();
  17937. if (explicitInterface != NULL)
  17938. {
  17939. mCurMethodInstance->GetMethodInfoEx()->mExplicitInterface = explicitInterface->ToTypeInstance();
  17940. if (autoComplete != NULL)
  17941. {
  17942. BfTokenNode* dotToken = NULL;
  17943. BfAstNode* nameNode = NULL;
  17944. if (auto methodDeclaration = BfNodeDynCast<BfMethodDeclaration>(methodDef->mMethodDeclaration))
  17945. {
  17946. dotToken = methodDeclaration->mExplicitInterfaceDotToken;
  17947. nameNode = methodDeclaration->mNameNode;
  17948. }
  17949. autoComplete->CheckExplicitInterface(explicitInterface, dotToken, nameNode);
  17950. }
  17951. }
  17952. if ((mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mExplicitInterface != NULL))
  17953. {
  17954. bool interfaceFound = false;
  17955. for (auto ifaceInst : typeInstance->mInterfaces)
  17956. interfaceFound |= ifaceInst.mInterfaceType == mCurMethodInstance->mMethodInfoEx->mExplicitInterface;
  17957. if (!interfaceFound)
  17958. {
  17959. if (methodDef->mMethodDeclaration != NULL)
  17960. Fail("Containing class has not declared to implement this interface", methodDef->mMethodDeclaration);
  17961. else
  17962. {
  17963. // For property decls, we should have already given the error during type population
  17964. if (mCompiler->mRevision == 1)
  17965. AssertErrorState();
  17966. }
  17967. }
  17968. }
  17969. }
  17970. bool isThisStruct = mCurTypeInstance->IsStruct();
  17971. BfType* thisType = NULL;
  17972. if ((!methodDef->mIsStatic) && (!mCurTypeInstance->IsValuelessType()))
  17973. {
  17974. if ((isThisStruct) || (mCurTypeInstance->IsTypedPrimitive()))
  17975. {
  17976. thisType = mCurTypeInstance;
  17977. if (thisType == NULL)
  17978. return;
  17979. if ((thisType->IsSplattable()) && (!methodDef->HasNoThisSplat()))
  17980. {
  17981. BfTypeUtils::SplatIterate([&](BfType* checkType)
  17982. {
  17983. PopulateType(checkType, BfPopulateType_Data);
  17984. }, thisType);
  17985. }
  17986. }
  17987. else
  17988. {
  17989. thisType = mCurTypeInstance;
  17990. PopulateType(thisType, BfPopulateType_Declaration);
  17991. }
  17992. }
  17993. int implicitParamCount = 0;
  17994. if ((mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo != NULL))
  17995. implicitParamCount = (int)methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries.size();
  17996. methodInstance->mMethodDef->mParams.Reserve((int)methodDef->mParams.size());
  17997. bool hadDelegateParams = false;
  17998. bool hadParams = false;
  17999. for (int paramIdx = 0; paramIdx < (int)methodDef->mParams.size() + implicitParamCount; paramIdx++)
  18000. {
  18001. BfClosureCapturedEntry* closureCaptureEntry = NULL;
  18002. BfParameterDef* paramDef = NULL;
  18003. int paramDefIdx = -1;
  18004. if (paramIdx < implicitParamCount)
  18005. closureCaptureEntry = &methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries[paramIdx];
  18006. else
  18007. {
  18008. paramDefIdx = paramIdx - implicitParamCount;
  18009. paramDef = methodDef->mParams[paramDefIdx];
  18010. }
  18011. if (hadParams)
  18012. break;
  18013. if ((paramDef != NULL) && (paramDef->mParamKind == BfParamKind_VarArgs))
  18014. continue;
  18015. if ((paramDef != NULL) && (mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL) &&
  18016. (paramDef->mParamKind != BfParamKind_AppendIdx))
  18017. mCompiler->mResolvePassData->mAutoComplete->CheckTypeRef(paramDef->mTypeRef, false);
  18018. if ((paramDef != NULL) && (paramDef->mParamDeclaration != NULL) && (paramDef->mParamDeclaration->mAttributes != NULL))
  18019. {
  18020. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes == NULL)
  18021. methodInstance->mMethodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  18022. while ((int)methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.size() < paramIdx)
  18023. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.push_back(NULL);
  18024. auto customAttributes = GetCustomAttributes(paramDef->mParamDeclaration->mAttributes, BfAttributeTargets_Parameter);
  18025. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.push_back(customAttributes);
  18026. }
  18027. BfType* resolvedParamType = NULL;
  18028. if (closureCaptureEntry != NULL)
  18029. resolvedParamType = closureCaptureEntry->mType;
  18030. else if (paramDef->mTypeRef->IsA<BfLetTypeReference>())
  18031. {
  18032. Fail("Cannot declare 'let' parameters", paramDef->mTypeRef);
  18033. resolvedParamType = mContext->mBfObjectType;
  18034. }
  18035. else if (paramDef->mTypeRef->IsA<BfVarTypeReference>())
  18036. {
  18037. if (methodDef->mMethodType != BfMethodType_Mixin)
  18038. {
  18039. Fail("Cannot declare var parameters", paramDef->mTypeRef);
  18040. resolvedParamType = mContext->mBfObjectType;
  18041. }
  18042. else
  18043. resolvedParamType = GetPrimitiveType(BfTypeCode_Var);
  18044. }
  18045. BfType* unresolvedParamType = resolvedParamType;
  18046. bool wasGenericParam = false;
  18047. if (resolvedParamType == NULL)
  18048. {
  18049. BfResolveTypeRefFlags resolveFlags = (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_AllowRef | BfResolveTypeRefFlag_AllowRefGeneric | BfResolveTypeRefFlag_AllowGenericMethodParamConstValue);
  18050. if (paramDef->mParamKind == BfParamKind_ExplicitThis)
  18051. resolveFlags = (BfResolveTypeRefFlags)(resolveFlags | BfResolveTypeRefFlag_NoWarnOnMut);
  18052. resolvedParamType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration, resolveFlags);
  18053. if ((paramDef->mParamKind == BfParamKind_ExplicitThis) && (resolvedParamType != NULL) && (resolvedParamType->IsRef()))
  18054. resolvedParamType = resolvedParamType->GetUnderlyingType();
  18055. }
  18056. if (resolvedParamType == NULL)
  18057. {
  18058. resolvedParamType = GetPrimitiveType(BfTypeCode_Var);
  18059. unresolvedParamType = resolvedParamType;
  18060. if (mCurTypeInstance->IsBoxed())
  18061. {
  18062. auto boxedType = (BfBoxedType*)mCurTypeInstance;
  18063. // If we failed a lookup here then we better have also failed it in the original type
  18064. BF_ASSERT(boxedType->mElementType->ToTypeInstance()->mModule->mHadBuildError || mContext->mFailTypes.Contains(boxedType->mElementType->ToTypeInstance()));
  18065. }
  18066. }
  18067. if (!methodInstance->IsSpecializedGenericMethod())
  18068. AddDependency(resolvedParamType, typeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  18069. PopulateType(resolvedParamType, BfPopulateType_Declaration);
  18070. AddDependency(resolvedParamType, mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
  18071. if ((paramDef != NULL) && (paramDef->mParamDeclaration != NULL) && (paramDef->mParamDeclaration->mInitializer != NULL) &&
  18072. (!paramDef->mParamDeclaration->mInitializer->IsA<BfBlock>()))
  18073. {
  18074. if (paramDef->mParamKind == BfParamKind_Params)
  18075. {
  18076. BfAstNode* refNode = paramDef->mParamDeclaration->mEqualsNode;
  18077. if (refNode != NULL)
  18078. refNode = paramDef->mParamDeclaration->mModToken;
  18079. Fail("Cannot specify a default value for a 'params' parameter", refNode);
  18080. }
  18081. BfMethodState methodState;
  18082. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  18083. methodState.mTempKind = BfMethodState::TempKind_Static;
  18084. BfTypedValue defaultValue;
  18085. if (resolvedParamType->IsConstExprValue())
  18086. {
  18087. auto constExprType = (BfConstExprValueType*)resolvedParamType;
  18088. BfExprEvaluator exprEvaluator(this);
  18089. exprEvaluator.mExpectingType = constExprType->mType;
  18090. exprEvaluator.GetLiteral(NULL, constExprType->mValue);
  18091. defaultValue = exprEvaluator.GetResult();
  18092. }
  18093. else
  18094. {
  18095. BfConstResolver constResolver(this);
  18096. defaultValue = constResolver.Resolve(paramDef->mParamDeclaration->mInitializer, resolvedParamType, (BfConstResolveFlags)(BfConstResolveFlag_NoCast | BfConstResolveFlag_AllowGlobalVariable));
  18097. if ((defaultValue) && (defaultValue.mType != resolvedParamType))
  18098. {
  18099. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  18100. auto castedDefaultValue = Cast(paramDef->mParamDeclaration->mInitializer, defaultValue, resolvedParamType, (BfCastFlags)(BfCastFlags_SilentFail | BfCastFlags_NoConversionOperator));
  18101. if ((castedDefaultValue) && (castedDefaultValue.mValue.IsConst()))
  18102. {
  18103. defaultValue = castedDefaultValue; // Good!
  18104. }
  18105. else if (!CanCast(defaultValue, resolvedParamType))
  18106. {
  18107. // We only care that we get a constant value that can be implicitly casted at the callsite- even if that requires
  18108. // a conversion operator.
  18109. // This should throw an error
  18110. defaultValue = Cast(paramDef->mParamDeclaration->mInitializer, defaultValue, resolvedParamType);
  18111. AssertErrorState();
  18112. if (!defaultValue.mValue.IsConst())
  18113. defaultValue = BfTypedValue();
  18114. }
  18115. }
  18116. }
  18117. if (!defaultValue)
  18118. {
  18119. defaultValue = GetDefaultTypedValue(resolvedParamType);
  18120. if (!defaultValue.mValue.IsConst())
  18121. defaultValue = BfTypedValue();
  18122. }
  18123. if (defaultValue)
  18124. {
  18125. if (defaultValue.mType->IsVar())
  18126. {
  18127. AssertErrorState();
  18128. }
  18129. else
  18130. {
  18131. BF_ASSERT(defaultValue.mValue.IsConst());
  18132. while ((int)mCurMethodInstance->mDefaultValues.size() < paramDefIdx)
  18133. mCurMethodInstance->mDefaultValues.Add(BfTypedValue());
  18134. CurrentAddToConstHolder(defaultValue.mValue);
  18135. mCurMethodInstance->mDefaultValues.Add(defaultValue);
  18136. }
  18137. }
  18138. }
  18139. if ((paramDef != NULL) && (paramDef->mParamKind == BfParamKind_Params))
  18140. {
  18141. bool addParams = true;
  18142. bool isValid = false;
  18143. auto resolvedParamTypeInst = resolvedParamType->ToTypeInstance();
  18144. if ((resolvedParamTypeInst != NULL) && (resolvedParamTypeInst->mTypeDef == mCompiler->mSpanTypeDef))
  18145. {
  18146. // Span<T>
  18147. isValid = true;
  18148. }
  18149. else if (resolvedParamType->IsArray())
  18150. {
  18151. // Array is the 'normal' params type
  18152. isValid = true;
  18153. }
  18154. else if ((resolvedParamType->IsDelegate()) || (resolvedParamType->IsFunction()))
  18155. {
  18156. hadDelegateParams = true;
  18157. // This means we copy the params from a delegate
  18158. BfMethodParam methodParam;
  18159. methodParam.mResolvedType = resolvedParamType;
  18160. methodParam.mParamDefIdx = paramDefIdx;
  18161. methodParam.mDelegateParamIdx = 0;
  18162. auto invokeMethodInstance = methodParam.GetDelegateParamInvoke();
  18163. for (int delegateParamIdx = 0; delegateParamIdx < invokeMethodInstance->GetParamCount(); delegateParamIdx++)
  18164. {
  18165. methodParam.mDelegateParamIdx = delegateParamIdx;
  18166. mCurMethodInstance->mParams.Add(methodParam);
  18167. auto paramType = invokeMethodInstance->GetParamType(delegateParamIdx);
  18168. if (!methodInstance->IsSpecializedGenericMethod())
  18169. AddDependency(paramType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  18170. }
  18171. isValid = true;
  18172. addParams = false;
  18173. }
  18174. else if (resolvedParamType->IsGenericParam())
  18175. {
  18176. auto genericParamInstance = GetGenericParamInstance((BfGenericParamType*)resolvedParamType);
  18177. if (genericParamInstance->mTypeConstraint != NULL)
  18178. {
  18179. auto typeInstConstraint = genericParamInstance->mTypeConstraint->ToTypeInstance();
  18180. if (genericParamInstance->mTypeConstraint->IsArray())
  18181. {
  18182. BfMethodParam methodParam;
  18183. methodParam.mResolvedType = resolvedParamType;
  18184. methodParam.mParamDefIdx = paramDefIdx;
  18185. mCurMethodInstance->mParams.Add(methodParam);
  18186. isValid = true;
  18187. }
  18188. else if ((genericParamInstance->mTypeConstraint->IsDelegate()) || (genericParamInstance->mTypeConstraint->IsFunction()) ||
  18189. ((genericParamInstance != NULL) && (typeInstConstraint != NULL) &&
  18190. ((typeInstConstraint->mTypeDef == mCompiler->mDelegateTypeDef) || (typeInstConstraint->mTypeDef == mCompiler->mFunctionTypeDef))))
  18191. {
  18192. mCurMethodInstance->mHadGenericDelegateParams = true;
  18193. isValid = true;
  18194. addParams = false;
  18195. }
  18196. }
  18197. }
  18198. else
  18199. {
  18200. auto paramTypeInst = resolvedParamType->ToTypeInstance();
  18201. if ((paramTypeInst != NULL) &&
  18202. ((paramTypeInst->mTypeDef == mCompiler->mDelegateTypeDef) || (paramTypeInst->mTypeDef == mCompiler->mFunctionTypeDef)))
  18203. {
  18204. // If we have a 'params T' and 'T' gets specialized with actually 'Delegate' or 'Function' then just ignore it
  18205. isValid = true;
  18206. addParams = false;
  18207. }
  18208. }
  18209. if (!isValid)
  18210. {
  18211. Fail("Parameters with 'params' specifiers can only be used for array, span, delegate, or function types", paramDef->mParamDeclaration->mModToken);
  18212. // Failure case, make it an Object[]
  18213. resolvedParamType = CreateArrayType(mContext->mBfObjectType, 1);
  18214. }
  18215. if (addParams)
  18216. {
  18217. BfMethodParam methodParam;
  18218. methodParam.mResolvedType = resolvedParamType;
  18219. methodParam.mParamDefIdx = paramDefIdx;
  18220. mCurMethodInstance->mParams.push_back(methodParam);
  18221. }
  18222. if (paramDefIdx < (int)methodDef->mParams.size() - 1)
  18223. {
  18224. Fail("Only the last parameter can specify 'params'", paramDef->mParamDeclaration->mModToken);
  18225. }
  18226. }
  18227. else
  18228. {
  18229. BfMethodParam methodParam;
  18230. methodParam.mResolvedType = resolvedParamType;
  18231. methodParam.mParamDefIdx = paramDefIdx;
  18232. mCurMethodInstance->mParams.Add(methodParam);
  18233. }
  18234. }
  18235. if (hadDelegateParams)
  18236. {
  18237. HashSet<String> usedNames;
  18238. Dictionary<int, int> usedParamDefIdx;
  18239. for (auto methodParam : methodDef->mParams)
  18240. {
  18241. usedNames.Add(methodParam->mName);
  18242. }
  18243. for (auto& methodParam : mCurMethodInstance->mParams)
  18244. {
  18245. if ((methodParam.mParamDefIdx != -1) && (methodParam.mDelegateParamIdx == 0))
  18246. {
  18247. int* refCount = NULL;
  18248. usedParamDefIdx.TryAdd(methodParam.mParamDefIdx, NULL, &refCount);
  18249. (*refCount)++;
  18250. }
  18251. }
  18252. for (auto& methodParam : mCurMethodInstance->mParams)
  18253. {
  18254. if (methodParam.mDelegateParamIdx != -1)
  18255. {
  18256. if (usedParamDefIdx[methodParam.mParamDefIdx] > 1)
  18257. methodParam.mDelegateParamNameCombine = true;
  18258. BfMethodInstance* invokeMethodInstance = methodParam.GetDelegateParamInvoke();
  18259. String paramName = invokeMethodInstance->GetParamName(methodParam.mDelegateParamIdx);
  18260. if (usedNames.Contains(paramName))
  18261. methodParam.mDelegateParamNameCombine = true;
  18262. }
  18263. }
  18264. }
  18265. int argIdx = 0;
  18266. PopulateType(methodInstance->mReturnType, BfPopulateType_Data);
  18267. if ((!methodDef->mIsStatic) && (!methodDef->mHasExplicitThis))
  18268. {
  18269. int thisIdx = methodDef->mHasExplicitThis ? 0 : -1;
  18270. auto thisType = methodInstance->GetOwner();
  18271. if (methodInstance->GetParamIsSplat(thisIdx))
  18272. argIdx += methodInstance->GetParamType(thisIdx)->GetSplatCount();
  18273. else if (!thisType->IsValuelessType())
  18274. {
  18275. BfTypeCode loweredTypeCode = BfTypeCode_None;
  18276. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  18277. if (!methodDef->mIsMutating)
  18278. thisType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2);
  18279. argIdx++;
  18280. if (loweredTypeCode2 != BfTypeCode_None)
  18281. argIdx++;
  18282. }
  18283. }
  18284. if (methodInstance->GetStructRetIdx() != -1)
  18285. argIdx++;
  18286. for (int paramIdx = 0; paramIdx < mCurMethodInstance->mParams.size(); paramIdx++)
  18287. {
  18288. auto& methodParam = mCurMethodInstance->mParams[paramIdx];
  18289. BfType* checkType = methodParam.mResolvedType;
  18290. int checkArgIdx = argIdx;
  18291. if ((paramIdx == 0) && (methodDef->mHasExplicitThis))
  18292. {
  18293. checkArgIdx = 0;
  18294. checkType = methodInstance->GetThisType();
  18295. }
  18296. if (checkType->IsMethodRef())
  18297. {
  18298. methodParam.mIsSplat = true;
  18299. }
  18300. else if ((checkType->IsComposite()) && (methodInstance->AllowsSplatting()))
  18301. {
  18302. PopulateType(checkType, BfPopulateType_Data);
  18303. if (checkType->IsSplattable())
  18304. {
  18305. int splatCount = checkType->GetSplatCount();
  18306. if (checkArgIdx + splatCount <= mCompiler->mOptions.mMaxSplatRegs)
  18307. {
  18308. methodParam.mIsSplat = true;
  18309. argIdx += splatCount;
  18310. continue;
  18311. }
  18312. }
  18313. else if (!checkType->IsValuelessType())
  18314. {
  18315. BfTypeCode loweredTypeCode = BfTypeCode_None;
  18316. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  18317. checkType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2);
  18318. argIdx++;
  18319. if (loweredTypeCode2 != BfTypeCode_None)
  18320. argIdx++;
  18321. continue;
  18322. }
  18323. }
  18324. argIdx++;
  18325. }
  18326. bool hasExternSpecifier = (methodDeclaration != NULL) && (methodDeclaration->mExternSpecifier != NULL);
  18327. if ((hasExternSpecifier) && (methodDeclaration->mBody != NULL))
  18328. {
  18329. Fail("Cannot 'extern' and declare a body", methodDeclaration->mExternSpecifier);
  18330. }
  18331. else if ((methodDeclaration != NULL) && (methodDeclaration->mBody == NULL) && (!hasExternSpecifier) &&
  18332. (!typeInstance->IsInterface()) && (!mCurTypeInstance->IsDelegate()) && (!mCurTypeInstance->IsFunction()) &&
  18333. (!methodDef->mIsPartial) && (!methodDef->mIsAbstract) &&
  18334. (!methodDef->mIsSkipCall))
  18335. {
  18336. if (methodDeclaration->mEndSemicolon == NULL)
  18337. {
  18338. AssertParseErrorState();
  18339. }
  18340. else
  18341. {
  18342. bool isError = true;
  18343. if (typeInstance->IsTypedPrimitive())
  18344. {
  18345. if (auto operatorDeclaration = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  18346. {
  18347. if ((operatorDeclaration->mIsConvOperator) && (methodInstance->mParams.size() == 1))
  18348. {
  18349. if (((methodInstance->mReturnType == typeInstance) && (methodInstance->GetParamType(0) == typeInstance->GetUnderlyingType())) ||
  18350. ((methodInstance->mReturnType == typeInstance->GetUnderlyingType()) && (methodInstance->GetParamType(0) == typeInstance)))
  18351. {
  18352. isError = false;
  18353. }
  18354. }
  18355. }
  18356. }
  18357. if (isError)
  18358. {
  18359. Fail(StrFormat("'%s' must declare a body because it is not marked abstract, extern, or partial",
  18360. MethodToString(methodInstance).c_str()),
  18361. methodDef->GetRefNode());
  18362. }
  18363. }
  18364. }
  18365. if (methodDef->IsEmptyPartial())
  18366. hasExternSpecifier = true;
  18367. if (!methodInstance->IsAutocompleteMethod())
  18368. {
  18369. auto defaultMethodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  18370. int implicitParamCount = methodInstance->GetImplicitParamCount();
  18371. int defaultImplicitParamCount = defaultMethodInstance->GetImplicitParamCount();
  18372. int actualParamCount = (int)methodInstance->mParams.size() - implicitParamCount;
  18373. BF_ASSERT((actualParamCount == defaultMethodInstance->mParams.size() - defaultImplicitParamCount) || (defaultMethodInstance->mHadGenericDelegateParams));
  18374. mCurMethodInstance->mHadGenericDelegateParams = defaultMethodInstance->mHadGenericDelegateParams;
  18375. int paramIdx = 0;
  18376. int defaultParamIdx = 0;
  18377. while (true)
  18378. {
  18379. bool isDone = paramIdx + implicitParamCount >= (int)methodInstance->mParams.size();
  18380. bool isDefaultDone = defaultParamIdx + defaultImplicitParamCount >= (int)defaultMethodInstance->mParams.size();
  18381. if ((!isDone) && (methodInstance->mParams[paramIdx + implicitParamCount].mDelegateParamIdx >= 0))
  18382. {
  18383. paramIdx++;
  18384. continue;
  18385. }
  18386. if ((!isDefaultDone) && (defaultMethodInstance->mParams[defaultParamIdx + defaultImplicitParamCount].mDelegateParamIdx >= 0))
  18387. {
  18388. defaultParamIdx++;
  18389. continue;
  18390. }
  18391. if ((isDone) || (isDefaultDone))
  18392. {
  18393. // 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
  18394. // to cause us to throw an assertion in the declaration here
  18395. if (!defaultMethodInstance->mHadGenericDelegateParams)
  18396. BF_ASSERT((isDone) && (isDefaultDone));
  18397. break;
  18398. }
  18399. BfType* paramType = defaultMethodInstance->mParams[defaultParamIdx + defaultImplicitParamCount].mResolvedType;
  18400. if (paramType->IsRef())
  18401. paramType = paramType->GetUnderlyingType();
  18402. methodInstance->mParams[paramIdx + implicitParamCount].mWasGenericParam = paramType->IsGenericParam();
  18403. paramIdx++;
  18404. defaultParamIdx++;
  18405. }
  18406. }
  18407. StringT<128> mangledName;
  18408. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  18409. for (int paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  18410. {
  18411. auto paramType = methodInstance->GetParamType(paramIdx);
  18412. if (paramType->IsComposite())
  18413. PopulateType(paramType, BfPopulateType_Data);
  18414. if (!methodInstance->IsParamSkipped(paramIdx))
  18415. {
  18416. if (paramType->IsStruct())
  18417. {
  18418. //
  18419. }
  18420. else
  18421. {
  18422. PopulateType(paramType, BfPopulateType_Declaration);
  18423. }
  18424. }
  18425. }
  18426. // Only process method in default unspecialized mode, not in variations
  18427. if (methodInstance->mIsUnspecializedVariation)
  18428. return;
  18429. PopulateType(resolvedReturnType, BfPopulateType_Data);
  18430. auto retLLVMType = mBfIRBuilder->MapType(resolvedReturnType);
  18431. if (resolvedReturnType->IsValuelessType())
  18432. retLLVMType = mBfIRBuilder->GetPrimitiveType(BfTypeCode_None);
  18433. if (!mBfIRBuilder->mIgnoreWrites)
  18434. {
  18435. bool isIntrinsic = false;
  18436. if (!methodInstance->mIRFunction)
  18437. SetupIRFunction(methodInstance, mangledName, isTemporaryFunc, &isIntrinsic);
  18438. if (isIntrinsic)
  18439. {
  18440. addToWorkList = false;
  18441. }
  18442. }
  18443. auto func = methodInstance->mIRFunction;
  18444. // if (methodInstance->mIsReified)
  18445. // CheckHotMethod(methodInstance, mangledName);
  18446. 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);
  18447. SizedArray<BfIRMDNode, 8> diParams;
  18448. diParams.push_back(mBfIRBuilder->DbgGetType(resolvedReturnType));
  18449. if ((!methodDef->mIsStatic) && (typeDef->mIsStatic) && (methodDef->mMethodDeclaration != NULL))
  18450. {
  18451. //CS0708
  18452. Fail("Cannot declare instance members in a static class", methodDef->GetRefNode());
  18453. }
  18454. if ((methodDef->mIsVirtual) && (methodDef->mGenericParams.size() != 0))
  18455. {
  18456. Fail("Virtual generic methods not supported", methodDeclaration->mVirtualSpecifier);
  18457. methodDef->mIsVirtual = false;
  18458. }
  18459. if ((methodDeclaration != NULL) && (methodDeclaration->mMutSpecifier != NULL) && (!mCurTypeInstance->IsBoxed()) && (!methodInstance->mIsForeignMethodDef))
  18460. {
  18461. if (methodDef->mIsStatic)
  18462. Warn(0, "Unnecessary 'mut' specifier, static methods have no implicit 'this' target to mutate", methodDeclaration->mMutSpecifier);
  18463. else if ((!mCurTypeInstance->IsValueType()) && (!mCurTypeInstance->IsInterface()))
  18464. Warn(0, "Unnecessary 'mut' specifier, methods of reference types are implicitly mutating", methodDeclaration->mMutSpecifier);
  18465. else if (methodDef->mMethodType == BfMethodType_Ctor)
  18466. Warn(0, "Unnecessary 'mut' specifier, constructors are implicitly mutating", methodDeclaration->mMutSpecifier);
  18467. else if (methodDef->mMethodType == BfMethodType_Dtor)
  18468. Warn(0, "Unnecessary 'mut' specifier, destructors are implicitly mutating", methodDeclaration->mMutSpecifier);
  18469. }
  18470. if (isTemporaryFunc)
  18471. {
  18472. // This handles temporary methods for autocomplete types
  18473. //BF_ASSERT(mIsScratchModule);
  18474. //BF_ASSERT(mCompiler->IsAutocomplete());
  18475. BfLogSysM("DoMethodDeclaration isTemporaryFunc bailout\n");
  18476. return; // Bail out early for autocomplete pass
  18477. }
  18478. if ((methodInstance->GetImportCallKind() != BfImportCallKind_None) && (!mBfIRBuilder->mIgnoreWrites) && (!methodInstance->mIRFunction))
  18479. {
  18480. BfLogSysM("DllImportGlobalVar DoMethodDeclaration processing %p\n", methodInstance);
  18481. // If this is in an extension then we did create the global variable already in the original obj
  18482. bool doDefine = mExtensionCount == 0;
  18483. BfIRValue dllImportGlobalVar = CreateDllImportGlobalVar(methodInstance, doDefine);
  18484. methodInstance->mIRFunction = mBfIRBuilder->GetFakeVal();
  18485. mFuncReferences[mCurMethodInstance] = dllImportGlobalVar;
  18486. }
  18487. //TODO: We used to have this (this != mContext->mExternalFuncModule) check, but it caused us to keep around
  18488. // an invalid mFuncRefernce (which came from GetMethodInstanceAtIdx) which later got remapped by the
  18489. // autocompleter. Why did we have this check anyway?
  18490. /*if ((typeInstance->mContext != mContext) && (!methodDef->IsEmptyPartial()))
  18491. {
  18492. AddMethodReference(methodInstance);
  18493. mFuncReferences[methodInstance] = func;
  18494. BfLogSysM("Adding func reference (DoMethodDeclaration). Module:%p MethodInst:%p LLVMFunc:%p\n", this, methodInstance, func);
  18495. }*/
  18496. if (mParentModule != NULL)
  18497. {
  18498. // For extension modules we need to keep track of our own methods so we can know which methods
  18499. // we have defined ourselves and which are from the parent module or other extensions
  18500. if (!func.IsFake())
  18501. mFuncReferences[methodInstance] = func;
  18502. }
  18503. if (addToWorkList)
  18504. {
  18505. bool wasAwaitingDecl = methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl;
  18506. if (wasAwaitingDecl)
  18507. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingReference;
  18508. if ((!methodDef->mIsAbstract) && (!methodInstance->mIgnoreBody))
  18509. {
  18510. if (!wasAwaitingDecl)
  18511. AddMethodToWorkList(methodInstance);
  18512. }
  18513. else
  18514. {
  18515. BfLogSysM("DoMethodDeclaration ignoring method body %d %d %d\n", hasExternSpecifier, methodDef->mIsAbstract, methodInstance->mIgnoreBody);
  18516. methodInstance->mIgnoreBody = true;
  18517. if (typeInstance->IsUnspecializedType())
  18518. {
  18519. // Don't hold on to actual Function for unspecialized types
  18520. methodInstance->mIRFunction = BfIRFunction();
  18521. }
  18522. }
  18523. }
  18524. if ((!methodInstance->IsSpecializedGenericMethodOrType()) && (!mCurTypeInstance->IsBoxed()) &&
  18525. (!methodDef->mIsLocalMethod) &&
  18526. (!CheckDefineMemberProtection(methodDef->mProtection, methodInstance->mReturnType)) &&
  18527. (!methodDef->mReturnTypeRef->IsTemporary()))
  18528. {
  18529. if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  18530. {
  18531. //TODO:
  18532. //CS0053
  18533. Fail(StrFormat("Inconsistent accessibility: property type '%s' is less accessible than property '%s'",
  18534. TypeToString(methodInstance->mReturnType).c_str(), MethodToString(methodInstance).c_str()),
  18535. methodDef->mReturnTypeRef, true);
  18536. }
  18537. else
  18538. {
  18539. //CS0050
  18540. Fail(StrFormat("Inconsistent accessibility: return type '%s' is less accessible than method '%s'",
  18541. TypeToString(methodInstance->mReturnType).c_str(), MethodToString(methodInstance).c_str()),
  18542. methodDef->mReturnTypeRef, true);
  18543. }
  18544. }
  18545. if ((typeInstance->IsInterface()) && (methodDef->mMethodType == BfMethodType_Ctor))
  18546. {
  18547. Fail("Interfaces cannot contain constructors", methodDeclaration);
  18548. }
  18549. bool foundHiddenMethod = false;
  18550. // Don't compare specialized generic methods against normal methods
  18551. if ((((mCurMethodInstance->mIsUnspecialized) || (mCurMethodInstance->mMethodDef->mGenericParams.size() == 0))) &&
  18552. (!methodDef->mIsLocalMethod))
  18553. {
  18554. if (!methodInstance->mIsForeignMethodDef)
  18555. {
  18556. typeDef->PopulateMemberSets();
  18557. BfMethodDef* nextMethod = NULL;
  18558. BfMemberSetEntry* entry = NULL;
  18559. if (typeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  18560. nextMethod = (BfMethodDef*)entry->mMemberDef;
  18561. while (nextMethod != NULL)
  18562. {
  18563. auto checkMethod = nextMethod;
  18564. nextMethod = nextMethod->mNextWithSameName;
  18565. if ((checkMethod != methodDef) && (typeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault != NULL))
  18566. {
  18567. auto checkMethodInstance = typeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  18568. if (((checkMethodInstance->mChainType == BfMethodChainType_None) || (checkMethodInstance->mChainType == BfMethodChainType_ChainHead)) &&
  18569. (checkMethodInstance->GetExplicitInterface() == methodInstance->GetExplicitInterface()) &&
  18570. (checkMethod->mIsMutating == methodDef->mIsMutating) &&
  18571. (CompareMethodSignatures(checkMethodInstance, mCurMethodInstance)))
  18572. {
  18573. bool canChain = false;
  18574. if ((methodDef->mParams.empty()) &&
  18575. (checkMethodInstance->mMethodDef->mIsStatic == methodInstance->mMethodDef->mIsStatic))
  18576. {
  18577. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) || (methodDef->mMethodType == BfMethodType_Dtor))
  18578. canChain = true;
  18579. else if (methodDef->mMethodType == BfMethodType_Normal)
  18580. {
  18581. if ((methodDef->mName == BF_METHODNAME_MARKMEMBERS) ||
  18582. (methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC) ||
  18583. (methodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS))
  18584. canChain = true;
  18585. }
  18586. }
  18587. if (canChain)
  18588. {
  18589. bool isBetter;
  18590. bool isWorse;
  18591. CompareDeclTypes(checkMethodInstance->mMethodDef->mDeclaringType, methodInstance->mMethodDef->mDeclaringType, isBetter, isWorse);
  18592. if (isBetter && !isWorse)
  18593. {
  18594. methodInstance->mChainType = BfMethodChainType_ChainHead;
  18595. checkMethodInstance->mChainType = BfMethodChainType_ChainMember;
  18596. }
  18597. else
  18598. {
  18599. checkMethodInstance->mChainType = BfMethodChainType_ChainHead;
  18600. methodInstance->mChainType = BfMethodChainType_ChainMember;
  18601. }
  18602. }
  18603. else if ((checkMethod->mBody == NULL) && (methodDef->mBody != NULL) &&
  18604. (checkMethod->mDeclaringType != methodDef->mDeclaringType))
  18605. {
  18606. // We're allowed to override an empty-bodied method
  18607. checkMethodInstance->mChainType = BfMethodChainType_ChainSkip;
  18608. }
  18609. else
  18610. {
  18611. if (!typeInstance->IsTypeMemberAccessible(checkMethod->mDeclaringType, methodDef->mDeclaringType))
  18612. continue;
  18613. bool silentlyAllow = false;
  18614. bool extensionWarn = false;
  18615. if (checkMethod->mDeclaringType != methodDef->mDeclaringType)
  18616. {
  18617. if (typeInstance->IsInterface())
  18618. {
  18619. if (methodDef->mIsOverride)
  18620. silentlyAllow = true;
  18621. }
  18622. else
  18623. {
  18624. if ((methodDef->mDeclaringType->mProject != checkMethod->mDeclaringType->mProject) &&
  18625. (!checkMethod->mDeclaringType->IsExtension()))
  18626. {
  18627. foundHiddenMethod = true;
  18628. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mIsStatic))
  18629. silentlyAllow = true;
  18630. else if (methodDef->mIsNew)
  18631. silentlyAllow = true;
  18632. else
  18633. extensionWarn = true;
  18634. }
  18635. else
  18636. silentlyAllow = true;
  18637. }
  18638. }
  18639. if ((checkMethod->mCommutableKind == BfCommutableKind_Reverse) || (methodDef->mCommutableKind == BfCommutableKind_Reverse))
  18640. silentlyAllow = true;
  18641. if (!silentlyAllow)
  18642. {
  18643. if ((!methodDef->mName.IsEmpty()) || (checkMethodInstance->mMethodDef->mIsOperator))
  18644. {
  18645. auto refNode = methodDef->GetRefNode();
  18646. BfError* bfError;
  18647. if (extensionWarn)
  18648. bfError = Warn(BfWarning_CS0114_MethodHidesInherited,
  18649. StrFormat("This method hides a method in the root type definition. Use the 'new' keyword if the hiding was intentional. Note that this method is not callable from project '%s'.",
  18650. checkMethod->mDeclaringType->mProject->mName.c_str()), refNode);
  18651. else
  18652. bfError = Fail("Method already declared with the same parameter types", refNode, true);
  18653. if (bfError != NULL)
  18654. mCompiler->mPassInstance->MoreInfo("First declaration", checkMethod->GetRefNode());
  18655. }
  18656. }
  18657. }
  18658. }
  18659. }
  18660. }
  18661. }
  18662. // Virtual methods give their error while slotting
  18663. if ((!typeInstance->IsBoxed()) && (!methodDef->mIsVirtual) && (methodDef->mProtection != BfProtection_Private) &&
  18664. (!methodDef->mIsLocalMethod) &&
  18665. (!methodInstance->mIsForeignMethodDef) && (typeInstance->mBaseType != NULL) &&
  18666. (methodDef->mMethodType == BfMethodType_Normal) && (methodDef->mMethodDeclaration != NULL))
  18667. {
  18668. auto baseType = typeInstance->mBaseType;
  18669. while (baseType != NULL)
  18670. {
  18671. //for (int checkMethodIdx = 0; checkMethodIdx < (int) baseType->mTypeDef->mMethods.size(); checkMethodIdx++)
  18672. auto baseTypeDef = baseType->mTypeDef;
  18673. baseTypeDef->PopulateMemberSets();
  18674. BfMethodDef* checkMethod = NULL;
  18675. BfMemberSetEntry* entry = NULL;
  18676. if (baseTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  18677. checkMethod = (BfMethodDef*)entry->mMemberDef;
  18678. while (checkMethod != NULL)
  18679. {
  18680. if (checkMethod->mMethodDeclaration == NULL)
  18681. continue;
  18682. if (baseType->mMethodInstanceGroups.size() == 0)
  18683. {
  18684. BF_ASSERT(baseType->IsIncomplete() && mCompiler->IsAutocomplete());
  18685. break;
  18686. }
  18687. if (checkMethod == methodDef)
  18688. continue;
  18689. if (checkMethod->mName != methodDef->mName)
  18690. continue;
  18691. auto checkMethodInstance = GetRawMethodInstanceAtIdx(baseType, checkMethod->mIdx);
  18692. if (checkMethodInstance != NULL)
  18693. {
  18694. if ((checkMethodInstance->GetExplicitInterface() == methodInstance->GetExplicitInterface()) &&
  18695. (checkMethod->mProtection != BfProtection_Private) &&
  18696. (CompareMethodSignatures(checkMethodInstance, mCurMethodInstance)))
  18697. {
  18698. if (!methodDef->mIsNew)
  18699. {
  18700. BfAstNode* refNode = methodInstance->mMethodDef->GetRefNode();
  18701. if (refNode != NULL)
  18702. {
  18703. 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?
  18704. if (bfError != NULL)
  18705. bfError->mIsPersistent = true;
  18706. }
  18707. }
  18708. foundHiddenMethod = true;
  18709. break;
  18710. }
  18711. }
  18712. checkMethod = checkMethod->mNextWithSameName;
  18713. }
  18714. if (foundHiddenMethod)
  18715. break;
  18716. baseType = baseType->mBaseType;
  18717. }
  18718. if ((methodDef->mIsNew) && (!foundHiddenMethod))
  18719. {
  18720. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  18721. auto tokenNode = (propertyDeclaration != NULL) ? propertyDeclaration->mNewSpecifier :
  18722. methodDeclaration->mNewSpecifier;
  18723. Fail("Method does not hide an inherited member. The 'new' keyword is not required", tokenNode, true);
  18724. }
  18725. }
  18726. }
  18727. mCompiler->mStats.mMethodDeclarations++;
  18728. mCompiler->UpdateCompletion();
  18729. }
  18730. void BfModule::UniqueSlotVirtualMethod(BfMethodInstance* methodInstance)
  18731. {
  18732. BF_ASSERT(methodInstance->GetOwner() == mCurTypeInstance);
  18733. auto typeInstance = mCurTypeInstance;
  18734. auto methodDef = methodInstance->mMethodDef;
  18735. int virtualMethodMatchIdx = -1;
  18736. if (typeInstance->mHotTypeData != NULL)
  18737. {
  18738. if (typeInstance->mHotTypeData->mVTableOrigLength != -1)
  18739. {
  18740. BF_ASSERT(mCompiler->IsHotCompile());
  18741. // In the 'normal' case we'd assert that mIsOverride is false, but if we can't find the declaring method then we
  18742. // may slot this override anyway (?)
  18743. int vTableStart = 0;
  18744. auto implBaseType = typeInstance->GetImplBaseType();
  18745. if (implBaseType != NULL)
  18746. vTableStart = implBaseType->mVirtualMethodTableSize;
  18747. StringT<128> mangledName;
  18748. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  18749. for (int checkIdxOfs = 0; checkIdxOfs < (int)typeInstance->mHotTypeData->mVTableEntries.size(); checkIdxOfs++)
  18750. {
  18751. // O(1) checking when virtual methods haven't changed
  18752. int checkIdx = (typeInstance->mVirtualMethodTableSize - vTableStart + checkIdxOfs) % (int)typeInstance->mHotTypeData->mVTableEntries.size();
  18753. auto& entry = typeInstance->mHotTypeData->mVTableEntries[checkIdx];
  18754. if (mangledName == entry.mFuncName)
  18755. {
  18756. virtualMethodMatchIdx = vTableStart + checkIdx;
  18757. break;
  18758. }
  18759. }
  18760. if (virtualMethodMatchIdx != -1)
  18761. {
  18762. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  18763. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod = methodInstance;
  18764. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod = methodInstance;
  18765. }
  18766. typeInstance->mVirtualMethodTableSize = (int)typeInstance->mVirtualMethodTable.size();
  18767. }
  18768. }
  18769. if (virtualMethodMatchIdx == -1)
  18770. {
  18771. methodInstance->mVirtualTableIdx = typeInstance->mVirtualMethodTableSize++;
  18772. BfVirtualMethodEntry entry = { methodInstance, methodInstance };
  18773. typeInstance->mVirtualMethodTable.push_back(entry);
  18774. }
  18775. }
  18776. void BfModule::CompareDeclTypes(BfTypeDef* newDeclType, BfTypeDef* prevDeclType, bool& isBetter, bool& isWorse)
  18777. {
  18778. if ((!prevDeclType->IsExtension()) && (newDeclType->IsExtension()))
  18779. {
  18780. // When we provide an extension override in the same project a root type override
  18781. isBetter = true;
  18782. isWorse = false;
  18783. }
  18784. else
  18785. {
  18786. isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  18787. isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  18788. }
  18789. }
  18790. bool BfModule::SlotVirtualMethod(BfMethodInstance* methodInstance, BfAmbiguityContext* ambiguityContext)
  18791. {
  18792. BP_ZONE("BfModule::SlotVirtualMethod");
  18793. if (mCurTypeInstance->IsUnspecializedTypeVariation())
  18794. return false;
  18795. auto _AddVirtualDecl = [&](BfMethodInstance* declMethodInstance)
  18796. {
  18797. if (!mCompiler->mOptions.mAllowHotSwapping)
  18798. return;
  18799. if ((!methodInstance->mIsReified) || (!declMethodInstance->mIsReified))
  18800. return;
  18801. if (methodInstance->mHotMethod == NULL)
  18802. CheckHotMethod(methodInstance, "");
  18803. if (methodInstance->mHotMethod == NULL)
  18804. return;
  18805. //BF_ASSERT(declMethodInstance->mHotMethod != NULL);
  18806. if (declMethodInstance->mHotMethod == NULL)
  18807. CheckHotMethod(declMethodInstance, "");
  18808. auto virtualDecl = mCompiler->mHotData->GetVirtualDeclaration(declMethodInstance->mHotMethod);
  18809. virtualDecl->mRefCount++;
  18810. methodInstance->mHotMethod->mReferences.Add(virtualDecl);
  18811. };
  18812. auto typeInstance = mCurTypeInstance;
  18813. auto typeDef = typeInstance->mTypeDef;
  18814. auto methodDef = methodInstance->mMethodDef;
  18815. auto methodDeclaration = methodDef->GetMethodDeclaration();
  18816. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  18817. auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration();
  18818. BfAstNode* declaringNode = methodDeclaration;
  18819. if (propertyMethodDeclaration != NULL)
  18820. declaringNode = propertyMethodDeclaration->mNameNode;
  18821. BfMethodInstance* methodOverriden = NULL;
  18822. bool usedMethod = false;
  18823. BfTokenNode* virtualToken = NULL;
  18824. if (propertyDeclaration != NULL)
  18825. virtualToken = propertyDeclaration->mVirtualSpecifier;
  18826. else if (methodDeclaration != NULL)
  18827. virtualToken = methodDeclaration->mVirtualSpecifier;
  18828. if ((methodDef->mIsVirtual) && (methodDef->mIsStatic))
  18829. {
  18830. Fail("Static members cannot be marked as override, virtual, or abstract", virtualToken, true);
  18831. }
  18832. else if (methodDef->mIsVirtual)
  18833. {
  18834. if (mCompiler->IsHotCompile())
  18835. mContext->EnsureHotMangledVirtualMethodName(methodInstance);
  18836. if ((methodDef->mProtection == BfProtection_Private) && (virtualToken != NULL))
  18837. Fail("Virtual or abstract members cannot be private", virtualToken, true);
  18838. BfTypeInstance* checkBase = typeInstance;
  18839. // If we are in an extension, look in ourselves first
  18840. if (methodDef->mDeclaringType->mTypeDeclaration == typeInstance->mTypeDef->mTypeDeclaration)
  18841. checkBase = checkBase->mBaseType;
  18842. if (typeInstance->IsValueType())
  18843. {
  18844. if (typeInstance->mBaseType == NULL)
  18845. return false; // It's actually ValueType
  18846. // We allow structs to override object methods for when they get boxed, so just ignore 'override' keyword until it gets boxed
  18847. if (!methodDef->mIsOverride)
  18848. {
  18849. Fail("Structs cannot have virtual methods", virtualToken, true);
  18850. return false;
  18851. }
  18852. checkBase = mContext->mBfObjectType;
  18853. if (checkBase->mVirtualMethodTableSize == 0)
  18854. PopulateType(checkBase, BfPopulateType_Full);
  18855. if (checkBase->mDefineState < BfTypeDefineState_DefinedAndMethodsSlotted)
  18856. return false; // System circular ref, don't do struct checking on those
  18857. }
  18858. int virtualMethodMatchIdx = -1;
  18859. bool hadHidingError = false;
  18860. BfMethodInstance* bestOverrideMethodInstance = NULL;
  18861. BfMethodInstance* ambiguousOverrideMethodInstance = NULL;
  18862. int bestOverrideMethodIdx = -1;
  18863. int ambiguousOverrideMethodIdx = -1;
  18864. if (checkBase != NULL)
  18865. {
  18866. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  18867. auto lookupType = checkBase;
  18868. while (lookupType != NULL)
  18869. {
  18870. lookupType->mTypeDef->PopulateMemberSets();
  18871. BfMethodDef* nextMethodDef = NULL;
  18872. BfMemberSetEntry* entry;
  18873. if (lookupType->mTypeDef->mMethodSet.TryGetWith((StringImpl&)methodInstance->mMethodDef->mName, &entry))
  18874. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  18875. while (nextMethodDef != NULL)
  18876. {
  18877. auto checkMethodDef = nextMethodDef;
  18878. nextMethodDef = nextMethodDef->mNextWithSameName;
  18879. if ((!checkMethodDef->mIsVirtual) || (checkMethodDef->mIsOverride))
  18880. continue;
  18881. BfMethodInstance* lookupMethodInstance = lookupType->mMethodInstanceGroups[checkMethodDef->mIdx].mDefault;
  18882. if ((lookupMethodInstance == NULL) || (lookupMethodInstance->mVirtualTableIdx == -1))
  18883. continue;
  18884. int checkMethodIdx = lookupMethodInstance->mVirtualTableIdx;
  18885. auto& baseMethodRef = baseVirtualMethodTable[checkMethodIdx];
  18886. if (baseMethodRef.mDeclaringMethod.mMethodNum == -1)
  18887. {
  18888. BF_ASSERT(mCompiler->mOptions.mHasVDataExtender);
  18889. continue;
  18890. }
  18891. BfMethodInstance* baseMethodInstance = baseVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  18892. if (baseMethodInstance == NULL)
  18893. {
  18894. AssertErrorState();
  18895. continue;
  18896. }
  18897. if ((baseMethodInstance != NULL) && (CompareMethodSignatures(baseMethodInstance, methodInstance)))
  18898. {
  18899. if (methodDef->mIsOverride)
  18900. {
  18901. BfMethodInstance* checkMethodInstance;
  18902. if (typeInstance->IsValueType())
  18903. checkMethodInstance = checkBase->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  18904. else
  18905. checkMethodInstance = typeInstance->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  18906. auto newDeclType = checkMethodInstance->mMethodDef->mDeclaringType;
  18907. if (!typeInstance->IsTypeMemberAccessible(newDeclType, methodDef->mDeclaringType->mProject))
  18908. continue;
  18909. if (bestOverrideMethodInstance != NULL)
  18910. {
  18911. auto prevDeclType = bestOverrideMethodInstance->mMethodDef->mDeclaringType;
  18912. bool isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  18913. bool isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  18914. if (isBetter == isWorse)
  18915. {
  18916. ambiguousOverrideMethodInstance = bestOverrideMethodInstance;
  18917. }
  18918. else
  18919. {
  18920. if (isWorse)
  18921. continue;
  18922. ambiguousOverrideMethodInstance = NULL;
  18923. }
  18924. }
  18925. bestOverrideMethodInstance = checkMethodInstance;
  18926. bestOverrideMethodIdx = checkMethodIdx;
  18927. }
  18928. else
  18929. {
  18930. if ((baseMethodInstance->GetOwner() != methodInstance->GetOwner()) && (!methodDef->mIsNew))
  18931. {
  18932. if (!hadHidingError)
  18933. Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use either 'override' or 'new'.", TypeToString(checkBase).c_str()), declaringNode);
  18934. hadHidingError = true;
  18935. }
  18936. }
  18937. }
  18938. }
  18939. lookupType = lookupType->mBaseType;
  18940. }
  18941. }
  18942. //TODO:
  18943. if ((checkBase != NULL)
  18944. && (false)
  18945. )
  18946. {
  18947. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  18948. for (int checkMethodIdx = (int) baseVirtualMethodTable.size() - 1; checkMethodIdx >= 0; checkMethodIdx--)
  18949. {
  18950. auto& baseMethodRef = baseVirtualMethodTable[checkMethodIdx];
  18951. if (baseMethodRef.mDeclaringMethod.mMethodNum == -1)
  18952. {
  18953. BF_ASSERT(mCompiler->mOptions.mHasVDataExtender);
  18954. continue;
  18955. }
  18956. BfMethodInstance* baseMethodInstance = baseVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  18957. if (baseMethodInstance == NULL)
  18958. {
  18959. AssertErrorState();
  18960. continue;
  18961. }
  18962. if ((baseMethodInstance != NULL) && (CompareMethodSignatures(baseMethodInstance, methodInstance)))
  18963. {
  18964. if (methodDef->mIsOverride)
  18965. {
  18966. BfMethodInstance* checkMethodInstance;
  18967. if (typeInstance->IsValueType())
  18968. checkMethodInstance = checkBase->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  18969. else
  18970. checkMethodInstance = typeInstance->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  18971. auto newDeclType = checkMethodInstance->mMethodDef->mDeclaringType;
  18972. if (!typeInstance->IsTypeMemberAccessible(newDeclType, methodDef->mDeclaringType->mProject))
  18973. continue;
  18974. if (bestOverrideMethodInstance != NULL)
  18975. {
  18976. auto prevDeclType = bestOverrideMethodInstance->mMethodDef->mDeclaringType;
  18977. bool isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  18978. bool isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  18979. if (isBetter == isWorse)
  18980. {
  18981. ambiguousOverrideMethodInstance = bestOverrideMethodInstance;
  18982. }
  18983. else
  18984. {
  18985. if (isWorse)
  18986. continue;
  18987. ambiguousOverrideMethodInstance = NULL;
  18988. }
  18989. }
  18990. bestOverrideMethodInstance = checkMethodInstance;
  18991. bestOverrideMethodIdx = checkMethodIdx;
  18992. }
  18993. else
  18994. {
  18995. if ((baseMethodInstance->GetOwner() != methodInstance->GetOwner()) && (!methodDef->mIsNew))
  18996. {
  18997. if (!hadHidingError)
  18998. Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use either 'override' or 'new'.", TypeToString(checkBase).c_str()), declaringNode);
  18999. hadHidingError = true;
  19000. }
  19001. }
  19002. }
  19003. }
  19004. }
  19005. if (bestOverrideMethodInstance != NULL)
  19006. {
  19007. if (ambiguousOverrideMethodInstance != NULL)
  19008. {
  19009. bool allow = false;
  19010. // 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.
  19011. // When when specialize, the specialized type will determine wither it has illegally pulled in both declarations or not
  19012. bool canSeeEachOther = false;
  19013. //
  19014. {
  19015. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, ambiguousOverrideMethodInstance);
  19016. if (bestOverrideMethodInstance->GetOwner()->IsTypeMemberIncluded(bestOverrideMethodInstance->mMethodDef->mDeclaringType, ambiguousOverrideMethodInstance->mMethodDef->mDeclaringType, this))
  19017. canSeeEachOther = true;
  19018. }
  19019. //
  19020. {
  19021. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, bestOverrideMethodInstance);
  19022. if (ambiguousOverrideMethodInstance->GetOwner()->IsTypeMemberIncluded(ambiguousOverrideMethodInstance->mMethodDef->mDeclaringType, bestOverrideMethodInstance->mMethodDef->mDeclaringType, this))
  19023. canSeeEachOther = true;
  19024. }
  19025. if (!canSeeEachOther)
  19026. {
  19027. BF_ASSERT(bestOverrideMethodInstance->GetOwner()->IsUnspecializedType() && ambiguousOverrideMethodInstance->GetOwner()->IsUnspecializedType());
  19028. }
  19029. else
  19030. {
  19031. auto error = Fail(StrFormat("Method '%s' is an ambiguous override", MethodToString(methodInstance).c_str()), methodDef->GetRefNode());
  19032. if (error != NULL)
  19033. {
  19034. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", MethodToString(bestOverrideMethodInstance).c_str()), bestOverrideMethodInstance->mMethodDef->GetRefNode());
  19035. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", MethodToString(ambiguousOverrideMethodInstance).c_str()), ambiguousOverrideMethodInstance->mMethodDef->GetRefNode());
  19036. }
  19037. }
  19038. }
  19039. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  19040. BfMethodInstance* baseVirtualMethodInstance = baseVirtualMethodTable[bestOverrideMethodIdx].mDeclaringMethod;
  19041. if ((baseVirtualMethodInstance != methodInstance) && (methodDef->mIsOverride))
  19042. {
  19043. if (baseVirtualMethodInstance->mReturnType != methodInstance->mReturnType)
  19044. {
  19045. BfTypeReference* returnTypeRef;
  19046. if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  19047. {
  19048. returnTypeRef = propertyDeclaration->mTypeRef;
  19049. Fail("Property differs from overridden property by type", returnTypeRef, true);
  19050. }
  19051. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  19052. {
  19053. returnTypeRef = methodDeclaration->mReturnType;
  19054. Fail("Method differs from overridden method by return value", returnTypeRef, true);
  19055. }
  19056. else
  19057. {
  19058. Fail(StrFormat("Internal error with method '%s'", MethodToString(methodInstance).c_str()));
  19059. }
  19060. return usedMethod;
  19061. }
  19062. }
  19063. if (methodDef->mIsOverride)
  19064. {
  19065. // We can have multiple matches when a virtual method is used to implement interface methods
  19066. // It doesn't matter what we set mVirtualTableIdx, as all base classes will override all matching
  19067. // vtable entries for this method signature
  19068. virtualMethodMatchIdx = bestOverrideMethodIdx;
  19069. if (!typeInstance->IsValueType())
  19070. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  19071. if (typeInstance->IsValueType())
  19072. {
  19073. methodOverriden = checkBase->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod;
  19074. }
  19075. else
  19076. {
  19077. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  19078. bool preferRootDefinition = (methodDef->mName == BF_METHODNAME_MARKMEMBERS) || (methodDef->mMethodType == BfMethodType_Dtor);
  19079. BfMethodInstance* setMethodInstance = methodInstance;
  19080. bool doOverride = false;
  19081. auto& overridenRef = typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod;
  19082. if (overridenRef.mKind != BfMethodRefKind_AmbiguousRef)
  19083. {
  19084. methodOverriden = overridenRef;
  19085. doOverride = true;
  19086. if (methodOverriden->GetOwner() == methodInstance->GetOwner())
  19087. {
  19088. bool isBetter = false;
  19089. bool isWorse = false;
  19090. CompareDeclTypes(methodInstance->mMethodDef->mDeclaringType, methodOverriden->mMethodDef->mDeclaringType, isBetter, isWorse);
  19091. if (isBetter == isWorse)
  19092. {
  19093. // We have to resolve later per-project
  19094. if ((ambiguityContext != NULL) && (ambiguityContext->mIsProjectSpecific))
  19095. {
  19096. auto declMethodInstance = checkBase->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod;
  19097. ambiguityContext->Add(virtualMethodMatchIdx, NULL, -1, methodOverriden, methodInstance);
  19098. }
  19099. if ((ambiguityContext == NULL) || (!ambiguityContext->mIsProjectSpecific))
  19100. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod.mKind = BfMethodRefKind_AmbiguousRef;
  19101. doOverride = false;
  19102. }
  19103. else
  19104. {
  19105. if ((isBetter) && (ambiguityContext != NULL))
  19106. {
  19107. ambiguityContext->Remove(virtualMethodMatchIdx);
  19108. }
  19109. if ((isBetter) && (methodInstance->GetOwner() == methodOverriden->GetOwner()))
  19110. {
  19111. if (preferRootDefinition)
  19112. {
  19113. // Leave the master GCMarkMember
  19114. isBetter = false;
  19115. isWorse = true;
  19116. }
  19117. }
  19118. doOverride = isBetter;
  19119. }
  19120. }
  19121. }
  19122. else if ((preferRootDefinition) && (!methodDef->mDeclaringType->IsExtension()))
  19123. {
  19124. methodOverriden = overridenRef;
  19125. doOverride = true;
  19126. }
  19127. if (doOverride)
  19128. {
  19129. auto declMethodInstance = (BfMethodInstance*)typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod;
  19130. _AddVirtualDecl(declMethodInstance);
  19131. setMethodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  19132. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod = setMethodInstance;
  19133. }
  19134. }
  19135. if (methodOverriden != NULL)
  19136. {
  19137. auto prevProtection = methodOverriden->mMethodDef->mProtection;
  19138. if ((methodDef->mProtection != prevProtection) && (methodDef->mMethodType != BfMethodType_Dtor))
  19139. {
  19140. const char* protectionNames[] = {"hidden", "private", "internal", "protected", "public"};
  19141. BfAstNode* protectionRefNode = NULL;
  19142. if (auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration())
  19143. {
  19144. protectionRefNode = propertyMethodDeclaration->mProtectionSpecifier;
  19145. if (protectionRefNode == NULL)
  19146. protectionRefNode = propertyMethodDeclaration->mPropertyDeclaration->mProtectionSpecifier;
  19147. if (protectionRefNode == NULL)
  19148. protectionRefNode = propertyMethodDeclaration->mPropertyDeclaration->mNameNode;
  19149. }
  19150. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  19151. {
  19152. protectionRefNode = methodDeclaration->mProtectionSpecifier;
  19153. if (protectionRefNode == NULL)
  19154. protectionRefNode = methodDeclaration->mNameNode;
  19155. }
  19156. if (protectionRefNode != NULL)
  19157. Fail(StrFormat("Cannot change access modifiers when overriding '%s' inherited member", protectionNames[(int)prevProtection]), protectionRefNode, true);
  19158. }
  19159. }
  19160. }
  19161. }
  19162. if ((virtualMethodMatchIdx == -1) && ((ambiguityContext == NULL) || (!ambiguityContext->mIsReslotting)))
  19163. {
  19164. if (methodDef->mIsOverride)
  19165. {
  19166. BfTokenNode* overrideToken = NULL;
  19167. if (auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration())
  19168. overrideToken = propertyMethodDeclaration->mPropertyDeclaration->mVirtualSpecifier;
  19169. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  19170. overrideToken = methodDeclaration->mVirtualSpecifier;
  19171. if (overrideToken != NULL)
  19172. {
  19173. if ((propertyDeclaration != NULL) && (propertyDeclaration->mNameNode != NULL) &&
  19174. ((methodDef->mMethodType == BfMethodType_PropertyGetter) || (methodDef->mMethodType == BfMethodType_PropertySetter)))
  19175. Fail(StrFormat("No suitable method found to override for '%s.%s'",
  19176. propertyDeclaration->mNameNode->ToString().c_str(), (methodDef->mMethodType == BfMethodType_PropertyGetter) ? "get" : "set"), overrideToken, true);
  19177. else
  19178. Fail("No suitable method found to override", overrideToken, true);
  19179. }
  19180. return usedMethod;
  19181. }
  19182. UniqueSlotVirtualMethod(methodInstance);
  19183. }
  19184. else
  19185. usedMethod = true;
  19186. if (typeInstance->IsValueType())
  19187. return usedMethod;
  19188. }
  19189. bool foundInterface = false;
  19190. bool hadAnyMatch = false;
  19191. // See if this method matches interfaces
  19192. for (auto& ifaceTypeInst : typeInstance->mInterfaces)
  19193. {
  19194. auto ifaceInst = ifaceTypeInst.mInterfaceType;
  19195. if (ifaceInst->IsIncomplete())
  19196. PopulateType(ifaceInst, BfPopulateType_DataAndMethods);
  19197. int startIdx = ifaceTypeInst.mStartInterfaceTableIdx;
  19198. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  19199. // See "bidirectional" rules mentioned in DoTypeInstanceMethodProcessing
  19200. if ((!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, ifaceTypeInst.mDeclaringType)) &&
  19201. (!typeInstance->IsTypeMemberAccessible(ifaceTypeInst.mDeclaringType, methodDef->mDeclaringType)))
  19202. continue;
  19203. if (!typeInstance->IsTypeMemberIncluded(methodDef->mDeclaringType, ifaceTypeInst.mDeclaringType, this))
  19204. continue;
  19205. bool hadMatch = false;
  19206. BfMethodInstance* hadNameMatch = NULL;
  19207. BfType* expectedReturnType = NULL;
  19208. bool showedError = false;
  19209. // We go through our VTable looking for NULL entries within the interface sections
  19210. // The only instance of finding a "better" method is when we have explicitly interface-dotted method
  19211. // because a normal method declared in this type could have matched earlier
  19212. //for (int iMethodIdx = 0; iMethodIdx < iMethodCount; iMethodIdx++)
  19213. ifaceInst->mTypeDef->PopulateMemberSets();
  19214. BfMethodDef* checkMethodDef = NULL;
  19215. BfMemberSetEntry* entry;
  19216. if (ifaceInst->mTypeDef->mMethodSet.TryGetWith((StringImpl&)methodInstance->mMethodDef->mName, &entry))
  19217. checkMethodDef = (BfMethodDef*)entry->mMemberDef;
  19218. while (checkMethodDef != NULL)
  19219. {
  19220. int iMethodIdx = checkMethodDef->mIdx;
  19221. int iTableIdx = iMethodIdx + startIdx;
  19222. BfTypeInterfaceMethodEntry* interfaceMethodEntry = &typeInstance->mInterfaceMethodTable[iTableIdx];
  19223. auto iMethodPtr = &interfaceMethodEntry->mMethodRef;
  19224. bool storeIFaceMethod = false;
  19225. if ((mCompiler->mPassInstance->HasFailed()) && (iMethodIdx >= (int)ifaceInst->mMethodInstanceGroups.size()))
  19226. {
  19227. checkMethodDef = checkMethodDef->mNextWithSameName;
  19228. continue;
  19229. }
  19230. auto& iMethodGroup = ifaceInst->mMethodInstanceGroups[iMethodIdx];
  19231. auto iMethodInst = iMethodGroup.mDefault;
  19232. if (iMethodInst == NULL)
  19233. {
  19234. if ((!ifaceInst->IsGenericTypeInstance()) || (!ifaceInst->mTypeDef->mIsCombinedPartial))
  19235. AssertErrorState();
  19236. checkMethodDef = checkMethodDef->mNextWithSameName;
  19237. continue;
  19238. }
  19239. if (iMethodInst->mMethodDef->mName == methodInstance->mMethodDef->mName)
  19240. hadNameMatch = iMethodInst;
  19241. bool doesMethodSignatureMatch = CompareMethodSignatures(iMethodInst, methodInstance);
  19242. if ((!doesMethodSignatureMatch) && (iMethodInst->GetNumGenericParams() == 0) && (interfaceMethodEntry->mMethodRef.IsNull()))
  19243. {
  19244. doesMethodSignatureMatch = IsCompatibleInterfaceMethod(iMethodInst, methodInstance);
  19245. }
  19246. if ((doesMethodSignatureMatch) && (methodInstance->GetOwner()->IsValueType()))
  19247. {
  19248. if ((!iMethodInst->mMethodDef->mIsMutating) && (methodInstance->mMethodDef->mIsMutating))
  19249. {
  19250. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface == ifaceInst))
  19251. {
  19252. auto error = mCompiler->mPassInstance->Fail(StrFormat("Implementation method '%s' cannot specify 'mut' because the interface method does not allow it",
  19253. MethodToString(methodInstance).c_str()), methodInstance->mMethodDef->GetMutNode());
  19254. if (error != NULL)
  19255. mCompiler->mPassInstance->MoreInfo(StrFormat("Declare the interface method as 'mut' to allow matching 'mut' implementations"), iMethodInst->mMethodDef->mMethodDeclaration);
  19256. showedError = true;
  19257. }
  19258. }
  19259. }
  19260. if (doesMethodSignatureMatch)
  19261. {
  19262. usedMethod = true;
  19263. hadMatch = true;
  19264. hadAnyMatch = true;
  19265. storeIFaceMethod = true;
  19266. if ((iMethodPtr->mKind != BfMethodRefKind_AmbiguousRef) && (iMethodPtr->mTypeInstance != NULL))
  19267. {
  19268. auto prevMethod = (BfMethodInstance*)*iMethodPtr;
  19269. if ((mCompiler->mIsResolveOnly) && (prevMethod == methodInstance))
  19270. {
  19271. // When autocompletion regenerates a single method body but not the whole type then
  19272. // we will see ourselves in the vtable already
  19273. return usedMethod;
  19274. }
  19275. bool isBetter = false;
  19276. bool isWorse = false;
  19277. isBetter = (methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL);
  19278. isWorse = (prevMethod->mMethodInfoEx != NULL) && (prevMethod->mMethodInfoEx->mExplicitInterface != NULL);
  19279. if (isBetter == isWorse)
  19280. CompareDeclTypes(methodInstance->mMethodDef->mDeclaringType, prevMethod->mMethodDef->mDeclaringType, isBetter, isWorse);
  19281. if (isBetter == isWorse)
  19282. {
  19283. if (ambiguityContext != NULL)
  19284. {
  19285. ambiguityContext->Add(~iTableIdx, &ifaceTypeInst, iMethodIdx, prevMethod, methodInstance);
  19286. }
  19287. iMethodPtr->mKind = BfMethodRefKind_AmbiguousRef;
  19288. storeIFaceMethod = true;
  19289. }
  19290. else
  19291. {
  19292. if ((isBetter) && (ambiguityContext != NULL))
  19293. ambiguityContext->Remove(~iTableIdx);
  19294. storeIFaceMethod = isBetter;
  19295. }
  19296. }
  19297. }
  19298. if (storeIFaceMethod)
  19299. {
  19300. if (methodInstance->GetNumGenericParams() != 0)
  19301. _AddVirtualDecl(iMethodInst);
  19302. *iMethodPtr = methodInstance;
  19303. }
  19304. checkMethodDef = checkMethodDef->mNextWithSameName;
  19305. }
  19306. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface == ifaceInst) && (!hadMatch) && (!showedError))
  19307. {
  19308. if (expectedReturnType != NULL)
  19309. Fail(StrFormat("Wrong return type, expected '%s'", TypeToString(expectedReturnType).c_str()), declaringNode, true);
  19310. else if (hadNameMatch != NULL)
  19311. {
  19312. auto error = Fail("Method parameters don't match interface method", declaringNode, true);
  19313. if (error != NULL)
  19314. mCompiler->mPassInstance->MoreInfo("See interface method declaration", hadNameMatch->mMethodDef->GetRefNode());
  19315. }
  19316. else
  19317. {
  19318. auto propertyDecl = methodDef->GetPropertyDeclaration();
  19319. if (propertyDecl != NULL)
  19320. {
  19321. auto propertyMethodDecl = methodDef->GetPropertyMethodDeclaration();
  19322. String name;
  19323. if (auto indexerDeclaration = BfNodeDynCast<BfIndexerDeclaration>(propertyDecl))
  19324. name = "this[]";
  19325. else if (propertyDecl->mNameNode != NULL)
  19326. propertyDecl->mNameNode->ToString(name);
  19327. Fail(StrFormat("Property '%s' %s accessor not defined in interface '%s'", name.c_str(),
  19328. (methodDef->mMethodType == BfMethodType_PropertyGetter) ? "get" : "set", TypeToString(ifaceInst).c_str()), methodDef->GetRefNode(), true);
  19329. }
  19330. else
  19331. Fail(StrFormat("Method '%s' not found in interface '%s'", methodDef->mName.c_str(), TypeToString(ifaceInst).c_str()), methodDef->GetRefNode(), true);
  19332. }
  19333. }
  19334. }
  19335. // Any overriden virtual methods that were used in interfaces also need to be replaced
  19336. if (methodOverriden != NULL)
  19337. {
  19338. for (auto& methodEntry : typeInstance->mInterfaceMethodTable)
  19339. {
  19340. if (methodEntry.mMethodRef == methodOverriden)
  19341. methodEntry.mMethodRef = methodInstance;
  19342. }
  19343. }
  19344. return usedMethod;
  19345. }
  19346. bool BfModule::SlotInterfaceMethod(BfMethodInstance* methodInstance)
  19347. {
  19348. auto typeInstance = mCurTypeInstance;
  19349. auto methodDef = methodInstance->mMethodDef;
  19350. if (methodDef->mMethodType == BfMethodType_Ctor)
  19351. return true;
  19352. bool foundOverride = false;
  19353. if ((methodDef->mBody == NULL) && (methodDef->mProtection == BfProtection_Private))
  19354. {
  19355. Fail("Private interface methods must provide a body", methodDef->GetMethodDeclaration()->mProtectionSpecifier);
  19356. }
  19357. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL) && (!methodDef->mIsOverride))
  19358. {
  19359. Fail("Explicit interfaces can only be specified for overrides in interface declarations", methodDef->GetMethodDeclaration()->mExplicitInterface);
  19360. }
  19361. BfAstNode* declaringNode = methodDef->GetRefNode();
  19362. for (auto& ifaceTypeInst : typeInstance->mInterfaces)
  19363. {
  19364. auto ifaceInst = ifaceTypeInst.mInterfaceType;
  19365. int startIdx = ifaceTypeInst.mStartInterfaceTableIdx;
  19366. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  19367. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != ifaceInst))
  19368. continue;
  19369. ifaceInst->mTypeDef->PopulateMemberSets();
  19370. BfMethodDef* nextMethod = NULL;
  19371. BfMemberSetEntry* entry = NULL;
  19372. if (ifaceInst->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  19373. nextMethod = (BfMethodDef*)entry->mMemberDef;
  19374. while (nextMethod != NULL)
  19375. {
  19376. auto checkMethod = nextMethod;
  19377. nextMethod = nextMethod->mNextWithSameName;
  19378. auto ifaceMethod = ifaceInst->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  19379. if (ifaceMethod == NULL)
  19380. continue;
  19381. if (CompareMethodSignatures(ifaceMethod, methodInstance))
  19382. {
  19383. if (methodDef->mIsOverride)
  19384. {
  19385. if (ifaceMethod->mMethodDef->mProtection == BfProtection_Private)
  19386. {
  19387. auto error = Fail(StrFormat("Interface method '%s' cannot override private interface method '%s'", MethodToString(methodInstance).c_str(), MethodToString(ifaceMethod).c_str()), declaringNode);
  19388. if (error != NULL)
  19389. {
  19390. mCompiler->mPassInstance->MoreInfo("See base interface method", ifaceMethod->mMethodDef->GetRefNode());
  19391. }
  19392. }
  19393. foundOverride = true;
  19394. }
  19395. else if (!methodDef->mIsNew)
  19396. {
  19397. Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use the 'new' keyword if hiding was intentional.", TypeToString(ifaceInst).c_str()), declaringNode);
  19398. }
  19399. }
  19400. }
  19401. }
  19402. if ((methodDef->mIsOverride) && (!foundOverride))
  19403. {
  19404. // This allows us to declare a method in the base definition or in an extension and then provide
  19405. // an implementation in a more-specific extension
  19406. typeInstance->mTypeDef->PopulateMemberSets();
  19407. BfMethodDef* nextMethod = NULL;
  19408. BfMemberSetEntry* entry = NULL;
  19409. if (typeInstance->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  19410. nextMethod = (BfMethodDef*)entry->mMemberDef;
  19411. while (nextMethod != NULL)
  19412. {
  19413. auto checkMethod = nextMethod;
  19414. nextMethod = nextMethod->mNextWithSameName;
  19415. auto ifaceMethod = typeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  19416. if (ifaceMethod == NULL)
  19417. continue;
  19418. if (ifaceMethod->mMethodDef->mDeclaringType == methodInstance->mMethodDef->mDeclaringType)
  19419. continue;
  19420. if (CompareMethodSignatures(ifaceMethod, methodInstance))
  19421. {
  19422. foundOverride = true;
  19423. }
  19424. }
  19425. // for (int methodIdx = 0; methodIdx < typeInstance->mMethodInstanceGroups.size(); methodIdx++)
  19426. // {
  19427. // auto ifaceMethod = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  19428. // if (ifaceMethod == NULL)
  19429. // continue;
  19430. // if (ifaceMethod->mMethodDef->mDeclaringType == methodInstance->mMethodDef->mDeclaringType)
  19431. // continue;
  19432. //
  19433. // if (CompareMethodSignatures(ifaceMethod, methodInstance))
  19434. // {
  19435. // foundOverride = true;
  19436. // }
  19437. // }
  19438. }
  19439. if (methodDef->mIsOverride)
  19440. {
  19441. if (!foundOverride)
  19442. {
  19443. BfTokenNode* overrideToken = NULL;
  19444. if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  19445. overrideToken = propertyDeclaration->mVirtualSpecifier;
  19446. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  19447. overrideToken = methodDeclaration->mVirtualSpecifier;
  19448. if (overrideToken != NULL)
  19449. {
  19450. Fail("No suitable method found to override", overrideToken, true);
  19451. }
  19452. else
  19453. {
  19454. // Possible cause - DTOR with params
  19455. AssertErrorState();
  19456. }
  19457. }
  19458. return true;
  19459. }
  19460. // Generic methods can't be called virtually
  19461. if (methodInstance->GetNumGenericParams() != 0)
  19462. return true;
  19463. // Only public methods can be called virtually
  19464. if (methodDef->mProtection != BfProtection_Public)
  19465. return true;
  19466. UniqueSlotVirtualMethod(methodInstance);
  19467. return true;
  19468. }
  19469. void BfModule::SetMethodDependency(BfMethodInstance* methodInstance)
  19470. {
  19471. if (methodInstance->mMethodInfoEx == NULL)
  19472. return;
  19473. int wantMinDepth = -1;
  19474. if (mCurTypeInstance != NULL)
  19475. wantMinDepth = mCurTypeInstance->mDependencyMap.mMinDependDepth + 1;
  19476. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mMinDependDepth != -1))
  19477. {
  19478. int wantTypeMinDepth = mCurMethodInstance->mMethodInfoEx->mMinDependDepth + 1;
  19479. if ((wantMinDepth == -1) || (wantTypeMinDepth < wantMinDepth))
  19480. wantMinDepth = wantTypeMinDepth;
  19481. }
  19482. if ((methodInstance->mMethodInfoEx->mMinDependDepth == -1) || (wantMinDepth < methodInstance->mMethodInfoEx->mMinDependDepth))
  19483. methodInstance->mMethodInfoEx->mMinDependDepth = wantMinDepth;
  19484. }
  19485. void BfModule::DbgFinish()
  19486. {
  19487. if ((mBfIRBuilder == NULL) || (mExtensionCount != 0))
  19488. return;
  19489. if (mAwaitingInitFinish)
  19490. FinishInit();
  19491. if (mHasForceLinkMarker)
  19492. return;
  19493. String markerName;
  19494. BfIRValue linkMarker;
  19495. if (mBfIRBuilder->DbgHasInfo())
  19496. {
  19497. bool needForceLinking = false;
  19498. for (auto& ownedType : mOwnedTypeInstances)
  19499. {
  19500. bool hasConfirmedReference = false;
  19501. for (auto& methodInstGroup : ownedType->mMethodInstanceGroups)
  19502. {
  19503. if ((methodInstGroup.IsImplemented()) && (methodInstGroup.mDefault != NULL) &&
  19504. (!methodInstGroup.mDefault->mMethodDef->mIsStatic) && (methodInstGroup.mDefault->mIsReified) && (!methodInstGroup.mDefault->mAlwaysInline) &&
  19505. ((methodInstGroup.mOnDemandKind == BfMethodOnDemandKind_AlwaysInclude) || (methodInstGroup.mOnDemandKind == BfMethodOnDemandKind_Referenced)))
  19506. {
  19507. hasConfirmedReference = true;
  19508. }
  19509. }
  19510. if ((!hasConfirmedReference) || (ownedType->IsBoxed()))
  19511. needForceLinking = true;
  19512. }
  19513. if ((needForceLinking) && (mProject->mCodeGenOptions.mAsmKind == BfAsmKind_None))
  19514. {
  19515. BfMethodState methodState;
  19516. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  19517. methodState.mTempKind = BfMethodState::TempKind_Static;
  19518. mHasForceLinkMarker = true;
  19519. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  19520. SizedArray<BfIRType, 0> paramTypes;
  19521. BfIRFunctionType funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  19522. String linkName = "FORCELINKMOD_" + mModuleName;
  19523. BfIRFunction func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, linkName);
  19524. mBfIRBuilder->SetActiveFunction(func);
  19525. auto entryBlock = mBfIRBuilder->CreateBlock("main", true);
  19526. mBfIRBuilder->SetInsertPoint(entryBlock);
  19527. auto firstType = mOwnedTypeInstances[0];
  19528. UpdateSrcPos(mContext->mBfObjectType->mTypeDef->GetRefNode());
  19529. SizedArray<BfIRMDNode, 1> diParamTypes;
  19530. diParamTypes.Add(mBfIRBuilder->DbgGetType(GetPrimitiveType(BfTypeCode_None)));
  19531. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParamTypes);
  19532. auto diScope = mBfIRBuilder->DbgCreateFunction(mDICompileUnit, "FORCELINKMOD", linkName, mCurFilePosition.mFileInstance->mDIFile,
  19533. mCurFilePosition.mCurLine + 1, diFuncType, false, true, mCurFilePosition.mCurLine + 1, 0, false, func);
  19534. methodState.mCurScope->mDIScope = diScope;
  19535. UpdateSrcPos(mContext->mBfObjectType->mTypeDef->GetRefNode(), BfSrcPosFlag_Force);
  19536. SizedArray<BfIRValue, 8> args;
  19537. BfExprEvaluator exprEvaluator(this);
  19538. for (auto& ownedType : mOwnedTypeInstances)
  19539. {
  19540. auto alloca = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int8)));
  19541. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(diScope, "variable", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(ownedType));
  19542. mBfIRBuilder->DbgInsertDeclare(alloca, diVariable);
  19543. }
  19544. mBfIRBuilder->CreateRetVoid();
  19545. mBfIRBuilder->SetActiveFunction(BfIRFunction());
  19546. }
  19547. }
  19548. }
  19549. bool BfModule::Finish()
  19550. {
  19551. BP_ZONE("BfModule::Finish");
  19552. BfLogSysM("BfModule finish: %p\n", this);
  19553. if (mHadBuildError)
  19554. {
  19555. // Don't AssertErrorState here, this current pass may not have failed but
  19556. // the module was still queued in mFinishedModuleWorkList
  19557. ClearModule();
  19558. return true;
  19559. }
  19560. if (mUsedSlotCount != -1)
  19561. {
  19562. BF_ASSERT(mCompiler->mMaxInterfaceSlots != -1);
  19563. mUsedSlotCount = mCompiler->mMaxInterfaceSlots;
  19564. }
  19565. BF_ASSERT(mAddedToCount);
  19566. mAddedToCount = false;
  19567. mAwaitingFinish = false;
  19568. mCompiler->mStats.mModulesFinished++;
  19569. if (HasCompiledOutput())
  19570. {
  19571. DbgFinish();
  19572. if (mAwaitingInitFinish)
  19573. FinishInit();
  19574. for (auto ownedTypeInst : mOwnedTypeInstances)
  19575. {
  19576. // Generate dbg info and add global variables if we haven't already
  19577. mBfIRBuilder->PopulateType(ownedTypeInst);
  19578. }
  19579. if (mBfIRBuilder->DbgHasInfo())
  19580. {
  19581. mBfIRBuilder->DbgFinalize();
  19582. }
  19583. String objOutputPath;
  19584. String irOutputPath;
  19585. mIsModuleMutable = false;
  19586. //mOutFileNames.Clear();
  19587. BF_ASSERT((int)mOutFileNames.size() >= mExtensionCount);
  19588. bool writeModule = mBfIRBuilder->HasExports();
  19589. String outputPath;
  19590. BfCodeGenOptions codeGenOptions = mProject->mCodeGenOptions;
  19591. auto& compilerOpts = mCompiler->mOptions;
  19592. codeGenOptions.mSIMDSetting = compilerOpts.mSIMDSetting;
  19593. auto moduleOptions = GetModuleOptions();
  19594. codeGenOptions.mOptLevel = moduleOptions.mOptLevel;
  19595. codeGenOptions.mSIMDSetting = moduleOptions.mSIMDSetting;
  19596. codeGenOptions.mWriteLLVMIR = mCompiler->mOptions.mWriteIR;
  19597. codeGenOptions.mWriteObj = mCompiler->mOptions.mGenerateObj;
  19598. codeGenOptions.mWriteBitcode = mCompiler->mOptions.mGenerateBitcode;
  19599. codeGenOptions.mVirtualMethodOfs = 1 + mCompiler->GetDynCastVDataCount() + mCompiler->mMaxInterfaceSlots;
  19600. codeGenOptions.mDynSlotOfs = mSystem->mPtrSize - mCompiler->GetDynCastVDataCount() * 4;
  19601. mCompiler->mStats.mIRBytes += mBfIRBuilder->mStream.GetSize();
  19602. mCompiler->mStats.mConstBytes += mBfIRBuilder->mTempAlloc.GetAllocSize();
  19603. bool allowWriteToLib = true;
  19604. if ((allowWriteToLib) && (codeGenOptions.mOptLevel == BfOptLevel_OgPlus) &&
  19605. (!mCompiler->IsHotCompile()) && (mModuleName != "vdata"))
  19606. {
  19607. codeGenOptions.mWriteToLib = true;
  19608. mWroteToLib = true;
  19609. }
  19610. else
  19611. {
  19612. mWroteToLib = false;
  19613. }
  19614. for (int fileIdx = 0; fileIdx <= mExtensionCount; fileIdx++)
  19615. {
  19616. outputPath = mModuleName;
  19617. outputPath = mCompiler->mOutputDirectory + "/" + mProject->mName + "/" + outputPath;
  19618. BfModuleFileName moduleFileName;
  19619. if (mParentModule != NULL)
  19620. {
  19621. for (auto&& checkPair : mParentModule->mSpecializedMethodModules)
  19622. {
  19623. if (checkPair.mValue == this)
  19624. moduleFileName.mProjects = checkPair.mKey;
  19625. }
  19626. }
  19627. moduleFileName.mProjects.Add(mProject);
  19628. if (fileIdx > 0)
  19629. outputPath += StrFormat("@%d", fileIdx + 1);
  19630. if (mCompiler->mOptions.mWriteIR)
  19631. irOutputPath = outputPath + ".ll";
  19632. if (mCompiler->mOptions.mGenerateObj)
  19633. {
  19634. objOutputPath = outputPath + BF_OBJ_EXT;
  19635. moduleFileName.mFileName = objOutputPath;
  19636. }
  19637. else if (mCompiler->mOptions.mWriteIR)
  19638. {
  19639. moduleFileName.mFileName = irOutputPath;
  19640. }
  19641. else if ((!mCompiler->mOptions.mGenerateObj) && (!mCompiler->mOptions.mGenerateBitcode) && (!mCompiler->mOptions.mWriteIR))
  19642. {
  19643. BFMODULE_FATAL(this, "Neither obj nor IR specified");
  19644. }
  19645. moduleFileName.mModuleWritten = writeModule;
  19646. moduleFileName.mWroteToLib = mWroteToLib;
  19647. if (!mOutFileNames.Contains(moduleFileName))
  19648. mOutFileNames.Add(moduleFileName);
  19649. }
  19650. if (mCompiler->IsHotCompile())
  19651. {
  19652. codeGenOptions.mIsHotCompile = true;
  19653. if (mParentModule != NULL)
  19654. mParentModule->mHadHotObjectWrites = true;
  19655. mHadHotObjectWrites = true;
  19656. }
  19657. //TODO: Testing VDATA
  19658. /*if (mModuleName == "vdata")
  19659. {
  19660. codeGenOptions.mOptLevel = 4;
  19661. }*/
  19662. codeGenOptions.GenerateHash();
  19663. BP_ZONE("BfModule::Finish.WriteObjectFile");
  19664. if ((writeModule) && (!mBfIRBuilder->mIgnoreWrites))
  19665. mCompiler->mCodeGen.WriteObjectFile(this, outputPath, codeGenOptions);
  19666. mLastModuleWrittenRevision = mCompiler->mRevision;
  19667. }
  19668. else
  19669. {
  19670. for (auto type : mOwnedTypeInstances)
  19671. {
  19672. BF_ASSERT(!type->IsIncomplete());
  19673. }
  19674. }
  19675. for (auto& specModulePair : mSpecializedMethodModules)
  19676. {
  19677. auto specModule = specModulePair.mValue;
  19678. if ((specModule->mIsModuleMutable) && (!specModule->mAwaitingFinish))
  19679. {
  19680. BfLogSysM(" Mutable spec module remaining: %p\n", specModule);
  19681. }
  19682. }
  19683. CleanupFileInstances();
  19684. // We can't ClearModuleData here because we need the mSpecializedMethodModules to remain valid until we Finish them too
  19685. return true;
  19686. }
  19687. void BfModule::ReportMemory(MemReporter* memReporter)
  19688. {
  19689. memReporter->Add(sizeof(BfModule));
  19690. if (mBfIRBuilder != NULL)
  19691. {
  19692. memReporter->BeginSection("IRBuilder_ConstData");
  19693. memReporter->Add("Used", mBfIRBuilder->mTempAlloc.GetAllocSize());
  19694. memReporter->Add("Unused", mBfIRBuilder->mTempAlloc.GetTotalAllocSize() - mBfIRBuilder->mTempAlloc.GetAllocSize());
  19695. memReporter->EndSection();
  19696. memReporter->BeginSection("IRBuilder_BFIR");
  19697. memReporter->Add("Used", (int)(mBfIRBuilder->mStream.GetSize()));
  19698. memReporter->Add("Unused", (int)(mBfIRBuilder->mStream.mPools.size() * ChunkedDataBuffer::ALLOC_SIZE) - mBfIRBuilder->mStream.GetSize());
  19699. memReporter->EndSection();
  19700. memReporter->Add(sizeof(BfIRBuilder));
  19701. }
  19702. memReporter->BeginSection("FileInstanceMap");
  19703. memReporter->AddMap(mFileInstanceMap);
  19704. memReporter->AddMap(mNamedFileInstanceMap);
  19705. memReporter->Add((int)mNamedFileInstanceMap.size() * sizeof(BfFileInstance));
  19706. memReporter->EndSection();
  19707. memReporter->AddVec(mOwnedTypeInstances, false);
  19708. memReporter->AddVec(mSpecializedMethodModules, false);
  19709. memReporter->AddVec(mOutFileNames, false);
  19710. memReporter->AddMap("FuncReferences", mFuncReferences, false);
  19711. memReporter->AddMap(mInterfaceSlotRefs, false);
  19712. memReporter->AddMap(mStaticFieldRefs, false);
  19713. memReporter->AddMap(mClassVDataRefs, false);
  19714. memReporter->AddMap("VDataExtMap", mClassVDataExtRefs, false);
  19715. memReporter->AddMap(mTypeDataRefs, false);
  19716. memReporter->AddMap(mDbgRawAllocDataRefs, false);
  19717. memReporter->AddMap(mDeferredMethodCallData, false);
  19718. memReporter->AddHashSet(mDeferredMethodIds, false);
  19719. memReporter->AddHashSet("ModuleRefs", mModuleRefs, false);
  19720. }
  19721. // ClearModuleData is called immediately after the module is compiled, so don't clear out any data that needs to
  19722. // be transient through the next compile
  19723. void BfModule::ClearModuleData()
  19724. {
  19725. BfLogSysM("ClearModuleData %p\n", this);
  19726. if (mAddedToCount)
  19727. {
  19728. mCompiler->mStats.mModulesFinished++;
  19729. mAddedToCount = false;
  19730. }
  19731. mDICompileUnit = BfIRMDNode();
  19732. mIsModuleMutable = false;
  19733. mIncompleteMethodCount = 0;
  19734. mHasGenericMethods = false;
  19735. // We don't want to clear these because we want it to persist through module extensions-
  19736. // otherwise we may think an extension succeeds even though the base module failed
  19737. //mHadBuildError = false;
  19738. //mHadBuildWarning = false;
  19739. mClassVDataRefs.Clear();
  19740. mClassVDataExtRefs.Clear();
  19741. for (auto& kv : mTypeDataRefs)
  19742. kv.mValue = BfIRValue();
  19743. mStringCharPtrPool.Clear();
  19744. mStringObjectPool.Clear();
  19745. mStaticFieldRefs.Clear();
  19746. BF_ASSERT(!mIgnoreErrors);
  19747. for (auto prevIRBuilder : mPrevIRBuilders)
  19748. delete prevIRBuilder;
  19749. mPrevIRBuilders.Clear();
  19750. for (auto& specPair : mSpecializedMethodModules)
  19751. {
  19752. auto specModule = specPair.mValue;
  19753. specModule->ClearModuleData();
  19754. }
  19755. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  19756. mBuiltInFuncs[i] = BfIRFunction();
  19757. if (mNextAltModule != NULL)
  19758. mNextAltModule->ClearModuleData();
  19759. BfLogSysM("ClearModuleData. Deleting IRBuilder: %p\n", mBfIRBuilder);
  19760. delete mBfIRBuilder;
  19761. mBfIRBuilder = NULL;
  19762. mWantsIRIgnoreWrites = false;
  19763. }
  19764. void BfModule::DisownMethods()
  19765. {
  19766. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  19767. mBuiltInFuncs[i] = BfIRFunction();
  19768. BfModule* methodModule = this;
  19769. if (mParentModule != NULL)
  19770. methodModule = mParentModule;
  19771. for (auto typeInst : methodModule->mOwnedTypeInstances)
  19772. {
  19773. for (auto& methodGroup : typeInst->mMethodInstanceGroups)
  19774. {
  19775. if (methodGroup.mDefault != NULL)
  19776. {
  19777. if (methodGroup.mDefault->mIRFunction)
  19778. {
  19779. BF_ASSERT(methodGroup.mDefault->mDeclModule != NULL);
  19780. if (methodGroup.mDefault->mDeclModule == this)
  19781. {
  19782. methodGroup.mDefault->mIRFunction = BfIRFunction();
  19783. }
  19784. }
  19785. }
  19786. if (methodGroup.mMethodSpecializationMap != NULL)
  19787. {
  19788. for (auto& mapPair : *methodGroup.mMethodSpecializationMap)
  19789. {
  19790. auto methodInstance = mapPair.mValue;
  19791. if (methodInstance->mDeclModule == this)
  19792. {
  19793. methodInstance->mIRFunction = BfIRFunction();
  19794. }
  19795. }
  19796. }
  19797. }
  19798. }
  19799. }
  19800. void BfModule::ClearModule()
  19801. {
  19802. ClearModuleData();
  19803. DisownMethods();
  19804. for (auto& specPair : mSpecializedMethodModules)
  19805. {
  19806. auto specModule = specPair.mValue;
  19807. specModule->ClearModule();
  19808. }
  19809. if (mNextAltModule != NULL)
  19810. mNextAltModule->ClearModule();
  19811. }