BfModule.cpp 708 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004
  1. //#define USE_THUNKED_MddLLOC..
  2. #include "BeefySysLib/util/AllocDebug.h"
  3. #pragma warning(push) // 6
  4. #pragma warning(disable:4996)
  5. #include "BfCompiler.h"
  6. #include "BfSystem.h"
  7. #include "BfParser.h"
  8. #include "BfCodeGen.h"
  9. #include "BfExprEvaluator.h"
  10. #include "../Backend/BeLibManger.h"
  11. #include <fcntl.h>
  12. #include "BfConstResolver.h"
  13. #include "BfMangler.h"
  14. #include "BeefySysLib/util/PerfTimer.h"
  15. #include "BeefySysLib/util/BeefPerf.h"
  16. #include "BeefySysLib/util/StackHelper.h"
  17. #include "BfSourceClassifier.h"
  18. #include "BfAutoComplete.h"
  19. #include "BfDemangler.h"
  20. #include "BfResolvePass.h"
  21. #include "BfFixits.h"
  22. #include "BfIRCodeGen.h"
  23. #include "BfDefBuilder.h"
  24. #include "BfDeferEvalChecker.h"
  25. #pragma warning(pop)
  26. //////////////////////////////////////////////////////////////////////////
  27. static bool gDebugStuff = false;
  28. USING_NS_BF;
  29. //////////////////////////////////////////////////////////////////////////
  30. void BfLocalVariable::Init()
  31. {
  32. if (mResolvedType->IsValuelessType())
  33. {
  34. mIsAssigned = true;
  35. return;
  36. }
  37. if (mIsAssigned)
  38. return;
  39. bool isStruct = mResolvedType->IsStruct();
  40. if (mResolvedType->IsRef())
  41. isStruct = mResolvedType->GetUnderlyingType()->IsStruct();
  42. if ((isStruct) || ((mIsThis) && (mResolvedType->IsStructOrStructPtr())))
  43. {
  44. auto resolvedTypeRef = mResolvedType;
  45. if ((resolvedTypeRef->IsPointer()) || (resolvedTypeRef->IsRef()))
  46. resolvedTypeRef = resolvedTypeRef->GetUnderlyingType();
  47. auto typeInstance = resolvedTypeRef->ToTypeInstance();
  48. mUnassignedFieldFlags = (1 << typeInstance->mMergedFieldDataCount) - 1;
  49. if ((mIsThis) && (typeInstance->mBaseType != NULL))
  50. {
  51. // Base ctor is responsible for initializing its own fields
  52. mUnassignedFieldFlags &= ~(((int64)1 << typeInstance->mBaseType->mMergedFieldDataCount) - 1);
  53. }
  54. if (mUnassignedFieldFlags == 0)
  55. mIsAssigned = true;
  56. }
  57. else
  58. {
  59. mUnassignedFieldFlags = 1;
  60. }
  61. }
  62. BfLocalMethod::~BfLocalMethod()
  63. {
  64. BfLogSys(mSystem, "~BfLocalMethod %p\n", this);
  65. if (mMethodDeclaration != NULL)
  66. {
  67. mSource->mRefCount--;
  68. BF_ASSERT(mSource->mRefCount >= 0);
  69. }
  70. delete mMethodDef;
  71. delete mMethodInstanceGroup;
  72. }
  73. void BfDeferredLocalAssignData::ExtendFrom(BfDeferredLocalAssignData* outerLocalAssignData, bool doChain)
  74. {
  75. mIsChained = doChain;
  76. if (outerLocalAssignData == NULL)
  77. return;
  78. mChainedAssignData = outerLocalAssignData;
  79. if (!doChain)
  80. {
  81. outerLocalAssignData->BreakExtendChain();
  82. mAssignedLocals = outerLocalAssignData->mAssignedLocals;
  83. }
  84. mVarIdBarrier = outerLocalAssignData->mVarIdBarrier;
  85. }
  86. // The "extend chain" is broken when we have a conditional where the variable may not be defined after the block.
  87. // IE: "a" will be defined after the following, but "b" will not necessarily be defined.
  88. // if ((GetValue(out a)) && (GetValue(out b)) {}
  89. void BfDeferredLocalAssignData::BreakExtendChain()
  90. {
  91. if (!mIsChained)
  92. return;
  93. mIsChained = false;
  94. if (mChainedAssignData == NULL)
  95. return;
  96. mChainedAssignData->BreakExtendChain();
  97. mAssignedLocals = mChainedAssignData->mAssignedLocals;
  98. }
  99. void BfDeferredLocalAssignData::SetIntersection(const BfDeferredLocalAssignData& otherLocalAssignData)
  100. {
  101. BreakExtendChain();
  102. //TODO: We got rid of this case because we now set the proper assigned data when we do a return
  103. // If one of these had a return then treat that case as if it did have an assign -- because it doesn't
  104. // cause an UNASSIGNED value to be used
  105. // if (mHadReturn || otherLocalAssignData.mHadReturn)
  106. // {
  107. // SetUnion(otherLocalAssignData);
  108. // mHadFallthrough = mHadFallthrough && otherLocalAssignData.mHadFallthrough;
  109. // return;
  110. // }
  111. for (int i = 0; i < (int)mAssignedLocals.size(); )
  112. {
  113. auto& local = mAssignedLocals[i];
  114. if (!otherLocalAssignData.mAssignedLocals.Contains(local))
  115. {
  116. mAssignedLocals.RemoveAt(i);
  117. }
  118. else
  119. i++;
  120. }
  121. mHadFallthrough = mHadFallthrough && otherLocalAssignData.mHadFallthrough;
  122. }
  123. void BfDeferredLocalAssignData::Validate() const
  124. {
  125. for (auto var : mAssignedLocals)
  126. {
  127. BF_ASSERT((uintptr)var.mLocalVar->mName.length() < 100000);
  128. }
  129. }
  130. void BfDeferredLocalAssignData::SetUnion(const BfDeferredLocalAssignData& otherLocalAssignData)
  131. {
  132. BreakExtendChain();
  133. Validate();
  134. otherLocalAssignData.Validate();
  135. auto otherItr = otherLocalAssignData.mAssignedLocals.begin();
  136. while (otherItr != otherLocalAssignData.mAssignedLocals.end())
  137. {
  138. if (!mAssignedLocals.Contains(*otherItr))
  139. mAssignedLocals.push_back(*otherItr);
  140. ++otherItr;
  141. }
  142. mHadFallthrough = mHadFallthrough || otherLocalAssignData.mHadFallthrough;
  143. }
  144. BfMethodState::~BfMethodState()
  145. {
  146. BF_ASSERT(mPendingNullConditional == NULL);
  147. if (mPrevMethodState != NULL)
  148. {
  149. BF_ASSERT(mCurAccessId == 1);
  150. BF_ASSERT(mCurLocalVarId <= 0);
  151. }
  152. for (auto local : mLocals)
  153. delete local;
  154. for (auto& kv : mLambdaCache)
  155. delete kv.mValue;
  156. }
  157. BfMethodState* BfMethodState::GetMethodStateForLocal(BfLocalVariable* localVar)
  158. {
  159. auto checkMethodState = this;
  160. while (checkMethodState != NULL)
  161. {
  162. if ((localVar->mLocalVarIdx < checkMethodState->mLocals.size()) &&
  163. (checkMethodState->mLocals[localVar->mLocalVarIdx] == localVar))
  164. return checkMethodState;
  165. checkMethodState = checkMethodState->mPrevMethodState;
  166. }
  167. BF_FATAL("Failed to find method state for localvar");
  168. return NULL;
  169. }
  170. void BfMethodState::LocalDefined(BfLocalVariable* localVar, int fieldIdx)
  171. {
  172. auto localVarMethodState = GetMethodStateForLocal(localVar);
  173. if (localVarMethodState != this)
  174. {
  175. return;
  176. }
  177. //BF_ASSERT(localVarMethodState == this);
  178. if (!localVar->mIsAssigned)
  179. {
  180. BfDeferredLocalAssignData* ifDeferredLocalAssignData = NULL;
  181. // 'a' is always defined, but 'b' isn't:
  182. // if (Check(out a) || Check(out b)) { } int z = a;
  183. auto deferredLocalAssignData = mDeferredLocalAssignData;
  184. if ((deferredLocalAssignData != NULL) &&
  185. (deferredLocalAssignData->mIsIfCondition) &&
  186. (!deferredLocalAssignData->mIfMayBeSkipped))
  187. {
  188. ifDeferredLocalAssignData = deferredLocalAssignData;
  189. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  190. }
  191. while ((deferredLocalAssignData != NULL) &&
  192. ((deferredLocalAssignData->mIsChained) || (deferredLocalAssignData->mIsUnconditional)))
  193. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  194. if ((deferredLocalAssignData == NULL) || (localVar->mLocalVarId >= deferredLocalAssignData->mVarIdBarrier))
  195. {
  196. if (fieldIdx >= 0)
  197. {
  198. localVar->mUnassignedFieldFlags &= ~((int64)1 << fieldIdx);
  199. /*if ((localVar->mResolvedTypeRef != NULL) && (localVar->mResolvedTypeRef->IsUnion()))
  200. {
  201. }*/
  202. if (localVar->mUnassignedFieldFlags == 0)
  203. localVar->mIsAssigned = true;
  204. }
  205. else
  206. {
  207. localVar->mIsAssigned = true;
  208. }
  209. }
  210. else
  211. {
  212. BF_ASSERT(deferredLocalAssignData->mVarIdBarrier != -1);
  213. BfAssignedLocal defineVal = {localVar, fieldIdx + 1};
  214. auto& assignedLocals = deferredLocalAssignData->mAssignedLocals;
  215. if (!assignedLocals.Contains(defineVal))
  216. assignedLocals.push_back(defineVal);
  217. if (ifDeferredLocalAssignData != NULL)
  218. {
  219. auto& assignedLocals = ifDeferredLocalAssignData->mAssignedLocals;
  220. if (!assignedLocals.Contains(defineVal))
  221. assignedLocals.push_back(defineVal);
  222. }
  223. }
  224. }
  225. localVar->mWrittenToId = GetRootMethodState()->mCurAccessId++;
  226. }
  227. void BfMethodState::ApplyDeferredLocalAssignData(const BfDeferredLocalAssignData& deferredLocalAssignData)
  228. {
  229. BF_ASSERT(&deferredLocalAssignData != mDeferredLocalAssignData);
  230. for (auto& assignedLocal : deferredLocalAssignData.mAssignedLocals)
  231. {
  232. LocalDefined(assignedLocal.mLocalVar);
  233. }
  234. }
  235. void BfMethodState::Reset()
  236. {
  237. mHeadScope.mDeferredCallEntries.DeleteAll();
  238. }
  239. //////////////////////////////////////////////////////////////////////////
  240. void BfAmbiguityContext::Add(int id, BfTypeInterfaceEntry* interfaceEntry, int methodIdx, BfMethodInstance* candidateA, BfMethodInstance* candidateB)
  241. {
  242. Entry* entry = NULL;
  243. if (mEntries.TryAdd(id, NULL, &entry))
  244. {
  245. entry->mInterfaceEntry = interfaceEntry;
  246. entry->mMethodIdx = methodIdx;
  247. }
  248. if (!entry->mCandidates.Contains(candidateA))
  249. entry->mCandidates.push_back(candidateA);
  250. if (!entry->mCandidates.Contains(candidateB))
  251. entry->mCandidates.push_back(candidateB);
  252. }
  253. void BfAmbiguityContext::Remove(int id)
  254. {
  255. mEntries.Remove(id);
  256. }
  257. void BfAmbiguityContext::Finish()
  258. {
  259. for (auto& entryPair : mEntries)
  260. {
  261. int id = entryPair.mKey;
  262. auto entry = &entryPair.mValue;
  263. if (id >= 0)
  264. {
  265. auto declMethodInstance = mTypeInstance->mVirtualMethodTable[id].mDeclaringMethod;
  266. auto error = mModule->Fail(StrFormat("Method '%s' has ambiguous overrides", mModule->MethodToString(declMethodInstance).c_str()), declMethodInstance->mMethodDef->GetRefNode());
  267. for (auto candidate : entry->mCandidates)
  268. {
  269. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", mModule->MethodToString(candidate).c_str()), candidate->mMethodDef->GetRefNode());
  270. }
  271. }
  272. else
  273. {
  274. auto iMethodInst = entry->mInterfaceEntry->mInterfaceType->mMethodInstanceGroups[entry->mMethodIdx].mDefault;
  275. auto error = mModule->Fail(StrFormat("Interface method '%s' has ambiguous implementations", mModule->MethodToString(iMethodInst).c_str()), entry->mInterfaceEntry->mDeclaringType->GetRefNode());
  276. for (auto candidate : entry->mCandidates)
  277. {
  278. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", mModule->MethodToString(candidate).c_str()), candidate->mMethodDef->GetRefNode());
  279. }
  280. }
  281. }
  282. }
  283. //////////////////////////////////////////////////////////////////////////
  284. class HasAppendAllocVisitor : BfElementVisitor
  285. {
  286. public:
  287. bool mHas;
  288. public:
  289. HasAppendAllocVisitor()
  290. {
  291. mHas = false;
  292. }
  293. void Visit(BfObjectCreateExpression* objCreateExpr)
  294. {
  295. if (auto newToken = BfNodeDynCast<BfTokenNode>(objCreateExpr->mNewNode))
  296. {
  297. if (newToken->GetToken() == BfToken_Append)
  298. {
  299. mHas = true;
  300. }
  301. }
  302. }
  303. bool HasAppendAlloc(BfAstNode* node)
  304. {
  305. mHas = false;
  306. VisitChild(node);
  307. return mHas;
  308. }
  309. };
  310. class AppendAllocVisitor : public BfStructuralVisitor
  311. {
  312. public:
  313. BfModule* mModule;
  314. HasAppendAllocVisitor mHasAppendAllocVisitor;
  315. BfTypedValue mConstAccum;
  316. bool mFailed;
  317. bool mIsFirstConstPass;
  318. int mCurAppendAlign;
  319. public:
  320. AppendAllocVisitor()
  321. {
  322. mFailed = false;
  323. mIsFirstConstPass = false;
  324. mCurAppendAlign = 0;
  325. }
  326. void EmitAppendAlign(int align, int sizeMultiple = 0)
  327. {
  328. if (mIsFirstConstPass)
  329. mModule->mCurMethodInstance->mAppendAllocAlign = BF_MAX((int)mModule->mCurMethodInstance->mAppendAllocAlign, align);
  330. if (sizeMultiple == 0)
  331. sizeMultiple = align;
  332. if (mCurAppendAlign == 0)
  333. mCurAppendAlign = sizeMultiple;
  334. else
  335. {
  336. if (sizeMultiple % align == 0)
  337. mCurAppendAlign = align;
  338. else
  339. mCurAppendAlign = sizeMultiple % align;
  340. }
  341. if (mConstAccum)
  342. {
  343. auto constant = mModule->mBfIRBuilder->GetConstant(mConstAccum.mValue);
  344. if (constant != NULL)
  345. mConstAccum.mValue = mModule->GetConstValue(BF_ALIGN(constant->mInt64, align));
  346. else
  347. BF_ASSERT(mIsFirstConstPass);
  348. return;
  349. }
  350. mModule->EmitAppendAlign(align, sizeMultiple);
  351. }
  352. void Visit(BfAstNode* astNode) override
  353. {
  354. mModule->VisitChild(astNode);
  355. }
  356. void DoObjectCreate(BfObjectCreateExpression* objCreateExpr, BfVariableDeclaration* variableDecl)
  357. {
  358. if (auto newToken = BfNodeDynCast<BfTokenNode>(objCreateExpr->mNewNode))
  359. {
  360. if (newToken->GetToken() == BfToken_Append)
  361. {
  362. //auto variableDecl = BfNodeDynCast<BfVariableDeclaration>(objCreateExpr->mParent);
  363. auto accumValuePtr = mModule->mCurMethodState->mRetVal.mValue;
  364. auto intPtrType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  365. BfArrayType* arrayType = NULL;
  366. bool isArrayAlloc = false;
  367. bool isRawArrayAlloc = objCreateExpr->mStarToken != NULL;
  368. SizedArray<BfIRValue, 2> dimLengthVals;
  369. BfType* origResolvedTypeRef = NULL;
  370. if (auto dotTypeRef = BfNodeDynCast<BfDotTypeReference>(objCreateExpr->mTypeRef))
  371. {
  372. if (variableDecl != NULL)
  373. {
  374. origResolvedTypeRef = mModule->ResolveTypeRef(variableDecl->mTypeRef, BfPopulateType_Data, BfResolveTypeRefFlag_NoResolveGenericParam);
  375. if (origResolvedTypeRef->IsObject())
  376. {
  377. if (origResolvedTypeRef->IsArray())
  378. {
  379. arrayType = (BfArrayType*)origResolvedTypeRef;
  380. origResolvedTypeRef = origResolvedTypeRef->GetUnderlyingType();
  381. isArrayAlloc = true;
  382. }
  383. }
  384. else if (origResolvedTypeRef->IsPointer())
  385. {
  386. origResolvedTypeRef = origResolvedTypeRef->GetUnderlyingType();
  387. }
  388. }
  389. }
  390. else if (auto arrayTypeRef = BfNodeDynCast<BfArrayTypeRef>(objCreateExpr->mTypeRef))
  391. {
  392. isArrayAlloc = true;
  393. origResolvedTypeRef = mModule->ResolveTypeRef(arrayTypeRef->mElementType);
  394. int dimensions = 1;
  395. if (arrayTypeRef->mParams.size() != 0)
  396. {
  397. auto intType = mModule->ResolveTypeDef(mModule->mSystem->mTypeIntPtr);
  398. for (auto arg : arrayTypeRef->mParams)
  399. {
  400. if (auto tokenNode = BfNodeDynCastExact<BfTokenNode>(arg))
  401. {
  402. if (tokenNode->GetToken() == BfToken_Comma)
  403. {
  404. if (isRawArrayAlloc)
  405. {
  406. mModule->Fail("Sized arrays cannot be multidimensional", tokenNode);
  407. continue;
  408. }
  409. dimensions++;
  410. continue;
  411. }
  412. }
  413. auto expr = BfNodeDynCast<BfExpression>(arg);
  414. if ((isRawArrayAlloc) && (!dimLengthVals.IsEmpty()))
  415. {
  416. mModule->CreateValueFromExpression(expr, intType);
  417. continue;
  418. }
  419. BfTypedValue dimLength;
  420. if (expr == NULL)
  421. {
  422. // Not specified
  423. dimLengthVals.push_back(BfIRValue());
  424. continue;
  425. }
  426. if (arg != NULL)
  427. dimLength = mModule->CreateValueFromExpression(expr, intType);
  428. if (!dimLength)
  429. {
  430. dimLength = mModule->GetDefaultTypedValue(intType);
  431. }
  432. dimLengthVals.push_back(dimLength.mValue);
  433. }
  434. }
  435. if (!isRawArrayAlloc)
  436. arrayType = mModule->CreateArrayType(origResolvedTypeRef, dimensions);
  437. }
  438. if (origResolvedTypeRef == NULL)
  439. origResolvedTypeRef = mModule->ResolveTypeRef(objCreateExpr->mTypeRef, BfPopulateType_Data, BfResolveTypeRefFlag_NoResolveGenericParam);
  440. if (origResolvedTypeRef == NULL)
  441. {
  442. mModule->AssertErrorState();
  443. return;
  444. }
  445. bool isGenericParam = origResolvedTypeRef->IsGenericParam();
  446. auto resolvedTypeRef = origResolvedTypeRef;
  447. auto resultType = resolvedTypeRef;
  448. BfIRValue sizeValue;
  449. int curAlign = 0;
  450. if (isArrayAlloc)
  451. {
  452. int dimensions = 1;
  453. if (arrayType != NULL)
  454. dimensions = arrayType->mDimensions;
  455. bool sizeFailed = false;
  456. //
  457. {
  458. BfAstNode* initNode = objCreateExpr;
  459. for (int dim = 0; dim < dimensions; dim++)
  460. {
  461. BfAstNode* nextInitNode = NULL;
  462. int dimSize = -1;
  463. if (initNode == objCreateExpr)
  464. {
  465. dimSize = objCreateExpr->mArguments.size();
  466. if (!objCreateExpr->mArguments.IsEmpty())
  467. nextInitNode = objCreateExpr->mArguments[0];
  468. }
  469. else if (auto tupleNode = BfNodeDynCast<BfTupleExpression>(initNode))
  470. {
  471. dimSize = (int)tupleNode->mCommas.size() + 1;
  472. }
  473. if (dimSize >= 0)
  474. {
  475. if (dim >= dimLengthVals.size())
  476. dimLengthVals.Add(mModule->GetConstValue(dimSize));
  477. }
  478. else
  479. {
  480. sizeFailed = true;
  481. }
  482. }
  483. }
  484. BfIRValue allocCount;
  485. if (!sizeFailed)
  486. {
  487. if (!dimLengthVals.IsEmpty())
  488. {
  489. allocCount = dimLengthVals[0];
  490. for (int dim = 1; dim < (int)dimLengthVals.size(); dim++)
  491. allocCount = mModule->mBfIRBuilder->CreateMul(allocCount, dimLengthVals[dim]);
  492. }
  493. }
  494. if (!allocCount)
  495. {
  496. mFailed = true;
  497. if (!mIsFirstConstPass)
  498. {
  499. if (!mConstAccum)
  500. mModule->Fail("Unable to determine append alloc size", objCreateExpr->mNewNode);
  501. return;
  502. }
  503. }
  504. if (isRawArrayAlloc)
  505. {
  506. curAlign = resultType->mAlign;
  507. EmitAppendAlign(resultType->mAlign);
  508. sizeValue = mModule->mBfIRBuilder->CreateMul(mModule->GetConstValue(resultType->mSize), allocCount);
  509. }
  510. else
  511. {
  512. if (arrayType == NULL)
  513. arrayType = mModule->CreateArrayType(resultType, 1);
  514. // Array is a special case where the total size isn't aligned with mAlign
  515. // since we add arbitrary elements to the end without padding the end to align
  516. EmitAppendAlign(arrayType->mAlign, resultType->mAlign);
  517. curAlign = arrayType->mAlign;
  518. auto firstElementField = &arrayType->mFieldInstances.back();
  519. int arrayClassSize = arrayType->mInstSize - firstElementField->mDataSize;
  520. sizeValue = mModule->GetConstValue(arrayClassSize);
  521. BfIRValue elementDataSize = mModule->mBfIRBuilder->CreateMul(mModule->GetConstValue(resultType->mSize), allocCount);
  522. sizeValue = mModule->mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  523. }
  524. }
  525. else
  526. {
  527. auto typeInst = resultType->ToTypeInstance();
  528. if (typeInst != NULL)
  529. {
  530. curAlign = typeInst->mInstAlign;
  531. EmitAppendAlign(typeInst->mInstAlign, typeInst->mInstSize);
  532. sizeValue = mModule->GetConstValue(typeInst->mInstSize);
  533. }
  534. else
  535. {
  536. curAlign = resultType->mAlign;
  537. EmitAppendAlign(resultType->mAlign, resultType->mSize);
  538. sizeValue = mModule->GetConstValue(resultType->mSize);
  539. }
  540. BfTypedValue emtpyThis(mModule->mBfIRBuilder->GetFakeVal(), resultType, (typeInst == NULL) || (typeInst->IsComposite()));
  541. BfExprEvaluator exprEvaluator(mModule);
  542. SetAndRestoreValue<bool> prevNoBind(exprEvaluator.mNoBind, exprEvaluator.mNoBind || isGenericParam);
  543. BfFunctionBindResult bindResult;
  544. bindResult.mWantsArgs = true;
  545. exprEvaluator.mFunctionBindResult = &bindResult;
  546. SizedArray<BfExpression*, 8> copiedArgs;
  547. for (BfExpression* arg : objCreateExpr->mArguments)
  548. copiedArgs.push_back(arg);
  549. BfSizedArray<BfExpression*> sizedArgExprs(copiedArgs);
  550. BfResolvedArgs argValues(&sizedArgExprs);
  551. if (typeInst != NULL)
  552. {
  553. exprEvaluator.ResolveArgValues(argValues);
  554. exprEvaluator.MatchConstructor(objCreateExpr->mTypeRef, objCreateExpr, emtpyThis, typeInst, argValues, false, true);
  555. }
  556. exprEvaluator.mFunctionBindResult = NULL;
  557. if (bindResult.mMethodInstance != NULL)
  558. {
  559. if (bindResult.mMethodInstance->mMethodDef->mHasAppend)
  560. {
  561. auto calcAppendArgs = bindResult.mIRArgs;
  562. BF_ASSERT(calcAppendArgs[0].IsFake());
  563. calcAppendArgs.RemoveRange(0, 2); // Remove 'this' and 'appendIdx'
  564. auto calcAppendMethodModule = mModule->GetMethodInstanceAtIdx(bindResult.mMethodInstance->GetOwner(), bindResult.mMethodInstance->mMethodDef->mIdx + 1, BF_METHODNAME_CALCAPPEND);
  565. auto subDependSize = mModule->TryConstCalcAppend(bindResult.mMethodInstance, calcAppendArgs);
  566. if (calcAppendMethodModule.mMethodInstance->mAppendAllocAlign > 0)
  567. {
  568. EmitAppendAlign(calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  569. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign > -1);
  570. mModule->mCurMethodState->mCurAppendAlign = BF_MAX(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign, 0);
  571. }
  572. curAlign = std::max(curAlign, (int)calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  573. if ((!subDependSize) && (!mConstAccum))
  574. {
  575. BF_ASSERT(calcAppendMethodModule.mFunc);
  576. subDependSize = exprEvaluator.CreateCall(calcAppendMethodModule.mMethodInstance, calcAppendMethodModule.mFunc, false, calcAppendArgs);
  577. BF_ASSERT(subDependSize.mType == mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  578. }
  579. if (subDependSize)
  580. sizeValue = mModule->mBfIRBuilder->CreateAdd(sizeValue, subDependSize.mValue);
  581. else
  582. mFailed = true;
  583. }
  584. }
  585. }
  586. if (sizeValue)
  587. {
  588. if (mConstAccum)
  589. {
  590. if (!sizeValue.IsConst())
  591. {
  592. mFailed = true;
  593. if (!mIsFirstConstPass)
  594. return;
  595. }
  596. mConstAccum.mValue = mModule->mBfIRBuilder->CreateAdd(sizeValue, mConstAccum.mValue);
  597. }
  598. else
  599. {
  600. auto prevVal = mModule->mBfIRBuilder->CreateLoad(accumValuePtr);
  601. auto addedVal = mModule->mBfIRBuilder->CreateAdd(sizeValue, prevVal);
  602. mModule->mBfIRBuilder->CreateStore(addedVal, accumValuePtr);
  603. }
  604. }
  605. }
  606. }
  607. }
  608. void Visit(BfObjectCreateExpression* objCreateExpr) override
  609. {
  610. DoObjectCreate(objCreateExpr, NULL);
  611. }
  612. void Visit(BfVariableDeclaration* varDecl) override
  613. {
  614. if (mHasAppendAllocVisitor.HasAppendAlloc(varDecl))
  615. {
  616. if (auto objectCreateExpr = BfNodeDynCast<BfObjectCreateExpression>(varDecl->mInitializer))
  617. DoObjectCreate(objectCreateExpr, varDecl);
  618. else
  619. VisitChild(varDecl->mInitializer);
  620. if (varDecl->mNameNode != NULL)
  621. {
  622. BfLocalVariable* localDef = new BfLocalVariable();
  623. localDef->mName = varDecl->mNameNode->ToString();
  624. localDef->mNameNode = BfNodeDynCast<BfIdentifierNode>(varDecl->mNameNode);
  625. localDef->mResolvedType = mModule->GetPrimitiveType(BfTypeCode_None);
  626. localDef->mIsReadOnly = true;
  627. localDef->mParamFailed = true;
  628. localDef->mReadFromId = 0;
  629. mModule->AddLocalVariableDef(localDef);
  630. }
  631. }
  632. else
  633. {
  634. mModule->Visit(varDecl);
  635. }
  636. }
  637. void Visit(BfExpressionStatement* exprStatement) override
  638. {
  639. VisitChild(exprStatement->mExpression);
  640. }
  641. // void Visit(BfIfStatement* ifStmt) override
  642. // {
  643. // mModule->DoIfStatement(ifStmt,
  644. // mHasAppendAllocVisitor.HasAppendAlloc(ifStmt->mTrueStatement),
  645. // mHasAppendAllocVisitor.HasAppendAlloc(ifStmt->mFalseStatement));
  646. // }
  647. void Visit(BfBlock* block) override
  648. {
  649. if (!mHasAppendAllocVisitor.HasAppendAlloc(block))
  650. return;
  651. int appendAllocIdx = -1;
  652. for (int childIdx = block->mChildArr.mSize - 1; childIdx >= 0; childIdx--)
  653. {
  654. auto child = block->mChildArr.mVals[childIdx];
  655. if (mHasAppendAllocVisitor.HasAppendAlloc(child))
  656. {
  657. for (int emitIdx = 0; emitIdx <= childIdx; emitIdx++)
  658. {
  659. auto emitChild = block->mChildArr.mVals[emitIdx];
  660. mModule->UpdateSrcPos(emitChild);
  661. VisitChild(emitChild);
  662. if ((mFailed) && (!mIsFirstConstPass))
  663. break;
  664. }
  665. break;
  666. }
  667. }
  668. }
  669. };
  670. //////////////////////////////////////////////////////////////////////////
  671. BfModule* gLastCreatedModule = NULL;
  672. BfModule::BfModule(BfContext* context, const StringImpl& moduleName)
  673. {
  674. BfLogSys(context->mSystem, "BfModule::BFModule %p %s\n", this, moduleName.c_str());
  675. gLastCreatedModule = this;
  676. mContext = context;
  677. mModuleName = moduleName;
  678. if (!moduleName.empty())
  679. mContext->mUsedModuleNames.Add(ToUpper(moduleName));
  680. mAddedToCount = false;
  681. mParentModule = NULL;
  682. mNextAltModule = NULL;
  683. mBfIRBuilder = NULL;
  684. mWantsIRIgnoreWrites = false;
  685. mModuleOptions = NULL;
  686. mLastUsedRevision = -1;
  687. mUsedSlotCount = -1;
  688. mIsReified = true;
  689. mReifyQueued = false;
  690. mIsSpecialModule = false;
  691. mIsScratchModule = false;
  692. mIsSpecializedMethodModuleRoot = false; // There may be mNextAltModules extending from this
  693. mHadBuildError = false;
  694. mHadBuildWarning = false;
  695. mIgnoreErrors = false;
  696. mIgnoreWarnings = false;
  697. mReportErrors = true;
  698. mIsInsideAutoComplete = false;
  699. mIsDeleting = false;
  700. mSkipInnerLookup = false;
  701. mIsHotModule = false;
  702. mSetIllegalSrcPosition = false;
  703. mNoResolveGenericParams = false;
  704. mWroteToLib = false;
  705. mContext = context;
  706. mCompiler = context->mCompiler;
  707. mSystem = mCompiler->mSystem;
  708. mProject = NULL;
  709. mCurMethodState = NULL;
  710. mAttributeState = NULL;
  711. mCurLocalMethodId = 0;
  712. mParentNodeEntry = NULL;
  713. mRevision = -1;
  714. mRebuildIdx = 0;
  715. mLastModuleWrittenRevision = 0;
  716. mIsModuleMutable = false;
  717. mExtensionCount = 0;
  718. mIncompleteMethodCount = 0;
  719. mOnDemandMethodCount = 0;
  720. mHasGenericMethods = false;
  721. mCurMethodInstance = NULL;
  722. mCurTypeInstance = NULL;
  723. mAwaitingInitFinish = false;
  724. mAwaitingFinish = false;
  725. mHasFullDebugInfo = false;
  726. mHadHotObjectWrites = false;
  727. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  728. mBuiltInFuncs[i] = BfIRFunction();
  729. BfLogSysM("Creating module %p: %s Reified: %d ResolveOnly: %d\n", this, mModuleName.c_str(), mIsReified, mCompiler->mIsResolveOnly);
  730. }
  731. void BfReportMemory();
  732. BfModule::~BfModule()
  733. {
  734. BfLogSysM("Deleting module %p: %s \n", this, mModuleName.c_str());
  735. if (!mIsDeleting)
  736. RemoveModuleData();
  737. }
  738. void BfModule::RemoveModuleData()
  739. {
  740. BF_ASSERT(!mIsDeleting);
  741. if (!mModuleName.empty())
  742. {
  743. // Note: module names not necessarily unique
  744. mContext->mUsedModuleNames.Remove(ToUpper(mModuleName));
  745. }
  746. CleanupFileInstances();
  747. delete mBfIRBuilder;
  748. mBfIRBuilder = NULL;
  749. //delete mCpu;
  750. for (auto prevModule : mPrevIRBuilders)
  751. delete prevModule;
  752. mPrevIRBuilders.Clear();
  753. for (auto& pairVal : mDeferredMethodCallData)
  754. delete pairVal.mValue;
  755. mDeferredMethodCallData.Clear();
  756. mDeferredMethodIds.Clear();
  757. for (auto& specModulePair : mSpecializedMethodModules)
  758. delete specModulePair.mValue;
  759. mSpecializedMethodModules.Clear();
  760. if (mNextAltModule != NULL)
  761. delete mNextAltModule;
  762. mNextAltModule = NULL;
  763. if (mModuleOptions != NULL)
  764. delete mModuleOptions;
  765. mModuleOptions = NULL;
  766. BfReportMemory();
  767. }
  768. void BfModule::Init(bool isFullRebuild)
  769. {
  770. mContext->mFinishedModuleWorkList.Remove(this);
  771. if ((mCompiler->mIsResolveOnly) && (this != mContext->mUnreifiedModule))
  772. BF_ASSERT(mIsReified);
  773. if (!mIsScratchModule)
  774. {
  775. mCompiler->mStats.mModulesStarted++;
  776. if (mIsReified)
  777. mCompiler->mStats.mReifiedModuleCount++;
  778. mAddedToCount = true;
  779. }
  780. mIsHotModule = (mProject != NULL) && (mCompiler->mOptions.mHotProject != NULL) && (mCompiler->mOptions.mHotProject->ContainsReference(mProject));
  781. mFuncReferences.Clear();
  782. mClassVDataRefs.Clear();
  783. mClassVDataExtRefs.Clear();
  784. //mTypeDataRefs.Clear();
  785. mDbgRawAllocDataRefs.Clear();
  786. CleanupFileInstances();
  787. mStaticFieldRefs.Clear();
  788. //mInterfaceSlotRefs.Clear();
  789. // If we are just doing an extension then the ownede types aren't rebuilt.
  790. // If we set mRevision then QueueMethodSpecializations wouldn't actually queue up required specializations
  791. // and we'd end up with link errors if the original module uniquely referred to any generic methods
  792. if (isFullRebuild)
  793. mRevision = mCompiler->mRevision;
  794. BF_ASSERT(mCurTypeInstance == NULL);
  795. mIsModuleMutable = true;
  796. BF_ASSERT((mBfIRBuilder == NULL) || (mCompiler->mIsResolveOnly));
  797. #ifdef _DEBUG
  798. EnsureIRBuilder(mCompiler->mLastAutocompleteModule == this);
  799. #else
  800. EnsureIRBuilder(false);
  801. #endif
  802. mCurMethodState = NULL;
  803. mAwaitingInitFinish = true;
  804. mOnDemandMethodCount = 0;
  805. mAwaitingFinish = false;
  806. mHasForceLinkMarker = false;
  807. mUsedSlotCount = -1;
  808. }
  809. bool BfModule::WantsFinishModule()
  810. {
  811. return (mIncompleteMethodCount == 0) && (mOnDemandMethodCount == 0) && (!mHasGenericMethods) && (!mIsScratchModule) && (mExtensionCount == 0) && (mParentModule == NULL);
  812. }
  813. void BfModule::FinishInit()
  814. {
  815. BF_ASSERT(mAwaitingInitFinish);
  816. auto moduleOptions = GetModuleOptions();
  817. mBfIRBuilder->Start(mModuleName, mCompiler->mSystem->mPtrSize, IsOptimized());
  818. mBfIRBuilder->Module_SetTargetTriple(mCompiler->mOptions.mTargetTriple);
  819. mBfIRBuilder->SetBackend(IsTargetingBeefBackend());
  820. if (moduleOptions.mOptLevel == BfOptLevel_OgPlus)
  821. {
  822. // Og+ requires debug info
  823. moduleOptions.mEmitDebugInfo = 1;
  824. }
  825. mHasFullDebugInfo = moduleOptions.mEmitDebugInfo == 1;
  826. if ((!mCompiler->mIsResolveOnly) && (!mIsScratchModule) && (moduleOptions.mEmitDebugInfo != 0) && (mIsReified))
  827. {
  828. mBfIRBuilder->DbgInit();
  829. }
  830. else
  831. mHasFullDebugInfo = false;
  832. if ((mBfIRBuilder->DbgHasInfo()) && (mModuleName != "") &&
  833. ((moduleOptions.mEmitDebugInfo != 0)))
  834. {
  835. if (mCompiler->mOptions.IsCodeView())
  836. {
  837. mBfIRBuilder->Module_AddModuleFlag("CodeView", 1);
  838. }
  839. else
  840. {
  841. mBfIRBuilder->Module_AddModuleFlag("Dwarf Version", 4);
  842. }
  843. mBfIRBuilder->Module_AddModuleFlag("Debug Info Version", 3);
  844. mDICompileUnit = mBfIRBuilder->DbgCreateCompileUnit(llvm::dwarf::DW_LANG_C_plus_plus, mModuleName, ".", "Beef Compiler 0.42", /*moduleOptions.mOptLevel > 0*/false, "", 0, !mHasFullDebugInfo);
  845. }
  846. mAwaitingInitFinish = false;
  847. }
  848. void BfModule::ReifyModule()
  849. {
  850. BF_ASSERT((mCompiler->mCompileState != BfCompiler::CompileState_Unreified) && (mCompiler->mCompileState != BfCompiler::CompileState_VData));
  851. BfLogSysM("ReifyModule %@ %s\n", this, mModuleName.c_str());
  852. BF_ASSERT((this != mContext->mScratchModule) && (this != mContext->mUnreifiedModule));
  853. mIsReified = true;
  854. mReifyQueued = false;
  855. StartNewRevision(RebuildKind_SkipOnDemandTypes, true);
  856. mCompiler->mStats.mModulesReified++;
  857. }
  858. void BfModule::UnreifyModule()
  859. {
  860. BfLogSysM("UnreifyModule %p %s\n", this, mModuleName.c_str());
  861. BF_ASSERT((this != mContext->mScratchModule) && (this != mContext->mUnreifiedModule));
  862. mIsReified = false;
  863. mReifyQueued = false;
  864. StartNewRevision(RebuildKind_None, true);
  865. mCompiler->mStats.mModulesUnreified++;
  866. }
  867. void BfModule::CleanupFileInstances()
  868. {
  869. for (auto& itr : mNamedFileInstanceMap)
  870. {
  871. BfLogSysM("FileInstance deleted: %p\n", itr.mValue);
  872. delete itr.mValue;
  873. }
  874. mCurFilePosition.mFileInstance = NULL;//
  875. mFileInstanceMap.Clear();
  876. mNamedFileInstanceMap.Clear();
  877. }
  878. void BfModule::Cleanup()
  879. {
  880. CleanupFileInstances();
  881. }
  882. void BfModule::PrepareForIRWriting(BfTypeInstance* typeInst)
  883. {
  884. if (HasCompiledOutput())
  885. {
  886. // It's possible that the target's code hasn't changed but we're requesting a new generic method specialization
  887. if ((!mIsModuleMutable) && (!typeInst->IsUnspecializedType()) && (!typeInst->mResolvingVarField))
  888. {
  889. StartExtension();
  890. }
  891. }
  892. else
  893. {
  894. EnsureIRBuilder();
  895. }
  896. }
  897. void BfModule::EnsureIRBuilder(bool dbgVerifyCodeGen)
  898. {
  899. BF_ASSERT(!mIsDeleting);
  900. if (mBfIRBuilder == NULL)
  901. {
  902. if ((!mIsScratchModule) && (!mAddedToCount))
  903. {
  904. mCompiler->mStats.mModulesStarted++;
  905. mAddedToCount = true;
  906. }
  907. BF_ASSERT(mStaticFieldRefs.GetCount() == 0);
  908. /*if (mCompiler->mIsResolveOnly)
  909. BF_ASSERT(mIsResolveOnly);*/
  910. mBfIRBuilder = new BfIRBuilder(this);
  911. BfLogSysM("Created mBfIRBuilder %p in %p %s Reified: %d\n", mBfIRBuilder, this, mModuleName.c_str(), mIsReified);
  912. if (mIsScratchModule)
  913. {
  914. mBfIRBuilder->mIgnoreWrites = true;
  915. BF_ASSERT(!dbgVerifyCodeGen);
  916. }
  917. #ifdef _DEBUG
  918. if (mCompiler->mIsResolveOnly)
  919. {
  920. // For "deep" verification testing
  921. /*if (!mIsSpecialModule)
  922. dbgVerifyCodeGen = true;*/
  923. // We only want to turn this off on smaller builds for testing
  924. mBfIRBuilder->mIgnoreWrites = true;
  925. if (dbgVerifyCodeGen)
  926. mBfIRBuilder->mIgnoreWrites = false;
  927. if (!mBfIRBuilder->mIgnoreWrites)
  928. {
  929. // The only purpose of not ignoring writes is so we can verify the codegen one instruction at a time
  930. mBfIRBuilder->mDbgVerifyCodeGen = true;
  931. }
  932. }
  933. else if (!mIsReified)
  934. {
  935. mBfIRBuilder->mIgnoreWrites = true;
  936. }
  937. else
  938. {
  939. // We almost always want this to be 'false' unless we need need to be able to inspect the generated LLVM
  940. // code as we walk the AST
  941. //mBfIRBuilder->mDbgVerifyCodeGen = true;
  942. if (
  943. (mModuleName == "Blurg")
  944. //|| (mModuleName == "System_Internal")
  945. //|| (mModuleName == "vdata")
  946. //|| (mModuleName == "Hey_Dude_Bro_TestClass")
  947. )
  948. mBfIRBuilder->mDbgVerifyCodeGen = true;
  949. // Just for testing!
  950. //mBfIRBuilder->mIgnoreWrites = true;
  951. }
  952. #else
  953. if (mCompiler->mIsResolveOnly)
  954. {
  955. // Always ignore writes in resolveOnly for release builds
  956. mBfIRBuilder->mIgnoreWrites = true;
  957. }
  958. else
  959. {
  960. // Just for memory testing! This breaks everything.
  961. //mBfIRBuilder->mIgnoreWrites = true;
  962. // For "deep" verification testing
  963. //mBfIRBuilder->mDbgVerifyCodeGen = true;
  964. }
  965. #endif
  966. mWantsIRIgnoreWrites = mBfIRBuilder->mIgnoreWrites;
  967. }
  968. }
  969. BfIRValue BfModule::CreateForceLinkMarker(BfModule* module, String* outName)
  970. {
  971. String name = "FORCELINKMOD_" + module->mModuleName;
  972. if (outName != NULL)
  973. *outName = name;
  974. auto markerType = GetPrimitiveType(BfTypeCode_Int8);
  975. return mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(markerType), true, BfIRLinkageType_External, (module == this) ? mBfIRBuilder->CreateConst(BfTypeCode_Int8, 0) : BfIRValue(), name);
  976. }
  977. void BfModule::StartNewRevision(RebuildKind rebuildKind, bool force)
  978. {
  979. BP_ZONE("BfModule::StartNewRevision");
  980. // The project MAY be deleted because disabling a project can cause types to be deleted which
  981. // causes other types rebuild BEFORE they get deleted, which is okay (though wasteful)
  982. //BF_ASSERT((mProject == NULL) || (!mProject->mDisabled));
  983. // Already on new revision?
  984. if ((mRevision == mCompiler->mRevision) && (!force))
  985. return;
  986. mHadBuildError = false;
  987. mHadBuildWarning = false;
  988. mExtensionCount = 0;
  989. mRevision = mCompiler->mRevision;
  990. mRebuildIdx++;
  991. ClearModuleData();
  992. // Clear this here, not in ClearModuleData, so we preserve those references even after writing out module
  993. if (rebuildKind != BfModule::RebuildKind_None) // Leave string pool refs for when we need to use things like [LinkName("")] methods bofore re-reification
  994. mStringPoolRefs.Clear();
  995. mDllImportEntries.Clear();
  996. mImportFileNames.Clear();
  997. for (auto& pairVal : mDeferredMethodCallData)
  998. delete pairVal.mValue;
  999. mDeferredMethodCallData.Clear();
  1000. mDeferredMethodIds.Clear();
  1001. mModuleRefs.Clear();
  1002. mOutFileNames.Clear();
  1003. mTypeDataRefs.Clear();
  1004. mInterfaceSlotRefs.Clear();
  1005. if (rebuildKind == BfModule::RebuildKind_None)
  1006. {
  1007. for (auto& specPair : mSpecializedMethodModules)
  1008. {
  1009. auto specModule = specPair.mValue;
  1010. if (specModule->mIsReified != mIsReified)
  1011. {
  1012. if (mIsReified)
  1013. specModule->ReifyModule();
  1014. else
  1015. specModule->UnreifyModule();
  1016. }
  1017. }
  1018. }
  1019. else
  1020. {
  1021. for (auto& specPair : mSpecializedMethodModules)
  1022. {
  1023. auto specModule = specPair.mValue;
  1024. delete specModule;
  1025. }
  1026. }
  1027. mSpecializedMethodModules.Clear();
  1028. delete mNextAltModule;
  1029. mNextAltModule = NULL;
  1030. BF_ASSERT(mModuleOptions == NULL);
  1031. BfLogSysM("Mod:%p StartNewRevision: %s Revision: %d\n", this, mModuleName.c_str(), mRevision);
  1032. bool needsTypePopulated = false;
  1033. int oldOnDemandCount = 0;
  1034. // We don't have to rebuild types in the unspecialized module because there is no
  1035. // data that's needed -- their method instances are all NULL and the module
  1036. // doesn't get included in the build
  1037. if (this != mContext->mScratchModule)
  1038. {
  1039. for (int typeIdx = 0; typeIdx < (int)mOwnedTypeInstances.size(); typeIdx++)
  1040. {
  1041. auto typeInst = mOwnedTypeInstances[typeIdx];
  1042. if (!typeInst->IsDeleting())
  1043. {
  1044. typeInst->mIsReified = mIsReified;
  1045. if (rebuildKind != BfModule::RebuildKind_None)
  1046. {
  1047. if (typeInst->IsOnDemand())
  1048. {
  1049. // Changing config should require on demand types to be recreated, but reifying a module shouldn't cause the type to be deleted
  1050. if (rebuildKind == BfModule::RebuildKind_All)
  1051. mContext->DeleteType(typeInst);
  1052. else
  1053. {
  1054. RebuildMethods(typeInst);
  1055. }
  1056. }
  1057. else
  1058. mContext->RebuildType(typeInst, false, false, false);
  1059. }
  1060. else
  1061. {
  1062. for (auto& methodGroup : typeInst->mMethodInstanceGroups)
  1063. if ((methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) ||
  1064. (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference))
  1065. {
  1066. oldOnDemandCount++;
  1067. }
  1068. }
  1069. if (typeInst->IsDeleting())
  1070. typeIdx--;
  1071. }
  1072. }
  1073. }
  1074. if (!mIsDeleting)
  1075. Init();
  1076. mOnDemandMethodCount += oldOnDemandCount;
  1077. }
  1078. void BfModule::StartExtension()
  1079. {
  1080. BF_ASSERT(!mIsModuleMutable);
  1081. BfLogSysM("Extension started of module %p\n", this);
  1082. mExtensionCount++;
  1083. if (mBfIRBuilder != NULL)
  1084. mPrevIRBuilders.push_back(mBfIRBuilder);
  1085. mBfIRBuilder = NULL;
  1086. mWantsIRIgnoreWrites = false;
  1087. mFuncReferences.Clear();
  1088. mClassVDataRefs.Clear();
  1089. mClassVDataExtRefs.Clear();
  1090. for (auto& kv : mTypeDataRefs)
  1091. kv.mValue = BfIRValue();
  1092. mDbgRawAllocDataRefs.Clear();
  1093. mStringCharPtrPool.Clear();
  1094. mStringObjectPool.Clear();
  1095. mStaticFieldRefs.Clear();
  1096. for (auto& kv : mInterfaceSlotRefs)
  1097. kv.mValue = BfIRValue();
  1098. mDeferredMethodCallData.Clear();
  1099. mDeferredMethodIds.Clear();
  1100. DisownMethods();
  1101. BfLogSysM("Mod:%p StartExtension: %s\n", this, mModuleName.c_str());
  1102. bool wasAwaitingInitFinish = mAwaitingInitFinish;
  1103. int prevOnDemandMethodCount = mOnDemandMethodCount;
  1104. Init(false);
  1105. if (!wasAwaitingInitFinish)
  1106. FinishInit();
  1107. mOnDemandMethodCount = prevOnDemandMethodCount;
  1108. }
  1109. void BfModule::GetConstClassValueParam(BfIRValue classVData, SizedArrayImpl<BfIRValue>& typeValueParams)
  1110. {
  1111. BfIRValue vDataValue;
  1112. if (mCompiler->mOptions.mObjectHasDebugFlags)
  1113. vDataValue = mBfIRBuilder->CreatePtrToInt(classVData, BfTypeCode_IntPtr);
  1114. else
  1115. vDataValue = mBfIRBuilder->CreateBitCast(classVData, mBfIRBuilder->MapType(mContext->mBfClassVDataPtrType));
  1116. typeValueParams.push_back(vDataValue);
  1117. if (mCompiler->mOptions.mObjectHasDebugFlags)
  1118. {
  1119. auto primType = GetPrimitiveType(BfTypeCode_IntPtr);
  1120. typeValueParams.push_back(GetDefaultValue(primType));
  1121. }
  1122. }
  1123. BfIRValue BfModule::GetConstValue(int64 val)
  1124. {
  1125. return mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)val);
  1126. }
  1127. BfIRValue BfModule::GetConstValue(int64 val, BfType* type)
  1128. {
  1129. BfType* checkType = type;
  1130. if (type->IsTypedPrimitive())
  1131. {
  1132. checkType = type->GetUnderlyingType();
  1133. }
  1134. if (checkType->IsPrimitiveType())
  1135. {
  1136. auto primType = (BfPrimitiveType*)checkType;
  1137. if (checkType->IsFloat())
  1138. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (double)val);
  1139. else
  1140. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (uint64)val);
  1141. }
  1142. return BfIRValue();
  1143. }
  1144. BfIRValue BfModule::GetConstValue8(int val)
  1145. {
  1146. return mBfIRBuilder->CreateConst(BfTypeCode_Int8, (uint64)val);
  1147. }
  1148. BfIRValue BfModule::GetConstValue32(int32 val)
  1149. {
  1150. return mBfIRBuilder->CreateConst(BfTypeCode_Int32, (uint64)val);
  1151. }
  1152. BfIRValue BfModule::GetConstValue64(int64 val)
  1153. {
  1154. return mBfIRBuilder->CreateConst(BfTypeCode_Int64, (uint64)val);
  1155. }
  1156. BfIRValue BfModule::GetDefaultValue(BfType* type)
  1157. {
  1158. PopulateType(type, BfPopulateType_Data);
  1159. mBfIRBuilder->PopulateType(type, BfIRPopulateType_Declaration);
  1160. if (type->IsTypedPrimitive())
  1161. {
  1162. auto underlyingType = type->GetUnderlyingType();
  1163. if (underlyingType == NULL)
  1164. return mBfIRBuilder->CreateConst(BfTypeCode_Int64, 0);
  1165. return GetDefaultValue(type->GetUnderlyingType());
  1166. }
  1167. if (type->IsPointer() || type->IsObjectOrInterface() || type->IsGenericParam() || type->IsVar() || type->IsRef() || type->IsNull() ||
  1168. type->IsRetTypeType() || type->IsConcreteInterfaceType())
  1169. return mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(type));
  1170. if ((type->IsIntegral()) || (type->IsBoolean()))
  1171. {
  1172. auto primType = (BfPrimitiveType*)type;
  1173. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (uint64)0);
  1174. }
  1175. if (type->IsFloat())
  1176. {
  1177. auto primType = (BfPrimitiveType*)type;
  1178. return mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, 0.0);
  1179. }
  1180. if (type->IsVoid())
  1181. return mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(type));
  1182. return mBfIRBuilder->CreateConstStructZero(mBfIRBuilder->MapType(type));
  1183. }
  1184. BfTypedValue BfModule::GetFakeTypedValue(BfType* type)
  1185. {
  1186. // This is a conservative "IsValueless", since it's not an error to use a fakeVal even if we don't need one
  1187. if (type->mSize == 0)
  1188. return BfTypedValue(BfIRValue::sValueless, type);
  1189. else
  1190. return BfTypedValue(mBfIRBuilder->GetFakeVal(), type);
  1191. }
  1192. BfTypedValue BfModule::GetDefaultTypedValue(BfType* type, bool allowRef, BfDefaultValueKind defaultValueKind)
  1193. {
  1194. PopulateType(type, BfPopulateType_Data);
  1195. mBfIRBuilder->PopulateType(type, type->IsValueType() ? BfIRPopulateType_Full : BfIRPopulateType_Declaration);
  1196. if (defaultValueKind == BfDefaultValueKind_Undef)
  1197. {
  1198. auto primType = type->ToPrimitiveType();
  1199. if (primType != NULL)
  1200. {
  1201. return BfTypedValue(mBfIRBuilder->GetUndefConstValue(primType->mTypeDef->mTypeCode), type);
  1202. }
  1203. return BfTypedValue(mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(type)), type);
  1204. }
  1205. BfTypedValue typedValue;
  1206. if ((defaultValueKind != BfDefaultValueKind_Const) && (!type->IsValuelessType()))
  1207. {
  1208. if (type->IsRef())
  1209. {
  1210. BfRefType* refType = (BfRefType*)type;
  1211. BfType* underlyingType = refType->GetUnderlyingType();
  1212. typedValue = BfTypedValue(CreateAlloca(underlyingType), underlyingType, BfTypedValueKind_Addr);
  1213. }
  1214. else
  1215. {
  1216. typedValue = BfTypedValue(CreateAlloca(type), type, BfTypedValueKind_Addr);
  1217. }
  1218. if (!mBfIRBuilder->mIgnoreWrites)
  1219. {
  1220. mBfIRBuilder->CreateMemSet(typedValue.mValue, GetConstValue(0, GetPrimitiveType(BfTypeCode_Int8)),
  1221. GetConstValue(type->mSize), type->mAlign);
  1222. }
  1223. if ((defaultValueKind == BfDefaultValueKind_Value) && (!type->IsRef()))
  1224. typedValue = LoadValue(typedValue);
  1225. return typedValue;
  1226. }
  1227. if ((type->IsRef()) && (!allowRef))
  1228. {
  1229. BfRefType* refType = (BfRefType*)type;
  1230. BfType* underlyingType = refType->GetUnderlyingType();
  1231. if (underlyingType->IsValuelessType())
  1232. typedValue = BfTypedValue(mBfIRBuilder->GetFakeVal(), underlyingType, true);
  1233. else
  1234. typedValue = BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(type)), underlyingType, true);
  1235. }
  1236. else
  1237. {
  1238. typedValue = BfTypedValue(GetDefaultValue(type), type, (defaultValueKind == BfDefaultValueKind_Addr) ? BfTypedValueKind_Addr : BfTypedValueKind_Value);
  1239. }
  1240. return typedValue;
  1241. }
  1242. BfIRValue BfModule::CreateStringCharPtr(const StringImpl& str, int stringId, bool define)
  1243. {
  1244. String stringDataName = StrFormat("__bfStrData%d", stringId);
  1245. BfIRType strCharType;
  1246. //
  1247. {
  1248. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mWantsIRIgnoreWrites);
  1249. strCharType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_Char8), (int)str.length() + 1);
  1250. }
  1251. BfIRValue strConstant;
  1252. if (define)
  1253. {
  1254. strConstant = mBfIRBuilder->CreateConstString(str);
  1255. }
  1256. BfIRValue gv = mBfIRBuilder->CreateGlobalVariable(strCharType,
  1257. true, BfIRLinkageType_External,
  1258. strConstant, stringDataName);
  1259. if (define)
  1260. mBfIRBuilder->GlobalVar_SetUnnamedAddr(gv, true);
  1261. return mBfIRBuilder->CreateInBoundsGEP(gv, 0, 0);
  1262. }
  1263. BfIRValue BfModule::CreateStringObjectValue(const StringImpl& str, int stringId, bool define)
  1264. {
  1265. auto stringTypeInst = ResolveTypeDef(mCompiler->mStringTypeDef, define ? BfPopulateType_Data : BfPopulateType_Declaration)->ToTypeInstance();
  1266. mBfIRBuilder->PopulateType(stringTypeInst);
  1267. auto classVDataGlobal = CreateClassVDataGlobal(stringTypeInst);
  1268. String stringObjName = StrFormat("__bfStrObj%d", stringId);
  1269. BfIRValue stringValData;
  1270. if (define)
  1271. {
  1272. BfIRValue stringCharsVal = CreateStringCharPtr(str, stringId, define);
  1273. mStringCharPtrPool[stringId] = stringCharsVal;
  1274. SizedArray<BfIRValue, 8> typeValueParams;
  1275. GetConstClassValueParam(classVDataGlobal, typeValueParams);
  1276. auto objData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(stringTypeInst->mBaseType, BfIRPopulateType_Full), typeValueParams);
  1277. auto lenByteCount = stringTypeInst->mFieldInstances[0].mResolvedType->mSize;
  1278. typeValueParams.clear();
  1279. typeValueParams.push_back(objData);
  1280. if (lenByteCount == 4)
  1281. {
  1282. typeValueParams.push_back(GetConstValue32((int)str.length())); // mLength
  1283. typeValueParams.push_back(GetConstValue32((int32)(0x40000000 + str.length() + 1))); // mAllocSizeAndFlags
  1284. }
  1285. else
  1286. {
  1287. typeValueParams.push_back(GetConstValue64(str.length())); // mLength
  1288. typeValueParams.push_back(GetConstValue64(0x4000000000000000LL + str.length() + 1)); // mAllocSizeAndFlags
  1289. }
  1290. typeValueParams.push_back(stringCharsVal); // mPtr
  1291. stringValData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(stringTypeInst, BfIRPopulateType_Full), typeValueParams);
  1292. }
  1293. auto stringValLiteral = mBfIRBuilder->CreateGlobalVariable(
  1294. mBfIRBuilder->MapTypeInst(stringTypeInst),
  1295. true,
  1296. BfIRLinkageType_External,
  1297. define ? stringValData : BfIRValue(),
  1298. stringObjName);
  1299. auto stringVal = mBfIRBuilder->CreateBitCast(stringValLiteral, mBfIRBuilder->MapType(stringTypeInst, BfIRPopulateType_Full));
  1300. return stringVal;
  1301. }
  1302. int BfModule::GetStringPoolIdx(BfIRValue constantStr, BfIRConstHolder* constHolder)
  1303. {
  1304. BF_ASSERT(constantStr.IsConst());
  1305. if (constHolder == NULL)
  1306. constHolder = mBfIRBuilder;
  1307. auto constant = constHolder->GetConstant(constantStr);
  1308. if (constant->mTypeCode == BfTypeCode_Int32)
  1309. {
  1310. return constant->mInt32;
  1311. }
  1312. while (constant->mConstType == BfConstType_BitCast)
  1313. {
  1314. auto constBitCast = (BfConstantBitCast*)constant;
  1315. constant = constHolder->GetConstantById(constBitCast->mTarget);
  1316. }
  1317. if (constant->mConstType == BfConstType_GEP32_2)
  1318. {
  1319. auto constGEP = (BfConstantGEP32_2*)constant;
  1320. constant = constHolder->GetConstantById(constGEP->mTarget);
  1321. }
  1322. if (constant->mConstType == BfConstType_GlobalVar)
  1323. {
  1324. auto constGV = (BfGlobalVar*)constant;
  1325. const char* strDataPrefix = "__bfStrData";
  1326. if (strncmp(constGV->mName, strDataPrefix, strlen(strDataPrefix)) == 0)
  1327. return atoi(constGV->mName + strlen(strDataPrefix));
  1328. const char* strObjPrefix = "__bfStrObj";
  1329. if (strncmp(constGV->mName, strObjPrefix, strlen(strObjPrefix)) == 0)
  1330. return atoi(constGV->mName + strlen(strObjPrefix));
  1331. }
  1332. return -1;
  1333. }
  1334. String* BfModule::GetStringPoolString(BfIRValue constantStr, BfIRConstHolder * constHolder)
  1335. {
  1336. int strId = GetStringPoolIdx(constantStr, constHolder);
  1337. if (strId != -1)
  1338. {
  1339. auto& entry = mContext->mStringObjectIdMap[strId];
  1340. return &entry.mString;
  1341. }
  1342. return NULL;
  1343. }
  1344. BfIRValue BfModule::GetStringCharPtr(int stringId)
  1345. {
  1346. BfIRValue* irValue = NULL;
  1347. if (!mStringCharPtrPool.TryAdd(stringId, NULL, &irValue))
  1348. return *irValue;
  1349. // If this wasn't in neither dictionary yet, add to mStringPoolRefs
  1350. if (!mStringObjectPool.ContainsKey(stringId))
  1351. mStringPoolRefs.Add(stringId);
  1352. const StringImpl& str = mContext->mStringObjectIdMap[stringId].mString;
  1353. BfIRValue strCharPtrConst = CreateStringCharPtr(str, stringId, false);
  1354. *irValue = strCharPtrConst;
  1355. return strCharPtrConst;
  1356. }
  1357. BfIRValue BfModule::GetStringCharPtr(BfIRValue strValue)
  1358. {
  1359. if (strValue.IsConst())
  1360. {
  1361. int stringId = GetStringPoolIdx(strValue);
  1362. BF_ASSERT(stringId != -1);
  1363. return GetStringCharPtr(stringId);
  1364. }
  1365. BfIRValue charPtrPtr = mBfIRBuilder->CreateInBoundsGEP(strValue, 0, 1);
  1366. BfIRValue charPtr = mBfIRBuilder->CreateLoad(charPtrPtr);
  1367. return charPtr;
  1368. }
  1369. BfIRValue BfModule::GetStringCharPtr(const StringImpl& str)
  1370. {
  1371. return GetStringCharPtr(GetStringObjectValue(str));
  1372. }
  1373. BfIRValue BfModule::GetStringObjectValue(int strId)
  1374. {
  1375. BfIRValue* objValue;
  1376. if (mStringObjectPool.TryGetValue(strId, &objValue))
  1377. return *objValue;
  1378. auto stringPoolEntry = mContext->mStringObjectIdMap[strId];
  1379. return GetStringObjectValue(stringPoolEntry.mString, true);
  1380. }
  1381. BfIRValue BfModule::GetStringObjectValue(const StringImpl& str, bool define)
  1382. {
  1383. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef, define ? BfPopulateType_Data : BfPopulateType_Declaration);
  1384. mBfIRBuilder->PopulateType(stringType);
  1385. int strId = mContext->GetStringLiteralId(str);
  1386. BfIRValue* irValuePtr = NULL;
  1387. if (!mStringObjectPool.TryAdd(strId, NULL, &irValuePtr))
  1388. return *irValuePtr;
  1389. // If this wasn't in neither dictionary yet, add to mStringPoolRefs
  1390. if (!mStringCharPtrPool.ContainsKey(strId))
  1391. mStringPoolRefs.Add(strId);
  1392. BfIRValue strObject = CreateStringObjectValue(str, strId, define);
  1393. *irValuePtr = strObject;
  1394. mStringPoolRefs.Add(strId);
  1395. return strObject;
  1396. }
  1397. BfIRValue BfModule::CreateGlobalConstValue(const StringImpl& name, BfIRValue constant, BfIRType type, bool external)
  1398. {
  1399. auto newConst = mBfIRBuilder->CreateGlobalVariable(
  1400. type,
  1401. true,
  1402. external ? BfIRLinkageType_External : BfIRLinkageType_Internal,
  1403. constant,
  1404. name.c_str());
  1405. return newConst;
  1406. }
  1407. void BfModule::NewScopeState(bool createLexicalBlock, bool flushValueScope)
  1408. {
  1409. auto curScope = mCurMethodState->mCurScope;
  1410. if (curScope->mLabelNode != NULL)
  1411. curScope->mLabelNode->ToString(curScope->mLabel);
  1412. if (!mCurMethodState->mCurScope->mLabel.IsEmpty())
  1413. {
  1414. auto checkScope = mCurMethodState->mCurScope->mPrevScope;
  1415. while (checkScope != NULL)
  1416. {
  1417. if (checkScope->mLabel == mCurMethodState->mCurScope->mLabel)
  1418. {
  1419. auto errorNode = Fail("Duplicate scope label", curScope->mLabelNode);
  1420. if (errorNode != NULL)
  1421. mCompiler->mPassInstance->MoreInfo("See previous scope label", checkScope->mLabelNode);
  1422. break;
  1423. }
  1424. checkScope = checkScope->mPrevScope;
  1425. }
  1426. }
  1427. auto prevScope = mCurMethodState->mCurScope->mPrevScope;
  1428. if ((flushValueScope) && (prevScope != NULL) && (prevScope->mValueScopeStart))
  1429. {
  1430. if (prevScope->mHadScopeValueRetain)
  1431. mBfIRBuilder->CreateValueScopeSoftEnd(prevScope->mValueScopeStart);
  1432. else
  1433. mBfIRBuilder->CreateValueScopeHardEnd(prevScope->mValueScopeStart);
  1434. }
  1435. mCurMethodState->mBlockNestLevel++;
  1436. if ((createLexicalBlock) && (mBfIRBuilder->DbgHasInfo()) && (mHasFullDebugInfo))
  1437. {
  1438. // DIScope could be NULL if we're in an unspecialized method (for example)
  1439. if (mCurMethodState->mCurScope->mDIScope)
  1440. mCurMethodState->mCurScope->mDIScope = mBfIRBuilder->DbgCreateLexicalBlock(mCurMethodState->mCurScope->mDIScope, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mCurFilePosition.mCurColumn);
  1441. }
  1442. mCurMethodState->mCurScope->mLocalVarStart = (int)mCurMethodState->mLocals.size();
  1443. mCurMethodState->mCurScope->mBlock = mBfIRBuilder->MaybeChainNewBlock((!mCurMethodState->mCurScope->mLabel.empty()) ? mCurMethodState->mCurScope->mLabel : "newScope");
  1444. }
  1445. void BfModule::RestoreScoreState_LocalVariables()
  1446. {
  1447. while (mCurMethodState->mCurScope->mLocalVarStart < (int)mCurMethodState->mLocals.size())
  1448. {
  1449. auto localVar = mCurMethodState->mLocals.back();
  1450. LocalVariableDone(localVar, false);
  1451. mCurMethodState->mLocals.pop_back();
  1452. if (localVar->mShadowedLocal != NULL)
  1453. {
  1454. BfLocalVarEntry* localVarEntryPtr;
  1455. if (mCurMethodState->mLocalVarSet.TryGet(BfLocalVarEntry(localVar), &localVarEntryPtr))
  1456. {
  1457. localVarEntryPtr->mLocalVar = localVar->mShadowedLocal;
  1458. }
  1459. }
  1460. else
  1461. {
  1462. mCurMethodState->mLocalVarSet.Remove(BfLocalVarEntry(localVar));
  1463. }
  1464. delete localVar;
  1465. }
  1466. }
  1467. void BfModule::RestoreScopeState()
  1468. {
  1469. BfScopeData* prevScopeData = mCurMethodState->mCurScope->mPrevScope;
  1470. mCurMethodState->mBlockNestLevel--;
  1471. if (!mCurMethodState->mCurScope->mAtEndBlocks.empty())
  1472. {
  1473. BfIRBlock afterEndBlock;
  1474. if (!mCurMethodState->mLeftBlockUncond)
  1475. {
  1476. afterEndBlock = mBfIRBuilder->CreateBlock("scopeAfterEnd");
  1477. mBfIRBuilder->CreateBr(afterEndBlock);
  1478. mBfIRBuilder->ClearDebugLocation_Last();
  1479. }
  1480. for (auto preExitBlock : mCurMethodState->mCurScope->mAtEndBlocks)
  1481. mBfIRBuilder->MoveBlockToEnd(preExitBlock);
  1482. if (afterEndBlock)
  1483. {
  1484. mBfIRBuilder->AddBlock(afterEndBlock);
  1485. mBfIRBuilder->SetInsertPoint(afterEndBlock);
  1486. }
  1487. }
  1488. if (!mCurMethodState->mLeftBlockUncond)
  1489. EmitDeferredScopeCalls(true, mCurMethodState->mCurScope);
  1490. RestoreScoreState_LocalVariables();
  1491. if (mCurMethodState->mCurScope->mValueScopeStart)
  1492. mBfIRBuilder->CreateValueScopeHardEnd(mCurMethodState->mCurScope->mValueScopeStart);
  1493. mCurMethodState->mCurScope = prevScopeData;
  1494. mCurMethodState->mTailScope = mCurMethodState->mCurScope;
  1495. }
  1496. BfIRValue BfModule::CreateAlloca(BfType* type, bool addLifetime, const char* name, BfIRValue arraySize)
  1497. {
  1498. if (mBfIRBuilder->mIgnoreWrites)
  1499. return mBfIRBuilder->GetFakeVal();
  1500. BF_ASSERT((*(int8*)&addLifetime == 1) || (*(int8*)&addLifetime == 0));
  1501. mBfIRBuilder->PopulateType(type);
  1502. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  1503. if (!mBfIRBuilder->mIgnoreWrites)
  1504. BF_ASSERT(!prevInsertBlock.IsFake());
  1505. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  1506. BfIRValue allocaInst;
  1507. if (arraySize)
  1508. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type), arraySize);
  1509. else
  1510. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type));
  1511. mBfIRBuilder->SetAllocaAlignment(allocaInst, type->mAlign);
  1512. mBfIRBuilder->ClearDebugLocation(allocaInst);
  1513. if (name != NULL)
  1514. mBfIRBuilder->SetName(allocaInst, name);
  1515. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  1516. if ((addLifetime) && (WantsLifetimes()))
  1517. {
  1518. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  1519. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  1520. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  1521. }
  1522. return allocaInst;
  1523. }
  1524. BfIRValue BfModule::CreateAllocaInst(BfTypeInstance* typeInst, bool addLifetime, const char* name)
  1525. {
  1526. if (mBfIRBuilder->mIgnoreWrites)
  1527. return mBfIRBuilder->GetFakeVal();
  1528. BF_ASSERT((*(int8*)&addLifetime == 1) || (*(int8*)&addLifetime == 0));
  1529. mBfIRBuilder->PopulateType(typeInst);
  1530. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  1531. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  1532. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapTypeInst(typeInst));
  1533. mBfIRBuilder->SetAllocaAlignment(allocaInst, typeInst->mInstAlign);
  1534. mBfIRBuilder->ClearDebugLocation(allocaInst);
  1535. if (name != NULL)
  1536. mBfIRBuilder->SetName(allocaInst, name);
  1537. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  1538. if ((addLifetime) && (WantsLifetimes()))
  1539. {
  1540. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  1541. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  1542. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  1543. }
  1544. return allocaInst;
  1545. }
  1546. void BfModule::AddStackAlloc(BfTypedValue val, BfAstNode* refNode, BfScopeData* scopeData, bool condAlloca, bool mayEscape)
  1547. {
  1548. //This was removed because we want the alloc to be added to the __deferred list if it's actually a "stack"
  1549. // 'stack' in a head scopeData is really the same as 'scopeData', so use the simpler scopeData handling
  1550. /*if (mCurMethodState->mInHeadScope)
  1551. isScopeAlloc = true;*/
  1552. if (scopeData == NULL)
  1553. return;
  1554. auto checkBaseType = val.mType->ToTypeInstance();
  1555. if ((checkBaseType != NULL) && (checkBaseType->IsObject()))
  1556. {
  1557. bool hadDtorCall = false;
  1558. while (checkBaseType != NULL)
  1559. {
  1560. if ((checkBaseType->mTypeDef->mDtorDef != NULL) /*&& (checkBaseType != mContext->mBfObjectType)*/)
  1561. {
  1562. bool isDynAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsDyn(scopeData));
  1563. auto dtorMethodInstance = GetMethodInstance(checkBaseType, checkBaseType->mTypeDef->mDtorDef, BfTypeVector());
  1564. BfIRValue useVal = val.mValue;
  1565. useVal = mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapTypeInstPtr(checkBaseType));
  1566. if (isDynAlloc)
  1567. {
  1568. //
  1569. }
  1570. else if (condAlloca)
  1571. {
  1572. BF_ASSERT(!IsTargetingBeefBackend());
  1573. BF_ASSERT(!isDynAlloc);
  1574. auto valPtr = CreateAlloca(checkBaseType);
  1575. mBfIRBuilder->CreateStore(useVal, valPtr);
  1576. useVal = valPtr;
  1577. }
  1578. SizedArray<BfIRValue, 1> llvmArgs;
  1579. llvmArgs.push_back(useVal);
  1580. auto deferredCall = AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1581. if (deferredCall != NULL)
  1582. {
  1583. deferredCall->mCastThis = (val.mType != checkBaseType) && (!isDynAlloc);
  1584. if (condAlloca)
  1585. deferredCall->mArgsNeedLoad = true;
  1586. }
  1587. hadDtorCall = true;
  1588. break;
  1589. }
  1590. checkBaseType = checkBaseType->mBaseType;
  1591. }
  1592. return;
  1593. }
  1594. //TODO: In the future we could be smarter about statically determining that our value hasn't escaped and eliding this
  1595. if (mayEscape)
  1596. {
  1597. // Is this worth it?
  1598. // if ((!IsOptimized()) && (val.mType->IsComposite()) && (!val.mType->IsValuelessType()) && (!mBfIRBuilder->mIgnoreWrites) && (!mCompiler->mIsResolveOnly))
  1599. // {
  1600. // auto nullPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  1601. // bool isDyn = mCurMethodState->mCurScope->IsDyn(scopeData);
  1602. // if (!isDyn)
  1603. // {
  1604. // int clearSize = val.mType->mSize;
  1605. // BfModuleMethodInstance dtorMethodInstance = GetInternalMethod("MemSet");
  1606. // BF_ASSERT(dtorMethodInstance.mMethodInstance != NULL);
  1607. // SizedArray<BfIRValue, 1> llvmArgs;
  1608. // llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(nullPtrType)));
  1609. // llvmArgs.push_back(GetConstValue8(0xDD));
  1610. // llvmArgs.push_back(GetConstValue(clearSize));
  1611. // llvmArgs.push_back(GetConstValue32(val.mType->mAlign));
  1612. // llvmArgs.push_back(mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 0));
  1613. // AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1614. // }
  1615. // else
  1616. // {
  1617. // const char* funcName = "SetDeleted1";
  1618. // if (val.mType->mSize >= 16)
  1619. // funcName = "SetDeleted16";
  1620. // else if (val.mType->mSize >= 8)
  1621. // funcName = "SetDeleted8";
  1622. // else if (val.mType->mSize >= 4)
  1623. // funcName = "SetDeleted4";
  1624. //
  1625. // BfModuleMethodInstance dtorMethodInstance = GetInternalMethod(funcName);
  1626. // BF_ASSERT(dtorMethodInstance.mMethodInstance != NULL);
  1627. // SizedArray<BfIRValue, 1> llvmArgs;
  1628. // llvmArgs.push_back(mBfIRBuilder->CreateBitCast(val.mValue, mBfIRBuilder->MapType(nullPtrType)));
  1629. // AddDeferredCall(dtorMethodInstance, llvmArgs, scopeData, refNode, true);
  1630. // }
  1631. // }
  1632. }
  1633. }
  1634. bool BfModule::TryLocalVariableInit(BfLocalVariable* localVar)
  1635. {
  1636. auto startTypeInstance = localVar->mResolvedType->ToTypeInstance();
  1637. if ((startTypeInstance == NULL) || (!startTypeInstance->IsStruct()))
  1638. return false;
  1639. auto checkTypeInstance = startTypeInstance;
  1640. while (checkTypeInstance != NULL)
  1641. {
  1642. for (auto& fieldInstance : checkTypeInstance->mFieldInstances)
  1643. {
  1644. if (fieldInstance.mMergedDataIdx != -1)
  1645. {
  1646. int64 checkMask = (int64)1 << fieldInstance.mMergedDataIdx;
  1647. if ((localVar->mUnassignedFieldFlags & checkMask) != 0)
  1648. {
  1649. // For fields added in extensions, we automatically initialize those if necessary
  1650. auto fieldDef = fieldInstance.GetFieldDef();
  1651. if (!fieldDef->mDeclaringType->IsExtension())
  1652. return false;
  1653. if ((fieldInstance.mDataIdx != -1) && (!mBfIRBuilder->mIgnoreWrites) && (!mCompiler->mIsResolveOnly))
  1654. {
  1655. auto curInsertBlock = mBfIRBuilder->GetInsertBlock();
  1656. mBfIRBuilder->SaveDebugLocation();
  1657. if (localVar->IsParam())
  1658. mBfIRBuilder->SetInsertPointAtStart(mCurMethodState->mIRInitBlock);
  1659. else
  1660. {
  1661. BF_ASSERT(localVar->mDeclBlock);
  1662. mBfIRBuilder->SetInsertPointAtStart(localVar->mDeclBlock);
  1663. }
  1664. mBfIRBuilder->ClearDebugLocation();
  1665. BfIRValue curVal;
  1666. if (localVar->mIsThis)
  1667. curVal = mBfIRBuilder->GetArgument(0);
  1668. else
  1669. curVal = localVar->mAddr;
  1670. auto subTypeInstance = startTypeInstance;
  1671. while (subTypeInstance != checkTypeInstance)
  1672. {
  1673. curVal = mBfIRBuilder->CreateInBoundsGEP(curVal, 0, 0);
  1674. subTypeInstance = subTypeInstance->mBaseType;
  1675. }
  1676. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(curVal, 0, fieldInstance.mDataIdx);
  1677. auto defVal = GetDefaultValue(fieldInstance.mResolvedType);
  1678. auto storeInst = mBfIRBuilder->CreateStore(defVal, fieldPtr);
  1679. mBfIRBuilder->SetInsertPoint(curInsertBlock);
  1680. mBfIRBuilder->RestoreDebugLocation();
  1681. }
  1682. localVar->mUnassignedFieldFlags &= ~checkMask;
  1683. if (localVar->mUnassignedFieldFlags == 0)
  1684. localVar->mIsAssigned = true;
  1685. }
  1686. }
  1687. }
  1688. checkTypeInstance = checkTypeInstance->mBaseType;
  1689. }
  1690. return localVar->mIsAssigned;
  1691. }
  1692. void BfModule::LocalVariableDone(BfLocalVariable* localVar, bool isMethodExit)
  1693. {
  1694. //if (localVar->mAddr == NULL)
  1695. /*if ((localVar->mValue) && (!localVar->mAddr) && (IsTargetingBeefBackend()))
  1696. {
  1697. if ((!localVar->mValue.IsConst()) && (!localVar->mValue.IsArg()) && (!localVar->mValue.IsFake()))
  1698. {
  1699. if (mCurMethodInstance->mMethodDef->mName == "FuncA")
  1700. mBfIRBuilder->CreateLifetimeEnd(localVar->mValue);
  1701. }
  1702. }*/
  1703. BfAstNode* localNameNode = localVar->mNameNode;
  1704. if (localVar->mIsThis)
  1705. {
  1706. localNameNode = mCurMethodInstance->mMethodDef->GetRefNode();
  1707. }
  1708. if (localNameNode != NULL)
  1709. {
  1710. bool isOut = false;
  1711. if (localVar->mResolvedType->IsRef())
  1712. {
  1713. auto refType = (BfRefType*)localVar->mResolvedType;
  1714. isOut = refType->mRefKind == BfRefType::RefKind_Out;
  1715. }
  1716. if ((localVar->mReadFromId == -1) || (isOut) || ((localVar->mIsThis) && (mCurTypeInstance->IsStruct())))
  1717. {
  1718. if ((!localVar->mIsAssigned) & (localVar->IsParam()))
  1719. TryLocalVariableInit(localVar);
  1720. // We may skip processing of local methods, so we won't know if it bind to any of our local variables or not
  1721. bool deferFullAnalysis = mCurMethodState->GetRootMethodState()->mLocalMethodCache.size() != 0;
  1722. //bool deferFullAnalysis = true;
  1723. bool deferUsageWarning = deferFullAnalysis && mCompiler->IsAutocomplete();
  1724. if (!localVar->mIsAssigned)
  1725. {
  1726. if (deferUsageWarning)
  1727. {
  1728. // Ignore
  1729. }
  1730. else if (localVar->mIsThis)
  1731. {
  1732. bool foundFields = false;
  1733. auto checkTypeInstance = mCurTypeInstance;
  1734. while (checkTypeInstance != NULL)
  1735. {
  1736. for (auto& fieldInstance : checkTypeInstance->mFieldInstances)
  1737. {
  1738. if (fieldInstance.mMergedDataIdx != -1)
  1739. {
  1740. int checkMask = 1 << fieldInstance.mMergedDataIdx;
  1741. if ((localVar->mUnassignedFieldFlags & checkMask) != 0)
  1742. {
  1743. auto fieldDef = fieldInstance.GetFieldDef();
  1744. if (fieldDef->mProtection != BfProtection_Hidden)
  1745. {
  1746. if (checkTypeInstance == mCurTypeInstance)
  1747. {
  1748. Fail(StrFormat("Field '%s' must be fully assigned before control is returned to the caller",
  1749. fieldDef->mName.c_str()), localNameNode, deferFullAnalysis); // 0171
  1750. }
  1751. else
  1752. {
  1753. Fail(StrFormat("Field '%s.%s' must be fully assigned before control is returned to the caller",
  1754. TypeToString(checkTypeInstance).c_str(),
  1755. fieldDef->mName.c_str()), localNameNode, deferFullAnalysis); // 0171
  1756. }
  1757. }
  1758. foundFields = true;
  1759. }
  1760. }
  1761. }
  1762. checkTypeInstance = checkTypeInstance->mBaseType;
  1763. }
  1764. if (!foundFields)
  1765. {
  1766. if (mCurTypeInstance->mInstSize > 0)
  1767. Fail(StrFormat("The variable '%s' must be fully assigned to before control leaves the current method", localVar->mName.c_str()), localNameNode); // 0177
  1768. }
  1769. }
  1770. else if (localVar->IsParam())
  1771. Fail(StrFormat("The out parameter '%s' must be assigned to before control leaves the current method", localVar->mName.c_str()), localNameNode, deferFullAnalysis); // 0177
  1772. else if (!deferUsageWarning)
  1773. Warn(BfWarning_CS0168_VariableDeclaredButNeverUsed, StrFormat("The variable '%s' is declared but never used", localVar->mName.c_str()), localNameNode, deferFullAnalysis);
  1774. }
  1775. else if ((localVar->mReadFromId == -1) && (!localVar->IsParam()) && (!deferUsageWarning))
  1776. Warn(BfWarning_CS0168_VariableDeclaredButNeverUsed, StrFormat("The variable '%s' is assigned but its value is never used", localVar->mName.c_str()), localNameNode, deferFullAnalysis);
  1777. }
  1778. }
  1779. }
  1780. void BfModule::MarkDynStack(BfScopeData* scopeData)
  1781. {
  1782. auto checkScope = mCurMethodState->mCurScope;
  1783. while (true)
  1784. {
  1785. if (checkScope == scopeData)
  1786. break;
  1787. checkScope->mHadOuterDynStack = true;
  1788. checkScope = checkScope->mPrevScope;
  1789. }
  1790. }
  1791. void BfModule::SaveStackState(BfScopeData* scopeData)
  1792. {
  1793. // If we push a value on the stack that needs to survive until the end of scopeData, we need to make sure that no
  1794. // scopes within scopeData restore the stack
  1795. auto checkScope = mCurMethodState->mCurScope;
  1796. while (true)
  1797. {
  1798. if (checkScope == scopeData)
  1799. {
  1800. if ((!checkScope->mSavedStack) && (checkScope->mBlock) && (!checkScope->mIsScopeHead) && (!checkScope->mHadOuterDynStack))
  1801. {
  1802. if (mBfIRBuilder->mHasDebugInfo)
  1803. mBfIRBuilder->SaveDebugLocation();
  1804. auto prevPos = mBfIRBuilder->GetInsertBlock();
  1805. mBfIRBuilder->SetInsertPointAtStart(checkScope->mBlock);
  1806. checkScope->mSavedStack = mBfIRBuilder->CreateStackSave();
  1807. mBfIRBuilder->ClearDebugLocation(checkScope->mSavedStack);
  1808. mBfIRBuilder->SetInsertPoint(prevPos);
  1809. if (mBfIRBuilder->mHasDebugInfo)
  1810. mBfIRBuilder->RestoreDebugLocation();
  1811. }
  1812. break;
  1813. }
  1814. if (checkScope->mSavedStack)
  1815. {
  1816. for (auto usage : checkScope->mSavedStackUses)
  1817. mBfIRBuilder->EraseInstFromParent(usage);
  1818. checkScope->mSavedStackUses.Clear();
  1819. mBfIRBuilder->EraseInstFromParent(checkScope->mSavedStack);
  1820. checkScope->mSavedStack = BfIRValue();
  1821. }
  1822. checkScope = checkScope->mPrevScope;
  1823. }
  1824. }
  1825. BfIRValue BfModule::ValueScopeStart()
  1826. {
  1827. if (IsTargetingBeefBackend())
  1828. return mBfIRBuilder->CreateValueScopeStart();
  1829. return BfIRValue();
  1830. }
  1831. void BfModule::ValueScopeEnd(BfIRValue valueScopeStart)
  1832. {
  1833. if (valueScopeStart)
  1834. mBfIRBuilder->CreateValueScopeHardEnd(valueScopeStart);
  1835. }
  1836. BfFileInstance* BfModule::GetFileFromNode(BfAstNode* astNode)
  1837. {
  1838. auto bfParser = astNode->GetSourceData()->ToParserData();
  1839. if (bfParser == NULL)
  1840. return NULL;
  1841. BfFileInstance** fileInstancePtr = NULL;
  1842. if (!mFileInstanceMap.TryAdd(bfParser, NULL, &fileInstancePtr))
  1843. {
  1844. return *fileInstancePtr;
  1845. }
  1846. else
  1847. {
  1848. // It's possible two parsers have the same file name (ie: mNextRevision)
  1849. BfFileInstance** namedFileInstancePtr = NULL;
  1850. if (!mNamedFileInstanceMap.TryAdd(bfParser->mFileName, NULL, &namedFileInstancePtr))
  1851. {
  1852. auto bfFileInstance = *namedFileInstancePtr;
  1853. *fileInstancePtr = bfFileInstance;
  1854. return bfFileInstance;
  1855. }
  1856. int slashPos = (int)bfParser->mFileName.LastIndexOf(DIR_SEP_CHAR);
  1857. auto bfFileInstance = new BfFileInstance();
  1858. *fileInstancePtr = bfFileInstance;
  1859. *namedFileInstancePtr = bfFileInstance;
  1860. bfFileInstance->mPrevPosition.mFileInstance = bfFileInstance;
  1861. bfFileInstance->mParser = bfParser;
  1862. BfLogSysM("GetFileFromNode new file. Mod: %p FileInstance: %p Parser: %p\n", this, bfFileInstance, bfParser);
  1863. if ((mBfIRBuilder != NULL) && (mBfIRBuilder->DbgHasInfo()))
  1864. {
  1865. String fileName = bfParser->mFileName;
  1866. for (int i = 0; i < (int)fileName.length(); i++)
  1867. {
  1868. if (fileName[i] == DIR_SEP_CHAR_ALT)
  1869. fileName[i] = DIR_SEP_CHAR;
  1870. }
  1871. bfFileInstance->mDIFile = mBfIRBuilder->DbgCreateFile(fileName.Substring(slashPos + 1), fileName.Substring(0, slashPos));
  1872. }
  1873. return bfFileInstance;
  1874. }
  1875. }
  1876. void BfModule::UpdateSrcPos(BfAstNode* astNode, BfSrcPosFlags flags, int debugLocOffset)
  1877. {
  1878. // We set force to true when we MUST get the line position set (for navigation purposes, for example)
  1879. if (((mBfIRBuilder->mIgnoreWrites)) && ((flags & BfSrcPosFlag_Force) == 0))
  1880. return;
  1881. BF_ASSERT((!mAwaitingInitFinish) || (mBfIRBuilder->mIgnoreWrites));
  1882. if (astNode == NULL)
  1883. return;
  1884. auto bfParser = astNode->GetSourceData()->ToParserData();
  1885. if (bfParser == NULL)
  1886. return;
  1887. if ((mCurFilePosition.mFileInstance == NULL) || (mCurFilePosition.mFileInstance->mParser != bfParser))
  1888. {
  1889. if (mCurFilePosition.mFileInstance != NULL)
  1890. {
  1891. BF_ASSERT(mFileInstanceMap.GetCount() != 0);
  1892. mCurFilePosition.mFileInstance->mPrevPosition = mCurFilePosition;
  1893. }
  1894. auto bfFileInstance = GetFileFromNode(astNode);
  1895. if (bfFileInstance->mPrevPosition.mFileInstance != NULL)
  1896. {
  1897. mCurFilePosition = bfFileInstance->mPrevPosition;
  1898. }
  1899. else
  1900. {
  1901. mCurFilePosition.mFileInstance = bfFileInstance;
  1902. mCurFilePosition.mCurLine = 0;
  1903. mCurFilePosition.mCurSrcPos = 0;
  1904. }
  1905. }
  1906. int srcPos = astNode->GetSrcStart() + debugLocOffset;
  1907. BF_ASSERT(srcPos < bfParser->mSrcLength);
  1908. auto* jumpEntry = bfParser->mJumpTable + (srcPos / PARSER_JUMPTABLE_DIVIDE);
  1909. if (jumpEntry->mCharIdx > srcPos)
  1910. jumpEntry--;
  1911. mCurFilePosition.mCurLine = jumpEntry->mLineNum;
  1912. mCurFilePosition.mCurSrcPos = jumpEntry->mCharIdx;
  1913. mCurFilePosition.mCurColumn = 0;
  1914. while (mCurFilePosition.mCurSrcPos < srcPos)
  1915. {
  1916. if (bfParser->mSrc[mCurFilePosition.mCurSrcPos] == '\n')
  1917. {
  1918. mCurFilePosition.mCurLine++;
  1919. mCurFilePosition.mCurColumn = 0;
  1920. }
  1921. else
  1922. {
  1923. mCurFilePosition.mCurColumn++;
  1924. }
  1925. mCurFilePosition.mCurSrcPos++;
  1926. }
  1927. //TODO: if we bail on the "mCurMethodState == NULL" case then we don't get it set during type declarations
  1928. if (((flags & BfSrcPosFlag_NoSetDebugLoc) == 0) && (mBfIRBuilder->DbgHasInfo()) && (mCurMethodState != NULL))
  1929. {
  1930. int column = mCurFilePosition.mCurColumn + 1;
  1931. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend))
  1932. {
  1933. // Set to illegal position
  1934. column = 0;
  1935. }
  1936. if (mSetIllegalSrcPosition)
  1937. column = 0;
  1938. BfIRMDNode useDIScope = mCurMethodState->mCurScope->mDIScope;
  1939. auto wantDIFile = mCurFilePosition.mFileInstance->mDIFile;
  1940. if ((wantDIFile != mCurMethodState->mDIFile) && (mCurMethodState->mDIFile))
  1941. {
  1942. // This is from a different scope...
  1943. if (wantDIFile != mCurMethodState->mCurScope->mAltDIFile)
  1944. {
  1945. mCurMethodState->mCurScope->mAltDIFile = wantDIFile;
  1946. mCurMethodState->mCurScope->mAltDIScope = mBfIRBuilder->DbgCreateLexicalBlock(mCurMethodState->mCurScope->mDIScope, wantDIFile, mCurFilePosition.mCurLine + 1, column);
  1947. }
  1948. if (mCurMethodState->mCurScope->mAltDIScope) // This may not be set if mAltDIFile is set by a mixin
  1949. useDIScope = mCurMethodState->mCurScope->mAltDIScope;
  1950. }
  1951. else
  1952. {
  1953. if (mCurMethodState->mCurScope->mAltDIFile)
  1954. {
  1955. mCurMethodState->mCurScope->mAltDIFile = BfIRMDNode();
  1956. mCurMethodState->mCurScope->mAltDIScope = BfIRMDNode();
  1957. }
  1958. }
  1959. auto inlineAt = mCurMethodState->mCurScope->mDIInlinedAt;
  1960. if (mCurMethodState->mCrossingMixin)
  1961. inlineAt = BfIRMDNode();
  1962. mBfIRBuilder->SetCurrentDebugLocation(mCurFilePosition.mCurLine + 1, column, useDIScope, inlineAt);
  1963. if ((flags & BfSrcPosFlag_Expression) == 0)
  1964. mBfIRBuilder->CreateStatementStart();
  1965. }
  1966. }
  1967. void BfModule::UpdateExprSrcPos(BfAstNode* astNode, BfSrcPosFlags flags)
  1968. {
  1969. // We've turned off expr src pos (for now?)
  1970. //UpdateSrcPos(astNode, (BfSrcPosFlags)(flags | BfSrcPosFlag_Expression));
  1971. }
  1972. void BfModule::UseDefaultSrcPos(BfSrcPosFlags flags, int debugLocOffset)
  1973. {
  1974. UpdateSrcPos(mCompiler->mBfObjectTypeDef->mTypeDeclaration, flags, debugLocOffset);
  1975. }
  1976. void BfModule::SetIllegalSrcPos(BfSrcPosFlags flags)
  1977. {
  1978. if ((mBfIRBuilder->DbgHasInfo()) && (mCurMethodState != NULL))
  1979. {
  1980. if ((mCurMethodState->mCurScope->mDIInlinedAt) && (mCompiler->mOptions.IsCodeView()))
  1981. {
  1982. // Currently, CodeView does not record column positions so we can't use an illegal column position as an "invalid" marker
  1983. mBfIRBuilder->SetCurrentDebugLocation(0, 0, mCurMethodState->mCurScope->mDIScope, mCurMethodState->mCurScope->mDIInlinedAt);
  1984. }
  1985. else
  1986. {
  1987. // Set to whatever it previously was but at column zero, which we will know to be illegal
  1988. mBfIRBuilder->SetCurrentDebugLocation(mCurFilePosition.mCurLine + 1, 0, mCurMethodState->mCurScope->mDIScope, mCurMethodState->mCurScope->mDIInlinedAt);
  1989. }
  1990. if ((flags & BfSrcPosFlag_Expression) == 0)
  1991. mBfIRBuilder->CreateStatementStart();
  1992. }
  1993. }
  1994. void BfModule::SetIllegalExprSrcPos(BfSrcPosFlags flags)
  1995. {
  1996. // We've turned off expr src pos (for now?)
  1997. //SetIllegalSrcPos((BfSrcPosFlags)(flags | BfSrcPosFlag_Expression));
  1998. }
  1999. bool BfModule::CheckProtection(BfProtection protection, bool allowProtected, bool allowPrivate)
  2000. {
  2001. if ((protection == BfProtection_Public) ||
  2002. ((protection == BfProtection_Protected) && (allowProtected)) ||
  2003. ((protection == BfProtection_Private) && (allowPrivate)))
  2004. return true;
  2005. if ((mAttributeState != NULL) && (mAttributeState->mCustomAttributes != NULL) && (mAttributeState->mCustomAttributes->Contains(mCompiler->mFriendAttributeTypeDef)))
  2006. return true;
  2007. return false;
  2008. }
  2009. void BfModule::GetAccessAllowed(BfTypeInstance* checkType, bool &allowProtected, bool &allowPrivate)
  2010. {
  2011. allowPrivate = (checkType == mCurTypeInstance) || (IsInnerType(mCurTypeInstance, checkType));
  2012. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2013. {
  2014. auto mixinOwner = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  2015. allowPrivate |= (checkType == mixinOwner) || (IsInnerType(mixinOwner, checkType));
  2016. }
  2017. allowProtected = allowPrivate;
  2018. }
  2019. bool BfModule::CheckProtection(BfProtectionCheckFlags& flags, BfTypeInstance* memberOwner, BfProtection memberProtection, BfTypeInstance* lookupStartType)
  2020. {
  2021. if (memberProtection == BfProtection_Hidden)
  2022. return false;
  2023. if (memberProtection == BfProtection_Public)
  2024. return true;
  2025. if ((flags & BfProtectionCheckFlag_CheckedPrivate) == 0)
  2026. {
  2027. BfTypeInstance* curCheckType = mCurTypeInstance;
  2028. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2029. {
  2030. auto mixinOwner = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  2031. curCheckType = mixinOwner;
  2032. }
  2033. bool allowPrivate = (memberOwner->mTypeDef == curCheckType->mTypeDef) || (IsInnerType(curCheckType->mTypeDef, memberOwner->mTypeDef));
  2034. if (allowPrivate)
  2035. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_AllowPrivate | BfProtectionCheckFlag_CheckedPrivate);
  2036. else
  2037. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedPrivate);
  2038. }
  2039. if ((flags & BfProtectionCheckFlag_AllowPrivate) != 0)
  2040. return true;
  2041. if (memberProtection == BfProtection_Protected)
  2042. {
  2043. if ((flags & BfProtectionCheckFlag_CheckedProtected) == 0)
  2044. {
  2045. bool allowProtected = false;
  2046. auto memberOwnerTypeDef = memberOwner->mTypeDef;
  2047. auto curCheckType = mCurTypeInstance;
  2048. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2049. {
  2050. auto mixinOwner = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  2051. curCheckType = mixinOwner;
  2052. }
  2053. auto lookupCheckType = lookupStartType;
  2054. while (lookupCheckType->mInheritDepth >= curCheckType->mInheritDepth)
  2055. {
  2056. if (lookupCheckType == curCheckType)
  2057. {
  2058. allowProtected = true;
  2059. break;
  2060. }
  2061. if (lookupCheckType == memberOwner)
  2062. break;
  2063. lookupCheckType = lookupCheckType->mBaseType;
  2064. if (lookupCheckType == NULL)
  2065. break;
  2066. }
  2067. if (!allowProtected)
  2068. {
  2069. // It's possible our outer type is derived from 'memberOwner'
  2070. while (curCheckType->mTypeDef->mNestDepth > 0)
  2071. {
  2072. curCheckType = GetOuterType(curCheckType);
  2073. if (curCheckType == NULL)
  2074. break;
  2075. auto lookupCheckType = lookupStartType;
  2076. while (lookupCheckType->mInheritDepth >= curCheckType->mInheritDepth)
  2077. {
  2078. if (lookupCheckType == curCheckType)
  2079. {
  2080. allowProtected = true;
  2081. break;
  2082. }
  2083. if (lookupCheckType == memberOwner)
  2084. break;
  2085. lookupCheckType = lookupCheckType->mBaseType;
  2086. if (lookupCheckType == NULL)
  2087. break;
  2088. }
  2089. }
  2090. }
  2091. if (allowProtected)
  2092. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedProtected | BfProtectionCheckFlag_AllowProtected);
  2093. else
  2094. flags = (BfProtectionCheckFlags)(flags | BfProtectionCheckFlag_CheckedProtected);
  2095. }
  2096. if ((flags & BfProtectionCheckFlag_AllowProtected) != 0)
  2097. return true;
  2098. }
  2099. if ((mAttributeState != NULL) && (mAttributeState->mCustomAttributes != NULL) && (mAttributeState->mCustomAttributes->Contains(mCompiler->mFriendAttributeTypeDef)))
  2100. return true;
  2101. return false;
  2102. }
  2103. void BfModule::SetElementType(BfAstNode* astNode, BfSourceElementType elementType)
  2104. {
  2105. if ((mCompiler->mResolvePassData != NULL) &&
  2106. (mCompiler->mResolvePassData->mSourceClassifier != NULL) &&
  2107. (astNode->IsFromParser( mCompiler->mResolvePassData->mParser)))
  2108. {
  2109. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(astNode, elementType);
  2110. }
  2111. }
  2112. BfError* BfModule::Fail(const StringImpl& error, BfAstNode* refNode, bool isPersistent)
  2113. {
  2114. BP_ZONE("BfModule::Fail");
  2115. if (mIgnoreErrors)
  2116. {
  2117. return NULL;
  2118. }
  2119. if (!mReportErrors)
  2120. {
  2121. mCompiler->mPassInstance->SilentFail();
  2122. return NULL;
  2123. }
  2124. if (refNode != NULL)
  2125. refNode = BfNodeToNonTemporary(refNode);
  2126. //BF_ASSERT(refNode != NULL);
  2127. if (mCurMethodInstance != NULL)
  2128. mCurMethodInstance->mHasFailed = true;
  2129. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsUnspecializedTypeVariation()))
  2130. return NULL;
  2131. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsUnspecializedVariation))
  2132. return NULL; // Ignore errors on unspecialized variations, they are always dups
  2133. if (!mHadBuildError)
  2134. mHadBuildError = true;
  2135. if (mParentModule != NULL)
  2136. mParentModule->mHadBuildError = true;
  2137. if (mCurTypeInstance != NULL)
  2138. AddFailType(mCurTypeInstance);
  2139. BfLogSysM("BfModule::Fail module %p type %p %s\n", this, mCurTypeInstance, error.c_str());
  2140. String errorString = error;
  2141. bool isWhileSpecializing = false;
  2142. bool isWhileSpecializingMethod = false;
  2143. if ((mIsSpecialModule) && (mModuleName == "vdata"))
  2144. errorString += StrFormat("\n while generating vdata for project '%s'", mProject->mName.c_str());
  2145. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend))
  2146. errorString += StrFormat("\n while generating append size calculating method");
  2147. else if (refNode == NULL)
  2148. {
  2149. if (mCurTypeInstance != NULL)
  2150. errorString += StrFormat("\n while compiling '%s'", TypeToString(mCurTypeInstance, BfTypeNameFlags_None).c_str());
  2151. else if (mProject != NULL)
  2152. errorString += StrFormat("\n while compiling project '%s'", mProject->mName.c_str());
  2153. }
  2154. if ((mCurTypeInstance != NULL) && (mCurMethodState != NULL))
  2155. {
  2156. auto checkMethodState = mCurMethodState;
  2157. while (checkMethodState != NULL)
  2158. {
  2159. auto methodInstance = checkMethodState->mMethodInstance;
  2160. if (methodInstance == NULL)
  2161. {
  2162. checkMethodState = checkMethodState->mPrevMethodState;
  2163. continue;
  2164. }
  2165. // Propogatea the fail all the way to the main method (assuming we're in a local method or lambda)
  2166. methodInstance->mHasFailed = true;
  2167. bool isSpecializedMethod = ((methodInstance != NULL) && (!methodInstance->mIsUnspecialized) && (methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mMethodGenericArguments.size() != 0));
  2168. if (isSpecializedMethod)
  2169. {
  2170. //auto unspecializedMethod = &mCurMethodInstance->mMethodInstanceGroup->mMethodSpecializationMap.begin()->second;
  2171. auto unspecializedMethod = methodInstance->mMethodInstanceGroup->mDefault;
  2172. if (unspecializedMethod->mHasFailed)
  2173. return NULL; // At least SOME error has already been reported
  2174. }
  2175. if (isSpecializedMethod)
  2176. {
  2177. errorString += StrFormat("\n while specializing method '%s'", MethodToString(methodInstance).c_str());
  2178. isWhileSpecializing = true;
  2179. isWhileSpecializingMethod = true;
  2180. }
  2181. else if ((methodInstance != NULL) && (methodInstance->mIsForeignMethodDef))
  2182. {
  2183. errorString += StrFormat("\n while implementing default interface method '%s'", MethodToString(methodInstance).c_str());
  2184. isWhileSpecializing = true;
  2185. isWhileSpecializingMethod = true;
  2186. }
  2187. else if ((mCurTypeInstance->IsGenericTypeInstance()) && (!mCurTypeInstance->IsUnspecializedType()))
  2188. {
  2189. errorString += StrFormat("\n while specializing type '%s'", TypeToString(mCurTypeInstance).c_str());
  2190. isWhileSpecializing = true;
  2191. }
  2192. checkMethodState = checkMethodState->mPrevMethodState;
  2193. }
  2194. // Keep in mind that all method specializations with generic type instances as its method generic params
  2195. // need to be deferred because the specified generic type instance might get deleted at the end of the
  2196. // compilation due to no longer having indirect references removed, and we have to ignore errors from
  2197. // those method specializations if that occurs
  2198. if (isWhileSpecializing)
  2199. {
  2200. BfError* bfError = mCompiler->mPassInstance->DeferFail(errorString, refNode);
  2201. if (bfError != NULL)
  2202. bfError->mIsWhileSpecializing = isWhileSpecializing;
  2203. return bfError;
  2204. }
  2205. }
  2206. if (!mHadBuildError)
  2207. mHadBuildError = true;
  2208. // Check mixins
  2209. {
  2210. auto checkMethodInstance = mCurMethodState;
  2211. while (checkMethodInstance != NULL)
  2212. {
  2213. auto rootMixinState = checkMethodInstance->GetRootMixinState();
  2214. if (rootMixinState != NULL)
  2215. {
  2216. BfError* bfError = mCompiler->mPassInstance->Fail(StrFormat("Failed to inject mixin '%s'", MethodToString(rootMixinState->mMixinMethodInstance).c_str()), rootMixinState->mSource);
  2217. mCompiler->mPassInstance->MoreInfo(errorString, refNode);
  2218. auto mixinState = checkMethodInstance->mMixinState;
  2219. while ((mixinState != NULL) && (mixinState->mPrevMixinState != NULL))
  2220. {
  2221. mCompiler->mPassInstance->MoreInfo(StrFormat("Injected from mixin '%s'", MethodToString(mixinState->mPrevMixinState->mMixinMethodInstance).c_str()), mixinState->mSource);
  2222. mixinState = mixinState->mPrevMixinState;
  2223. }
  2224. return bfError;
  2225. }
  2226. checkMethodInstance = checkMethodInstance->mPrevMethodState;
  2227. }
  2228. }
  2229. BfError* bfError = NULL;
  2230. if (refNode == NULL)
  2231. bfError = mCompiler->mPassInstance->Fail(errorString);
  2232. else
  2233. {
  2234. bfError = mCompiler->mPassInstance->Fail(errorString, refNode);
  2235. }
  2236. if (bfError != NULL)
  2237. {
  2238. bfError->mIsPersistent = isPersistent;
  2239. bfError->mIsWhileSpecializing = isWhileSpecializing;
  2240. if ((mCurMethodState != NULL) && (mCurMethodState->mDeferredCallEmitState != NULL) && (mCurMethodState->mDeferredCallEmitState->mCloseNode != NULL))
  2241. mCompiler->mPassInstance->MoreInfo("Error during deferred statement handling", mCurMethodState->mDeferredCallEmitState->mCloseNode);
  2242. }
  2243. return bfError;
  2244. }
  2245. BfError* BfModule::FailAfter(const StringImpl& error, BfAstNode* refNode)
  2246. {
  2247. if (mIgnoreErrors)
  2248. return NULL;
  2249. if (refNode != NULL)
  2250. refNode = BfNodeToNonTemporary(refNode);
  2251. mHadBuildError = true;
  2252. return mCompiler->mPassInstance->FailAfter(error, refNode);
  2253. }
  2254. BfError* BfModule::Warn(int warningNum, const StringImpl& warning, BfAstNode* refNode, bool isPersistent)
  2255. {
  2256. if (mIgnoreErrors || mIgnoreWarnings)
  2257. return NULL;
  2258. if (!mReportErrors)
  2259. {
  2260. mCompiler->mPassInstance->SilentFail();
  2261. return NULL;
  2262. }
  2263. BfAstNode* unwarnNode = refNode;
  2264. //
  2265. {
  2266. BfParentNodeEntry* parentNodeEntry = mParentNodeEntry;
  2267. while (parentNodeEntry != NULL)
  2268. {
  2269. if (auto block = BfNodeDynCast<BfBlock>(parentNodeEntry->mNode))
  2270. break;
  2271. unwarnNode = parentNodeEntry->mNode;
  2272. parentNodeEntry = parentNodeEntry->mPrev;
  2273. }
  2274. }
  2275. auto parser = unwarnNode->GetSourceData()->ToParserData();
  2276. if ((parser != NULL) && (parser->IsUnwarnedAt(unwarnNode)))
  2277. {
  2278. return NULL;
  2279. }
  2280. // Right now we're only warning on the unspecialized declarations, we may revisit this
  2281. if (mCurMethodInstance != NULL)
  2282. {
  2283. if (mCurMethodInstance->IsSpecializedGenericMethodOrType())
  2284. return NULL;
  2285. if (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend)
  2286. return NULL; // No ctorCalcAppend warnings
  2287. }
  2288. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsSpecializedType()))
  2289. return NULL;
  2290. if (refNode != NULL)
  2291. refNode = BfNodeToNonTemporary(refNode);
  2292. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  2293. {
  2294. // We used to bubble up warnings into the mixin injection site, BUT
  2295. // we are now assuming any relevant warnings will be given at the declaration site
  2296. return NULL;
  2297. // AddFailType(mCurTypeInstance);
  2298. //
  2299. // BfError* bfError = mCompiler->mPassInstance->Warn(warningNum, "Warning while injecting mixin", mCurMethodState->mMixinState->GetRoot()->mSource);
  2300. // if (bfError == NULL)
  2301. // return NULL;
  2302. // mHadBuildWarning = true;
  2303. // return mCompiler->mPassInstance->MoreInfo(warning, refNode);
  2304. }
  2305. BfError* bfError = mCompiler->mPassInstance->WarnAt(warningNum, warning, refNode->GetSourceData(), refNode->GetSrcStart(), refNode->GetSrcLength());
  2306. if (bfError != NULL)
  2307. {
  2308. AddFailType(mCurTypeInstance);
  2309. mHadBuildWarning = true;
  2310. bfError->mIsPersistent = isPersistent;
  2311. if ((mCompiler->IsAutocomplete()) && (mCompiler->mResolvePassData->mAutoComplete->CheckFixit((refNode))))
  2312. {
  2313. BfParserData* parser = refNode->GetSourceData()->ToParserData();
  2314. if (parser != NULL)
  2315. {
  2316. int fileLoc = BfFixitFinder::FindLineStartBefore(refNode);
  2317. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("fixit", StrFormat("#unwarn\tunwarn|%s|%d|#unwarn|", parser->mFileName.c_str(), fileLoc).c_str()));
  2318. }
  2319. }
  2320. }
  2321. return bfError;
  2322. }
  2323. void BfModule::CheckRangeError(BfType* type, BfAstNode* refNode)
  2324. {
  2325. if (mBfIRBuilder->mOpFailed)
  2326. Fail(StrFormat("Result out of range for type '%s'", TypeToString(type).c_str()), refNode);
  2327. }
  2328. void BfModule::NotImpl(BfAstNode* astNode)
  2329. {
  2330. Fail("INTERNAL ERROR: Not implemented", astNode);
  2331. }
  2332. bool BfModule::CheckAccessMemberProtection(BfProtection protection, BfType* memberType)
  2333. {
  2334. bool allowPrivate = (memberType == mCurTypeInstance) || (IsInnerType(mCurTypeInstance, memberType));
  2335. if (!allowPrivate)
  2336. allowPrivate |= memberType->IsInterface();
  2337. bool allowProtected = allowPrivate;// allowPrivate || TypeIsSubTypeOf(mCurTypeInstance, memberType->ToTypeInstance());
  2338. if (!CheckProtection(protection, allowProtected, allowPrivate))
  2339. {
  2340. return false;
  2341. }
  2342. return true;
  2343. }
  2344. bool BfModule::CheckDefineMemberProtection(BfProtection protection, BfType* memberType)
  2345. {
  2346. // Use 'min' - exporting a 'public' from a 'private' class is really just 'private' still
  2347. protection = std::min(protection, mCurTypeInstance->mTypeDef->mProtection);
  2348. auto memberTypeInstance = memberType->ToTypeInstance();
  2349. if (memberTypeInstance == NULL)
  2350. {
  2351. auto underlyingType = memberType->GetUnderlyingType();
  2352. if (underlyingType != NULL)
  2353. return CheckDefineMemberProtection(protection, underlyingType);
  2354. return true;
  2355. }
  2356. if (memberTypeInstance->mTypeDef->mProtection < protection)
  2357. return false;
  2358. if (memberTypeInstance->IsGenericTypeInstance())
  2359. {
  2360. // When we're a generic struct, our data layout can depend on our generic parameters as well
  2361. auto genericTypeInstance = (BfGenericTypeInstance*) memberTypeInstance;
  2362. for (auto typeGenericArg : genericTypeInstance->mTypeGenericArguments)
  2363. {
  2364. if (!CheckDefineMemberProtection(protection, typeGenericArg))
  2365. return false;
  2366. }
  2367. }
  2368. return true;
  2369. }
  2370. void BfModule::AddDependency(BfType* usedType, BfType* usingType, BfDependencyMap::DependencyDependencyFlag flags)
  2371. {
  2372. if (usedType == usingType)
  2373. return;
  2374. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsAutocompleteMethod))
  2375. return;
  2376. if (usedType->IsSpecializedByAutoCompleteMethod())
  2377. return;
  2378. if ((mCurMethodState != NULL) && (mCurMethodState->mHotDataReferenceBuilder != NULL) && (usedType != mCurTypeInstance) &&
  2379. ((flags & (BfDependencyMap::DependencyFlag_ReadFields | BfDependencyMap::DependencyFlag_LocalUsage | BfDependencyMap::DependencyFlag_Allocates)) != 0))
  2380. {
  2381. bool addType = true;
  2382. auto checkType = usedType;
  2383. while (true)
  2384. {
  2385. if ((checkType->IsPointer()) || (checkType->IsRef()) || (checkType->IsSizedArray()))
  2386. checkType = checkType->GetUnderlyingType();
  2387. else if (checkType->IsArray())
  2388. {
  2389. checkType = ((BfGenericTypeInstance*)checkType)->mTypeGenericArguments[0];
  2390. }
  2391. else
  2392. break;
  2393. }
  2394. PopulateType(checkType, BfPopulateType_Data);
  2395. if (checkType->IsValuelessType())
  2396. addType = false;
  2397. else if (checkType->IsPrimitiveType())
  2398. addType = false;
  2399. else
  2400. {
  2401. auto checkTypeInst = checkType->ToTypeInstance();
  2402. if (checkTypeInst == NULL)
  2403. {
  2404. addType = false;
  2405. }
  2406. else
  2407. {
  2408. if (TypeIsSubTypeOf(mCurTypeInstance, checkTypeInst))
  2409. addType = false;
  2410. }
  2411. }
  2412. if (addType)
  2413. {
  2414. auto checkTypeInst = checkType->ToTypeInstance();
  2415. auto hotTypeVersion = checkTypeInst->mHotTypeData->GetLatestVersion();
  2416. BF_ASSERT(hotTypeVersion != NULL);
  2417. bool isAllocation = ((flags & BfDependencyMap::DependencyFlag_Allocates) != 0);
  2418. if (((flags & BfDependencyMap::DependencyFlag_LocalUsage) != 0) &&
  2419. (checkType->IsComposite()))
  2420. isAllocation = true;
  2421. if (isAllocation)
  2422. {
  2423. mCurMethodState->mHotDataReferenceBuilder->mAllocatedData.Add(hotTypeVersion);
  2424. }
  2425. else
  2426. mCurMethodState->mHotDataReferenceBuilder->mUsedData.Add(hotTypeVersion);
  2427. }
  2428. }
  2429. //BP_ZONE("BfModule::AddDependency");
  2430. /*if (usedType->IsMethodRef())
  2431. {
  2432. auto methodRefType = (BfMethodRefType*)usedType;
  2433. AddDependency(methodRefType->mMethodRef->GetOwner(), usingType, flags);
  2434. return;
  2435. }*/
  2436. // Why in the world were we doing this?
  2437. // This caused functions to get immediately deleted since they appear to have no references ever....
  2438. // if (usedType->IsFunction())
  2439. // {
  2440. // usedType = ResolveTypeDef(mCompiler->mFunctionTypeDef);
  2441. // }
  2442. if ((!mCompiler->mIsResolveOnly) && (mIsReified))
  2443. {
  2444. auto usingModule = usingType->GetModule();
  2445. BfModule* usedModule;
  2446. if (usedType->IsFunction())
  2447. {
  2448. auto typeInst = usedType->ToTypeInstance();
  2449. if (typeInst->mBaseType == NULL)
  2450. PopulateType(typeInst);
  2451. usedModule = typeInst->mBaseType->GetModule();
  2452. }
  2453. else
  2454. usedModule = usedType->GetModule();
  2455. if ((usingModule != NULL) && (!usingModule->mIsSpecialModule) &&
  2456. (usedModule != NULL) && (!usedModule->mIsSpecialModule))
  2457. {
  2458. usingModule->mModuleRefs.Add(usedModule);
  2459. }
  2460. }
  2461. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodInfoEx != NULL) && (flags != BfDependencyMap::DependencyFlag_MethodGenericArg))
  2462. {
  2463. // When we are specializing a method, usage of that specialized type is already handled with DependencyFlag_MethodGenericArg
  2464. for (auto genericArg : mCurMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  2465. if (genericArg == usedType)
  2466. return;
  2467. }
  2468. auto underlyingType = usedType->GetUnderlyingType();
  2469. if (underlyingType != NULL) // Not really a "GenericArg", but... same purpose.
  2470. AddDependency(underlyingType, usingType, BfDependencyMap::DependencyFlag_GenericArgRef);
  2471. BfDependedType* checkDType = usedType->ToDependedType();
  2472. if (checkDType == NULL)
  2473. return;
  2474. if ((usedType->mRebuildFlags & BfTypeRebuildFlag_AwaitingReference) != 0)
  2475. mContext->MarkAsReferenced(checkDType);
  2476. checkDType->mDependencyMap.AddUsedBy(usingType, flags);
  2477. if (checkDType->IsGenericTypeInstance())
  2478. {
  2479. auto genericTypeInstance = (BfGenericTypeInstance*) checkDType;
  2480. for (auto genericArg : genericTypeInstance->mTypeGenericArguments)
  2481. {
  2482. AddDependency(genericArg, usingType, BfDependencyMap::DependencyFlag_GenericArgRef);
  2483. }
  2484. }
  2485. }
  2486. void BfModule::AddCallDependency(BfMethodInstance* methodInstance, bool devirtualized)
  2487. {
  2488. if ((mCurMethodState != NULL) && (mCurMethodState->mHotDataReferenceBuilder != NULL))
  2489. {
  2490. if (methodInstance->mHotMethod == NULL)
  2491. CheckHotMethod(methodInstance, "");
  2492. BF_ASSERT(methodInstance->mHotMethod != NULL);
  2493. if (devirtualized)
  2494. mCurMethodState->mHotDataReferenceBuilder->mDevirtualizedCalledMethods.Add(methodInstance->mHotMethod);
  2495. else
  2496. mCurMethodState->mHotDataReferenceBuilder->mCalledMethods.Add(methodInstance->mHotMethod);
  2497. }
  2498. }
  2499. bool BfModule::IsAttribute(BfTypeInstance* typeInst)
  2500. {
  2501. auto checkTypeInst = typeInst;
  2502. while (checkTypeInst != NULL)
  2503. {
  2504. if (checkTypeInst->mTypeDef == mCompiler->mAttributeTypeDef)
  2505. return true;
  2506. checkTypeInst = checkTypeInst->mBaseType;
  2507. }
  2508. return false;
  2509. }
  2510. void BfModule::PopulateGlobalContainersList(const BfGlobalLookup& globalLookup)
  2511. {
  2512. if (mContext->mCurTypeState == NULL)
  2513. return;
  2514. BP_ZONE("PopulateGlobalContainersList");
  2515. BfTypeDef* userTypeDef = mContext->mCurTypeState->mCurTypeDef;
  2516. if (userTypeDef == NULL)
  2517. userTypeDef = mCurTypeInstance->mTypeDef;
  2518. if (mContext->mCurTypeState->mGlobalContainerCurUserTypeDef != userTypeDef)
  2519. {
  2520. mContext->mCurTypeState->mGlobalContainers.Clear();
  2521. for (int namespaceIdx = -1; namespaceIdx < (int)userTypeDef->mNamespaceSearch.size(); namespaceIdx++)
  2522. {
  2523. BfAtomComposite findStr;
  2524. if (namespaceIdx != -1)
  2525. findStr.Reference(userTypeDef->mNamespaceSearch[namespaceIdx]);
  2526. auto typeDefItr = mSystem->mTypeDefs.TryGet(findStr);
  2527. while (typeDefItr)
  2528. {
  2529. auto typeDef = *typeDefItr;
  2530. if ((typeDef->mFullName == findStr) && (typeDef->mIsCombinedPartial) && (typeDef->IsGlobalsContainer()))
  2531. {
  2532. if (typeDef->mProject->ContainsReference(typeDef->mProject))
  2533. {
  2534. BfGlobalContainerEntry globalEntry;
  2535. globalEntry.mTypeDef = typeDef;
  2536. globalEntry.mTypeInst = NULL;
  2537. typeDef->PopulateMemberSets();
  2538. mContext->mCurTypeState->mGlobalContainers.Add(globalEntry);
  2539. }
  2540. }
  2541. else if (!typeDef->mIsPartial)
  2542. {
  2543. //break;
  2544. }
  2545. typeDefItr.MoveToNextHashMatch();
  2546. }
  2547. }
  2548. mContext->mCurTypeState->mGlobalContainerCurUserTypeDef = userTypeDef;
  2549. }
  2550. // Only create actual typeInst when we have an applicable member. This helps in keeping unused globals from
  2551. // reifing types
  2552. for (auto& globalEntry : mContext->mCurTypeState->mGlobalContainers)
  2553. {
  2554. if (globalEntry.mTypeInst == NULL)
  2555. {
  2556. bool include = false;
  2557. if (globalLookup.mKind == BfGlobalLookup::Kind_All)
  2558. include = true;
  2559. else if (globalLookup.mKind == BfGlobalLookup::Kind_Field)
  2560. {
  2561. if (globalEntry.mTypeDef->mFieldSet.ContainsWith(globalLookup.mName))
  2562. include = true;
  2563. if (globalEntry.mTypeDef->mPropertySet.ContainsWith(globalLookup.mName))
  2564. include = true;
  2565. }
  2566. else if (globalLookup.mKind == BfGlobalLookup::Kind_Method)
  2567. {
  2568. if (globalEntry.mTypeDef->mMethodSet.ContainsWith(globalLookup.mName))
  2569. include = true;
  2570. }
  2571. if (include)
  2572. {
  2573. auto type = ResolveTypeDef(globalEntry.mTypeDef);
  2574. if (type != NULL)
  2575. globalEntry.mTypeInst = type->ToTypeInstance();
  2576. }
  2577. }
  2578. }
  2579. }
  2580. void PrintUsers(llvm::MDNode* md);
  2581. BfModuleOptions BfModule::GetModuleOptions()
  2582. {
  2583. if (mIsScratchModule)
  2584. return BfModuleOptions();
  2585. if (mModuleOptions != NULL)
  2586. return *mModuleOptions;
  2587. BfModuleOptions moduleOptions;
  2588. moduleOptions.mEmitDebugInfo = mCompiler->mOptions.mEmitDebugInfo ? 1 : mCompiler->mOptions.mEmitLineInfo ? 2 : 0;
  2589. if (mProject != NULL)
  2590. {
  2591. moduleOptions.mSIMDSetting = mProject->mCodeGenOptions.mSIMDSetting;
  2592. moduleOptions.mOptLevel = mProject->mCodeGenOptions.mOptLevel;
  2593. }
  2594. auto headModule = this;
  2595. while (headModule->mParentModule != NULL)
  2596. headModule = headModule->mParentModule;
  2597. BF_ASSERT((headModule->mOwnedTypeInstances.size() > 0) || (mModuleName == "vdata"));
  2598. if (headModule->mOwnedTypeInstances.size() > 0)
  2599. {
  2600. auto typeInst = headModule->mOwnedTypeInstances[0];
  2601. PopulateType(typeInst);
  2602. if (typeInst->mTypeOptionsIdx != -1)
  2603. {
  2604. auto typeOptions = mSystem->GetTypeOptions(typeInst->mTypeOptionsIdx);
  2605. moduleOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)moduleOptions.mSIMDSetting, typeOptions->mSIMDSetting);
  2606. moduleOptions.mEmitDebugInfo = BfTypeOptions::Apply(moduleOptions.mEmitDebugInfo, typeOptions->mEmitDebugInfo);
  2607. moduleOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)moduleOptions.mOptLevel, (int)typeOptions->mOptimizationLevel);
  2608. }
  2609. }
  2610. return moduleOptions;
  2611. }
  2612. BfCheckedKind BfModule::GetDefaultCheckedKind()
  2613. {
  2614. bool runtimeChecks = mCompiler->mOptions.mRuntimeChecks;
  2615. auto typeOptions = GetTypeOptions();
  2616. if (typeOptions != NULL)
  2617. runtimeChecks = BfTypeOptions::Apply(runtimeChecks, typeOptions->mRuntimeChecks);
  2618. return runtimeChecks ? BfCheckedKind_Checked : BfCheckedKind_Unchecked;
  2619. }
  2620. void BfModule::AddFailType(BfTypeInstance* typeInstance)
  2621. {
  2622. mContext->mFailTypes.Add(typeInstance);
  2623. }
  2624. void BfModule::CheckAddFailType()
  2625. {
  2626. //TODO: We removed this line, because failures in resolve-only generic method can occur in non-owning modules
  2627. // but we still need to add the owning type to the FailTypes list
  2628. //.. OLD:
  2629. // While we're inlining, it's possible that mCurTypeInstance belongs to another module, ignore it
  2630. /*if (mCurTypeInstance->mModule != this)
  2631. return;*/
  2632. // Using mHadBuildWarning to insert into mFailTypes is our core of our strategy for reasserting
  2633. // warnings on rebuilds where otherwise the warnings wouldn't be generated because no code was
  2634. // being recompiled. This forces types with warnings to be recompiled.
  2635. // We had this 'mIsResolveOnly' check for speed in resolveOnly, but we removed it so the IDE can be
  2636. // constantly warning-aware
  2637. if ((mHadBuildError) ||
  2638. (mHadBuildWarning /*&& !mCompiler->mIsResolveOnly*/))
  2639. {
  2640. //mContext->mFailTypes.Add(mCurTypeInstance);
  2641. }
  2642. }
  2643. void BfModule::MarkDerivedDirty(BfTypeInstance* typeInst)
  2644. {
  2645. if (!mCompiler->IsHotCompile())
  2646. return;
  2647. typeInst->mDirty = true;
  2648. for (auto& dep : typeInst->mDependencyMap)
  2649. {
  2650. auto depType = dep.mKey;
  2651. auto depFlags = dep.mValue.mFlags;
  2652. if ((depFlags & BfDependencyMap::DependencyFlag_DerivedFrom) != 0)
  2653. {
  2654. MarkDerivedDirty(depType->ToTypeInstance());
  2655. }
  2656. }
  2657. }
  2658. void BfModule::CreateStaticField(BfFieldInstance* fieldInstance, bool isThreadLocal)
  2659. {
  2660. auto fieldType = fieldInstance->GetResolvedType();
  2661. auto field = fieldInstance->GetFieldDef();
  2662. if (fieldType->IsVar())
  2663. return;
  2664. BfIRValue initValue;
  2665. if (field->mIsConst)
  2666. {
  2667. if (fieldType->IsPointer())
  2668. fieldType = fieldType->GetUnderlyingType();
  2669. }
  2670. if (!field->mIsExtern)
  2671. initValue = GetDefaultValue(fieldType);
  2672. if (fieldInstance->mOwner->IsUnspecializedType())
  2673. {
  2674. // Placeholder
  2675. auto ptrVal = CreatePointerType(fieldType);
  2676. mStaticFieldRefs[fieldInstance] = GetDefaultValue(ptrVal);
  2677. }
  2678. else
  2679. {
  2680. BfLogSysM("Creating static field Module:%p Type:%p\n", this, fieldType);
  2681. StringT<128> staticVarName;
  2682. BfMangler::Mangle(staticVarName, mCompiler->GetMangleKind(), fieldInstance);
  2683. if (!fieldType->IsValuelessType())
  2684. {
  2685. BfIRValue globalVar = mBfIRBuilder->CreateGlobalVariable(
  2686. mBfIRBuilder->MapType(fieldType, BfIRPopulateType_Eventually_Full),
  2687. false,
  2688. BfIRLinkageType_External,
  2689. initValue,
  2690. staticVarName,
  2691. isThreadLocal);
  2692. BF_ASSERT(globalVar);
  2693. mStaticFieldRefs[fieldInstance] = globalVar;
  2694. }
  2695. }
  2696. }
  2697. void BfModule::ResolveConstField(BfTypeInstance* typeInstance, BfFieldInstance* fieldInstance, BfFieldDef* fieldDef, bool forceResolve)
  2698. {
  2699. bool autoCompleteOnly = mCompiler->IsAutocomplete();
  2700. BfType* fieldType = NULL;
  2701. if (fieldInstance != NULL)
  2702. {
  2703. fieldType = fieldInstance->GetResolvedType();
  2704. if (fieldType == NULL)
  2705. fieldType = ResolveTypeRef(fieldDef->mTypeRef);
  2706. }
  2707. else
  2708. {
  2709. BF_ASSERT(mCompiler->IsAutocomplete());
  2710. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  2711. if ((typeInstance->IsEnum()) && (fieldDef->mTypeRef == NULL))
  2712. {
  2713. fieldType = typeInstance;
  2714. }
  2715. else
  2716. {
  2717. auto isLet = (fieldDef->mTypeRef != NULL) && (fieldDef->mTypeRef->IsExact<BfLetTypeReference>());
  2718. auto isVar = (fieldDef->mTypeRef != NULL) && (fieldDef->mTypeRef->IsExact<BfVarTypeReference>());
  2719. if (isLet || isVar)
  2720. fieldType = GetPrimitiveType(BfTypeCode_Var);
  2721. else
  2722. fieldType = ResolveTypeRef(fieldDef->mTypeRef);
  2723. if (fieldType == NULL)
  2724. fieldType = mContext->mBfObjectType;
  2725. }
  2726. }
  2727. if ((fieldInstance != NULL) && (fieldInstance->mConstIdx != -1) && (!forceResolve))
  2728. return;
  2729. if (mContext->mFieldResolveReentrys.size() > 1)
  2730. {
  2731. if (mContext->mFieldResolveReentrys.IndexOf(fieldInstance, 1) != -1)
  2732. {
  2733. String failStr = "Circular data reference detected between the following fields:";
  2734. for (int i = 1; i < (int)mContext->mFieldResolveReentrys.size(); i++)
  2735. {
  2736. if (i > 1)
  2737. failStr += ",";
  2738. failStr += "\n '" + TypeToString(typeInstance) + "." + mContext->mFieldResolveReentrys[i]->GetFieldDef()->mName + "'";
  2739. }
  2740. BfError* err = Fail(failStr, fieldDef->mFieldDeclaration);
  2741. if (err)
  2742. err->mIsPersistent = true;
  2743. return;
  2744. }
  2745. }
  2746. mContext->mFieldResolveReentrys.push_back(fieldInstance);
  2747. AutoPopBack<decltype (mContext->mFieldResolveReentrys)> popTypeResolveReentry(&mContext->mFieldResolveReentrys);
  2748. if (fieldInstance == NULL)
  2749. popTypeResolveReentry.Pop();
  2750. auto typeDef = typeInstance->mTypeDef;
  2751. BfIRValue constValue;
  2752. if (fieldDef->mIsExtern)
  2753. {
  2754. if (!fieldDef->mTypeRef->IsA<BfPointerTypeRef>())
  2755. {
  2756. Fail("Extern consts must be pointer types", fieldDef->mFieldDeclaration->mTypeRef);
  2757. }
  2758. if (fieldDef->mInitializer != NULL)
  2759. {
  2760. Fail("Extern consts cannot have initializers", fieldDef->mFieldDeclaration->mNameNode);
  2761. }
  2762. }
  2763. else if (fieldDef->mInitializer == NULL)
  2764. {
  2765. if (fieldDef->IsEnumCaseEntry())
  2766. {
  2767. if (typeInstance->IsTypedPrimitive())
  2768. {
  2769. BfFieldInstance* prevFieldInstance = NULL;
  2770. for (int i = fieldDef->mIdx - 1; i >= 0; i--)
  2771. {
  2772. BfFieldInstance* checkFieldInst = &typeInstance->mFieldInstances[i];
  2773. if (checkFieldInst->GetFieldDef()->IsEnumCaseEntry())
  2774. {
  2775. prevFieldInstance = checkFieldInst;
  2776. break;
  2777. }
  2778. }
  2779. if (prevFieldInstance == NULL)
  2780. constValue = GetConstValue(0, typeInstance);
  2781. else
  2782. {
  2783. ResolveConstField(typeInstance, prevFieldInstance, prevFieldInstance->GetFieldDef());
  2784. if (prevFieldInstance->mConstIdx == -1)
  2785. {
  2786. if (!mCompiler->IsAutocomplete())
  2787. AssertErrorState();
  2788. constValue = GetConstValue(0, typeInstance);
  2789. }
  2790. else
  2791. {
  2792. auto prevConstant = ConstantToCurrent(typeInstance->mConstHolder->GetConstantById(prevFieldInstance->mConstIdx), typeInstance->mConstHolder, typeInstance);
  2793. constValue = mBfIRBuilder->CreateAdd(prevConstant, GetConstValue(1, typeInstance));
  2794. }
  2795. }
  2796. }
  2797. }
  2798. else
  2799. {
  2800. Fail("Const requires initializer", fieldDef->mFieldDeclaration->mNameNode);
  2801. }
  2802. }
  2803. else
  2804. {
  2805. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  2806. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  2807. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL);
  2808. BfConstResolver constResolver(this);
  2809. BfMethodState methodState;
  2810. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  2811. methodState.mTempKind = BfMethodState::TempKind_Static;
  2812. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  2813. if (fieldType->IsVar())
  2814. {
  2815. auto initValue = GetFieldInitializerValue(fieldInstance, fieldDef->mInitializer, fieldDef, fieldType);
  2816. if (!initValue)
  2817. {
  2818. AssertErrorState();
  2819. initValue = GetDefaultTypedValue(mContext->mBfObjectType);
  2820. }
  2821. if (fieldInstance != NULL)
  2822. {
  2823. fieldInstance->mResolvedType = initValue.mType;
  2824. }
  2825. constValue = initValue.mValue;
  2826. }
  2827. else
  2828. {
  2829. auto uncastedInitValue = GetFieldInitializerValue(fieldInstance, fieldDef->mInitializer, fieldDef, fieldType);
  2830. constValue = uncastedInitValue.mValue;
  2831. }
  2832. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  2833. }
  2834. if (fieldInstance != NULL)
  2835. {
  2836. fieldType = fieldInstance->GetResolvedType();
  2837. if ((fieldType == NULL) || (fieldType->IsVar()))
  2838. {
  2839. AssertErrorState();
  2840. // Default const type is 'int'
  2841. BfTypedValue initValue = GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr));
  2842. if (fieldInstance != NULL)
  2843. {
  2844. fieldInstance->mResolvedType = initValue.mType;
  2845. }
  2846. constValue = initValue.mValue;
  2847. }
  2848. if ((constValue) && (fieldInstance->mConstIdx == -1))
  2849. {
  2850. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  2851. CurrentAddToConstHolder(constValue);
  2852. fieldInstance->mConstIdx = constValue.mId;
  2853. }
  2854. }
  2855. }
  2856. BfType* BfModule::ResolveVarFieldType(BfTypeInstance* typeInstance, BfFieldInstance* fieldInstance, BfFieldDef* field)
  2857. {
  2858. bool isDeclType = BfNodeDynCastExact<BfDeclTypeRef>(field->mFieldDeclaration->mTypeRef) != NULL;
  2859. auto fieldType = fieldInstance->GetResolvedType();
  2860. if ((field->mIsConst) && (!isDeclType))
  2861. {
  2862. ResolveConstField(typeInstance, fieldInstance, field);
  2863. return fieldInstance->GetResolvedType();
  2864. }
  2865. bool staticOnly = (field->mIsStatic) && (!isDeclType);
  2866. if (!fieldInstance->mIsInferredType)
  2867. return fieldType;
  2868. if (!fieldType->IsVar())
  2869. return fieldType;
  2870. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  2871. BfTypeState typeState(mCurTypeInstance, mContext->mCurTypeState);
  2872. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState, mContext->mCurTypeState->mTypeInstance != typeInstance);
  2873. auto typeDef = typeInstance->mTypeDef;
  2874. if ((!field->mIsStatic) && (typeDef->mIsStatic))
  2875. {
  2876. AssertErrorState();
  2877. return GetPrimitiveType(BfTypeCode_Var);
  2878. }
  2879. bool hadInferenceCycle = false;
  2880. if (mContext->mFieldResolveReentrys.size() > 1)
  2881. {
  2882. if (mContext->mFieldResolveReentrys.IndexOf(fieldInstance, 1) != -1)
  2883. {
  2884. for (int i = 1; i < (int)mContext->mFieldResolveReentrys.size(); i++)
  2885. {
  2886. auto fieldInst = mContext->mFieldResolveReentrys[i];
  2887. auto fieldDef = fieldInst->GetFieldDef();
  2888. auto fieldOwner = fieldInst->mOwner;
  2889. auto fieldModule = fieldOwner->mModule;
  2890. SetAndRestoreValue<bool> prevIgnoreError(fieldModule->mIgnoreErrors, false);
  2891. fieldModule->Fail(StrFormat("Field '%s.%s' creates a type inference cycle", TypeToString(fieldOwner).c_str(), fieldDef->mName.c_str()), fieldDef->mTypeRef, true);
  2892. }
  2893. return GetPrimitiveType(BfTypeCode_Var);
  2894. }
  2895. }
  2896. mContext->mFieldResolveReentrys.push_back(fieldInstance);
  2897. AutoPopBack<decltype (mContext->mFieldResolveReentrys)> popTypeResolveReentry(&mContext->mFieldResolveReentrys);
  2898. SetAndRestoreValue<bool> prevResolvingVar(typeInstance->mResolvingVarField, true);
  2899. SetAndRestoreValue<bool> prevCtxResolvingVar(mContext->mResolvingVarField, true);
  2900. if ((field->mInitializer == NULL) && (!isDeclType))
  2901. {
  2902. if ((field->mTypeRef->IsA<BfVarTypeReference>()) || (field->mTypeRef->IsA<BfLetTypeReference>()))
  2903. Fail("Implicitly-typed fields must be initialized", field->GetRefNode());
  2904. return GetPrimitiveType(BfTypeCode_Var);
  2905. }
  2906. BfType* resolvedType = NULL;
  2907. if (!hadInferenceCycle)
  2908. {
  2909. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  2910. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL/*ctorMethod.mMethodInstance*/);
  2911. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  2912. BfMethodState methodState;
  2913. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  2914. methodState.mTempKind = staticOnly ? BfMethodState::TempKind_Static : BfMethodState::TempKind_NonStatic;
  2915. if (!staticOnly)
  2916. {
  2917. //BfLocalVariable localVar;
  2918. //methodState.mLocals.push_back(localVar);
  2919. }
  2920. if (isDeclType)
  2921. {
  2922. auto fieldDef = fieldInstance->GetFieldDef();
  2923. resolvedType = ResolveTypeRef(fieldDef->mTypeRef, BfPopulateType_Identity);
  2924. }
  2925. else
  2926. {
  2927. BfTypedValue valueFromExpr;
  2928. valueFromExpr = GetFieldInitializerValue(fieldInstance);
  2929. FixIntUnknown(valueFromExpr);
  2930. resolvedType = valueFromExpr.mType;
  2931. }
  2932. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  2933. }
  2934. if (resolvedType == NULL)
  2935. return GetPrimitiveType(BfTypeCode_Var);
  2936. fieldInstance->SetResolvedType(resolvedType);
  2937. if (field->mIsStatic)
  2938. {
  2939. }
  2940. else if (fieldInstance->mDataIdx <= 0)
  2941. {
  2942. }
  2943. else
  2944. {
  2945. BF_ASSERT(typeInstance->IsIncomplete());
  2946. }
  2947. return resolvedType;
  2948. }
  2949. void BfModule::MarkFieldInitialized(BfFieldInstance* fieldInstance)
  2950. {
  2951. BF_ASSERT(fieldInstance->mOwner == mCurTypeInstance);
  2952. auto fieldType = fieldInstance->GetResolvedType();
  2953. if ((fieldInstance->mMergedDataIdx != -1) && (mCurMethodState != NULL))
  2954. {
  2955. int fieldDataCount = 1;
  2956. if (fieldType->IsStruct())
  2957. {
  2958. auto structTypeInst = fieldType->ToTypeInstance();
  2959. fieldDataCount = structTypeInst->mMergedFieldDataCount;
  2960. }
  2961. //TODO: Under what circumstances could 'thisVariable' be NULL?
  2962. auto thisVariable = GetThisVariable();
  2963. if (thisVariable != NULL)
  2964. {
  2965. for (int i = 0; i < fieldDataCount; i++)
  2966. mCurMethodState->LocalDefined(thisVariable, fieldInstance->mMergedDataIdx + i);
  2967. }
  2968. }
  2969. }
  2970. bool BfModule::IsThreadLocal(BfFieldInstance * fieldInstance)
  2971. {
  2972. if (fieldInstance->mCustomAttributes == NULL)
  2973. return false;
  2974. auto fieldDef = fieldInstance->GetFieldDef();
  2975. if (!fieldDef->mIsStatic)
  2976. return false;
  2977. bool isThreadLocal = false;
  2978. if (fieldInstance->mCustomAttributes != NULL)
  2979. {
  2980. for (auto customAttr : fieldInstance->mCustomAttributes->mAttributes)
  2981. {
  2982. if (customAttr.mType->ToTypeInstance()->mTypeDef == mCompiler->mThreadStaticAttributeTypeDef)
  2983. return true;
  2984. }
  2985. }
  2986. return false;
  2987. }
  2988. BfTypedValue BfModule::GetFieldInitializerValue(BfFieldInstance* fieldInstance, BfExpression* initializer, BfFieldDef* fieldDef, BfType* fieldType)
  2989. {
  2990. if (fieldDef == NULL)
  2991. fieldDef = fieldInstance->GetFieldDef();
  2992. if (fieldType == NULL)
  2993. fieldType = fieldInstance->GetResolvedType();
  2994. if (initializer == NULL)
  2995. {
  2996. if (fieldDef == NULL)
  2997. return BfTypedValue();
  2998. initializer = fieldDef->mInitializer;
  2999. }
  3000. BfTypedValue result;
  3001. if (initializer == NULL)
  3002. {
  3003. result = GetDefaultTypedValue(fieldInstance->mResolvedType);
  3004. }
  3005. else
  3006. {
  3007. if ((mCompiler->mIsResolveOnly) && (mCompiler->mResolvePassData->mSourceClassifier != NULL) && (initializer->IsFromParser(mCompiler->mResolvePassData->mParser)))
  3008. {
  3009. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(initializer, BfSourceElementType_Normal);
  3010. mCompiler->mResolvePassData->mSourceClassifier->VisitChildNoRef(initializer);
  3011. }
  3012. if ((mCurTypeInstance->IsPayloadEnum()) && (fieldDef->IsEnumCaseEntry()))
  3013. {
  3014. Fail("Enums with payloads cannot have explicitly-defined discriminators", initializer);
  3015. BfConstResolver constResolver(this);
  3016. constResolver.Resolve(initializer);
  3017. return GetDefaultTypedValue(fieldType);
  3018. }
  3019. else if (fieldDef->mIsConst)
  3020. {
  3021. BfTypeState typeState;
  3022. typeState.mCurTypeDef = fieldDef->mDeclaringType;
  3023. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  3024. BfConstResolver constResolver(this);
  3025. if (fieldType->IsVar())
  3026. return constResolver.Resolve(initializer);
  3027. else
  3028. return constResolver.Resolve(initializer, fieldType);
  3029. }
  3030. if (fieldType->IsVar())
  3031. result = CreateValueFromExpression(initializer, NULL, (BfEvalExprFlags)(BfEvalExprFlags_NoValueAddr | BfEvalExprFlags_FieldInitializer));
  3032. else
  3033. result = CreateValueFromExpression(initializer, fieldType, (BfEvalExprFlags)(BfEvalExprFlags_NoValueAddr | BfEvalExprFlags_FieldInitializer));
  3034. }
  3035. if (fieldInstance != NULL)
  3036. MarkFieldInitialized(fieldInstance);
  3037. return result;
  3038. }
  3039. void BfModule::CheckInterfaceMethod(BfMethodInstance* methodInstance)
  3040. {
  3041. }
  3042. void BfModule::FindSubTypes(BfTypeInstance* classType, SizedArrayImpl<int>* outVals, SizedArrayImpl<BfTypeInstance*>* exChecks, bool isInterfacePass)
  3043. {
  3044. PopulateType(classType);
  3045. if (isInterfacePass)
  3046. {
  3047. for (auto ifaceInst : classType->mInterfaces)
  3048. {
  3049. if (exChecks->Contains(ifaceInst.mInterfaceType))
  3050. continue;
  3051. if (outVals->Contains(ifaceInst.mInterfaceType->mTypeId))
  3052. continue;
  3053. if (ifaceInst.mDeclaringType->IsExtension())
  3054. {
  3055. bool needsExCheck = false;
  3056. if (ifaceInst.mDeclaringType->mProject != classType->mTypeDef->mProject)
  3057. {
  3058. exChecks->push_back(ifaceInst.mInterfaceType);
  3059. continue;
  3060. }
  3061. }
  3062. outVals->push_back(ifaceInst.mInterfaceType->mTypeId);
  3063. }
  3064. }
  3065. else
  3066. {
  3067. outVals->push_back(classType->mTypeId);
  3068. }
  3069. if (classType->mBaseType != NULL)
  3070. {
  3071. FindSubTypes(classType->mBaseType, outVals, exChecks, isInterfacePass);
  3072. }
  3073. }
  3074. void BfModule::CreateDynamicCastMethod()
  3075. {
  3076. auto objType = mContext->mBfObjectType;
  3077. if ((mCompiler->mIsResolveOnly) || (!mIsReified))
  3078. {
  3079. // The main reason to punt on this method for ResolveOnly is because types can be created
  3080. // and destroyed quickly during autocomplete and the typeId creep can generate lots of
  3081. // entries in the LLVM ConstantInt pool, primarily from the FindSubTypes call. We can
  3082. // remove this punt when we recycle typeId's
  3083. mBfIRBuilder->CreateRet(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(objType)));
  3084. mCurMethodState->mHadReturn = true;
  3085. return;
  3086. }
  3087. bool isInterfacePass = mCurMethodInstance->mMethodDef->mName == BF_METHODNAME_DYNAMICCAST_INTERFACE;
  3088. auto func = mCurMethodState->mIRFunction;
  3089. auto thisValue = mBfIRBuilder->GetArgument(0);
  3090. auto typeIdValue = mBfIRBuilder->GetArgument(1);
  3091. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  3092. auto int32Type = GetPrimitiveType(BfTypeCode_Int32);
  3093. typeIdValue = CastToValue(NULL, BfTypedValue(typeIdValue, intPtrType), int32Type, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_SilentFail));
  3094. auto thisObject = mBfIRBuilder->CreateBitCast(thisValue, mBfIRBuilder->MapType(objType));
  3095. auto trueBB = mBfIRBuilder->CreateBlock("check.true");
  3096. //auto falseBB = mBfIRBuilder->CreateBlock("check.false");
  3097. auto exitBB = mBfIRBuilder->CreateBlock("exit");
  3098. SizedArray<int, 8> typeMatches;
  3099. SizedArray<BfTypeInstance*, 8> exChecks;
  3100. FindSubTypes(mCurTypeInstance, &typeMatches, &exChecks, isInterfacePass);
  3101. if ((mCurTypeInstance->IsGenericTypeInstance()) && (!mCurTypeInstance->IsUnspecializedType()))
  3102. {
  3103. // Add 'unbound' type id to cast list so things like "List<int> is List<>" work
  3104. auto genericTypeInst = mCurTypeInstance->mTypeDef;
  3105. BfTypeVector genericArgs;
  3106. for (int i = 0; i < (int) genericTypeInst->mGenericParamDefs.size(); i++)
  3107. genericArgs.push_back(GetGenericParamType(BfGenericParamKind_Type, i));
  3108. auto unboundType = ResolveTypeDef(mCurTypeInstance->mTypeDef, genericArgs, BfPopulateType_Declaration);
  3109. typeMatches.push_back(unboundType->mTypeId);
  3110. }
  3111. if (mCurTypeInstance->IsBoxed())
  3112. {
  3113. BfBoxedType* boxedType = (BfBoxedType*)mCurTypeInstance;
  3114. BfTypeInstance* innerType = boxedType->mElementType;
  3115. FindSubTypes(innerType, &typeMatches, &exChecks, isInterfacePass);
  3116. if (innerType->IsTypedPrimitive())
  3117. {
  3118. auto underlyingType = innerType->GetUnderlyingType();
  3119. typeMatches.push_back(underlyingType->mTypeId);
  3120. }
  3121. auto innerTypeInst = innerType->ToTypeInstance();
  3122. if ((innerTypeInst->mTypeDef == mCompiler->mSizedArrayTypeDef) ||
  3123. (innerTypeInst->mTypeDef == mCompiler->mPointerTTypeDef) ||
  3124. (innerTypeInst->mTypeDef == mCompiler->mMethodRefTypeDef))
  3125. {
  3126. PopulateType(innerTypeInst);
  3127. //TODO: What case was this supposed to handle?
  3128. //typeMatches.push_back(innerTypeInst->mFieldInstances[0].mResolvedType->mTypeId);
  3129. }
  3130. }
  3131. auto curBlock = mBfIRBuilder->GetInsertBlock();
  3132. BfIRValue vDataPtr;
  3133. if (!exChecks.empty())
  3134. {
  3135. BfType* intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  3136. auto ptrPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(intPtrType)));
  3137. auto vDataPtrPtr = mBfIRBuilder->CreateBitCast(thisValue, ptrPtrType);
  3138. vDataPtr = FixClassVData(mBfIRBuilder->CreateLoad(vDataPtrPtr/*, "vtable"*/));
  3139. }
  3140. auto switchStatement = mBfIRBuilder->CreateSwitch(typeIdValue, exitBB, (int)typeMatches.size() + (int)exChecks.size());
  3141. for (auto typeMatch : typeMatches)
  3142. mBfIRBuilder->AddSwitchCase(switchStatement, GetConstValue32(typeMatch), trueBB);
  3143. Array<BfIRValue> incomingFalses;
  3144. for (auto ifaceTypeInst : exChecks)
  3145. {
  3146. BfIRBlock nextBB = mBfIRBuilder->CreateBlock("exCheck", true);
  3147. mBfIRBuilder->AddSwitchCase(switchStatement, GetConstValue32(ifaceTypeInst->mTypeId), nextBB);
  3148. mBfIRBuilder->SetInsertPoint(nextBB);
  3149. BfIRValue slotOfs = GetInterfaceSlotNum(ifaceTypeInst);
  3150. auto ifacePtrPtr = mBfIRBuilder->CreateInBoundsGEP(vDataPtr, slotOfs/*, "iface"*/);
  3151. auto ifacePtr = mBfIRBuilder->CreateLoad(ifacePtrPtr);
  3152. auto cmpResult = mBfIRBuilder->CreateCmpNE(ifacePtr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0));
  3153. mBfIRBuilder->CreateCondBr(cmpResult, trueBB, exitBB);
  3154. incomingFalses.push_back(nextBB);
  3155. }
  3156. mBfIRBuilder->AddBlock(trueBB);
  3157. mBfIRBuilder->SetInsertPoint(trueBB);
  3158. mBfIRBuilder->CreateBr(exitBB);
  3159. mBfIRBuilder->AddBlock(exitBB);
  3160. mBfIRBuilder->SetInsertPoint(exitBB);
  3161. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapTypeInstPtr(objType), 2);
  3162. mBfIRBuilder->AddPhiIncoming(phi, thisObject, trueBB);
  3163. auto nullValue = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(objType));
  3164. for (auto incomingFalseBlock : incomingFalses)
  3165. mBfIRBuilder->AddPhiIncoming(phi, nullValue, incomingFalseBlock);
  3166. mBfIRBuilder->AddPhiIncoming(phi, nullValue, curBlock);
  3167. mBfIRBuilder->CreateRet(phi);
  3168. mCurMethodState->mHadReturn = true;
  3169. }
  3170. void BfModule::EmitEquals(BfTypedValue leftValue, BfTypedValue rightValue, BfIRBlock exitBB)
  3171. {
  3172. BfExprEvaluator exprEvaluator(this);
  3173. exprEvaluator.mExpectingType = mCurMethodInstance->mReturnType;
  3174. exprEvaluator.PerformBinaryOperation((BfAstNode*)NULL, (BfAstNode*)NULL, BfBinaryOp_Equality, NULL, BfBinOpFlag_None, leftValue, rightValue);
  3175. BfTypedValue result = exprEvaluator.GetResult();
  3176. if (result)
  3177. {
  3178. auto nextBB = mBfIRBuilder->CreateBlock("next");
  3179. mBfIRBuilder->CreateCondBr(result.mValue, nextBB, exitBB);
  3180. mBfIRBuilder->AddBlock(nextBB);
  3181. mBfIRBuilder->SetInsertPoint(nextBB);
  3182. }
  3183. }
  3184. void BfModule::CreateFakeCallerMethod(const String& funcName)
  3185. {
  3186. BF_ASSERT(mCurMethodInstance->mIRFunction);
  3187. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  3188. SizedArray<BfIRType, 4> paramTypes;
  3189. BfIRFunctionType funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  3190. BfIRFunction func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_Internal, "FORCELINK_" + funcName);
  3191. mBfIRBuilder->SetActiveFunction(func);
  3192. auto entryBlock = mBfIRBuilder->CreateBlock("main", true);
  3193. mBfIRBuilder->SetInsertPoint(entryBlock);
  3194. SizedArray<BfIRValue, 8> args;
  3195. BfExprEvaluator exprEvaluator(this);
  3196. if (mCurMethodInstance->HasThis())
  3197. {
  3198. auto thisValue = GetDefaultTypedValue(mCurMethodInstance->GetOwner(), true);
  3199. exprEvaluator.PushThis(NULL, thisValue, mCurMethodInstance, args);
  3200. }
  3201. for (int paramIdx = 0; paramIdx < mCurMethodInstance->GetParamCount(); paramIdx++)
  3202. {
  3203. auto paramType = mCurMethodInstance->GetParamType(paramIdx);
  3204. if (paramType->IsValuelessType())
  3205. continue;
  3206. exprEvaluator.PushArg(GetDefaultTypedValue(paramType, true), args);
  3207. }
  3208. mBfIRBuilder->CreateCall(mCurMethodInstance->mIRFunction, args);
  3209. mBfIRBuilder->CreateRetVoid();
  3210. }
  3211. void BfModule::CreateValueTypeEqualsMethod()
  3212. {
  3213. if (mCurMethodInstance->mIsUnspecialized)
  3214. return;
  3215. if (mCurTypeInstance->IsTypedPrimitive())
  3216. return;
  3217. if (mBfIRBuilder->mIgnoreWrites)
  3218. return;
  3219. BF_ASSERT(!mCurTypeInstance->IsBoxed());
  3220. auto compareType = mCurMethodInstance->mParams[0].mResolvedType;
  3221. bool isValid = true;
  3222. auto compareDType = compareType->ToDependedType();
  3223. BfTypeInstance* compareTypeInst = compareType->ToTypeInstance();
  3224. if (compareTypeInst != NULL)
  3225. {
  3226. if (compareType->IsPrimitiveType())
  3227. compareTypeInst = GetWrappedStructType(compareType);
  3228. if ((compareTypeInst == NULL) || (!compareTypeInst->IsValueType()))
  3229. {
  3230. isValid = false;
  3231. }
  3232. mBfIRBuilder->PopulateType(compareTypeInst);
  3233. }
  3234. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  3235. if (!isValid)
  3236. {
  3237. ClearLifetimeEnds();
  3238. mBfIRBuilder->CreateRet(GetDefaultValue(boolType));
  3239. return;
  3240. }
  3241. AddDependency(compareDType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  3242. auto refNode = mCurTypeInstance->mTypeDef->GetRefNode();
  3243. if (refNode == NULL)
  3244. refNode = mCompiler->mValueTypeTypeDef->GetRefNode();
  3245. UpdateSrcPos(refNode);
  3246. SetIllegalSrcPos();
  3247. auto resultVal = CreateAlloca(boolType);
  3248. mBfIRBuilder->CreateStore(GetConstValue(0, boolType), resultVal);
  3249. auto exitBB = mBfIRBuilder->CreateBlock("exit");
  3250. if (compareType->IsSizedArray())
  3251. {
  3252. auto sizedArrayType = (BfSizedArrayType*)compareType;
  3253. if (sizedArrayType->mElementCount > 6)
  3254. {
  3255. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  3256. auto itr = CreateAlloca(intPtrType);
  3257. mBfIRBuilder->CreateStore(GetDefaultValue(intPtrType), itr);
  3258. auto loopBB = mBfIRBuilder->CreateBlock("loop", true);
  3259. auto bodyBB = mBfIRBuilder->CreateBlock("body", true);
  3260. auto doneBB = mBfIRBuilder->CreateBlock("done", true);
  3261. mBfIRBuilder->CreateBr(loopBB);
  3262. mBfIRBuilder->SetInsertPoint(loopBB);
  3263. auto loadedItr = mBfIRBuilder->CreateLoad(itr);
  3264. auto cmpRes = mBfIRBuilder->CreateCmpGTE(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)sizedArrayType->mElementCount), true);
  3265. mBfIRBuilder->CreateCondBr(cmpRes, doneBB, bodyBB);
  3266. mBfIRBuilder->SetInsertPoint(bodyBB);
  3267. BfTypedValue leftValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, GetDefaultValue(intPtrType), loadedItr), sizedArrayType->mElementType, BfTypedValueKind_Addr);
  3268. BfTypedValue rightValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[1]->mValue, GetDefaultValue(intPtrType), loadedItr), sizedArrayType->mElementType, BfTypedValueKind_Addr);
  3269. EmitEquals(leftValue, rightValue, exitBB);
  3270. auto incValue = mBfIRBuilder->CreateAdd(loadedItr, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  3271. mBfIRBuilder->CreateStore(incValue, itr);
  3272. mBfIRBuilder->CreateBr(loopBB);
  3273. mBfIRBuilder->SetInsertPoint(doneBB);
  3274. }
  3275. else
  3276. {
  3277. for (int dataIdx = 0; dataIdx < sizedArrayType->mElementCount; dataIdx++)
  3278. {
  3279. BfTypedValue leftValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, dataIdx), sizedArrayType->mElementType, BfTypedValueKind_Addr);
  3280. BfTypedValue rightValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[1]->mValue, 0, dataIdx), sizedArrayType->mElementType, BfTypedValueKind_Addr);
  3281. EmitEquals(leftValue, rightValue, exitBB);
  3282. }
  3283. }
  3284. }
  3285. else if (compareType->IsMethodRef())
  3286. {
  3287. auto methodRefType = (BfMethodRefType*)compareType;
  3288. BfMethodInstance* methodInstance = methodRefType->mMethodRef;
  3289. BfExprEvaluator exprEvaluator(this);
  3290. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  3291. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  3292. // We only need to compare the 'this' capture. The rationale is that it's impossible to capture any other non-matching
  3293. // values for the same method reference -- they will always refer back to the same local variables.
  3294. int dataIdx = methodRefType->GetDataIdxFromParamIdx(-1);
  3295. if (dataIdx != -1)
  3296. {
  3297. bool failed = false;
  3298. BfTypedValue leftValue = exprEvaluator.DoImplicitArgCapture(NULL, methodInstance, methodRefType->GetParamIdxFromDataIdx(dataIdx), failed, BfImplicitParamKind_General, leftTypedVal);
  3299. BfTypedValue rightValue = exprEvaluator.DoImplicitArgCapture(NULL, methodInstance, methodRefType->GetParamIdxFromDataIdx(dataIdx), failed, BfImplicitParamKind_General, rightTypedVal);
  3300. BF_ASSERT(!failed);
  3301. EmitEquals(leftValue, rightValue, exitBB);
  3302. }
  3303. }
  3304. else if (compareTypeInst->IsEnum())
  3305. {
  3306. //auto intType = GetPrimitiveType(BfTypeCode_Int32);
  3307. BfExprEvaluator exprEvaluator(this);
  3308. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  3309. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  3310. auto dscrType = compareTypeInst->GetDiscriminatorType();
  3311. BfTypedValue leftValue = ExtractValue(leftTypedVal, NULL, 2);
  3312. leftValue = LoadValue(leftValue);
  3313. BfTypedValue rightValue = ExtractValue(rightTypedVal, NULL, 2);
  3314. rightValue = LoadValue(rightValue);
  3315. BfTypedValue leftPayload = ExtractValue(leftTypedVal, NULL, 1);
  3316. BfTypedValue rightPayload = ExtractValue(rightTypedVal, NULL, 1);
  3317. EmitEquals(leftValue, rightValue, exitBB);
  3318. int enumCount = 0;
  3319. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  3320. {
  3321. BfFieldInstance* fieldInstance = &fieldRef;
  3322. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  3323. if ((fieldDef != NULL) && (fieldDef->IsEnumCaseEntry()))
  3324. {
  3325. enumCount = -fieldInstance->mDataIdx;
  3326. }
  3327. }
  3328. if (enumCount > 0)
  3329. {
  3330. BfIRBlock matchedBlock = mBfIRBuilder->CreateBlock("matched");
  3331. auto switchVal = mBfIRBuilder->CreateSwitch(leftValue.mValue, exitBB, enumCount);
  3332. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  3333. {
  3334. BfFieldInstance* fieldInstance = &fieldRef;
  3335. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  3336. if ((fieldDef != NULL) && (fieldDef->IsEnumCaseEntry()))
  3337. {
  3338. int enumIdx = -fieldInstance->mDataIdx - 1;
  3339. if (fieldInstance->mResolvedType->mSize == 0)
  3340. {
  3341. mBfIRBuilder->AddSwitchCase(switchVal, mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, enumIdx), matchedBlock);
  3342. }
  3343. else
  3344. {
  3345. auto caseBlock = mBfIRBuilder->CreateBlock("case", true);
  3346. mBfIRBuilder->SetInsertPoint(caseBlock);
  3347. auto tuplePtr = CreatePointerType(fieldInstance->mResolvedType);
  3348. BfTypedValue leftTuple;
  3349. BfTypedValue rightTuple;
  3350. if (leftPayload.IsAddr())
  3351. {
  3352. leftTuple = BfTypedValue(mBfIRBuilder->CreateBitCast(leftPayload.mValue, mBfIRBuilder->MapType(tuplePtr)), fieldInstance->mResolvedType, true);
  3353. rightTuple = BfTypedValue(mBfIRBuilder->CreateBitCast(rightPayload.mValue, mBfIRBuilder->MapType(tuplePtr)), fieldInstance->mResolvedType, true);
  3354. }
  3355. else
  3356. {
  3357. leftTuple = Cast(NULL, leftPayload, fieldInstance->mResolvedType, BfCastFlags_Force);
  3358. rightTuple = Cast(NULL, rightPayload, fieldInstance->mResolvedType, BfCastFlags_Force);
  3359. }
  3360. EmitEquals(leftTuple, rightTuple, exitBB);
  3361. mBfIRBuilder->CreateBr(matchedBlock);
  3362. mBfIRBuilder->AddSwitchCase(switchVal, mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, enumIdx), caseBlock);
  3363. }
  3364. }
  3365. }
  3366. mBfIRBuilder->AddBlock(matchedBlock);
  3367. mBfIRBuilder->SetInsertPoint(matchedBlock);
  3368. }
  3369. }
  3370. else if (compareTypeInst->IsUnion())
  3371. {
  3372. auto innerType = compareTypeInst->GetUnionInnerType();
  3373. if (!innerType->IsValuelessType())
  3374. {
  3375. BfExprEvaluator exprEvaluator(this);
  3376. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  3377. BfTypedValue leftUnionTypedVal = ExtractValue(leftTypedVal, NULL, 1);
  3378. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  3379. BfTypedValue rightUnionTypedVal = ExtractValue(rightTypedVal, NULL, 1);
  3380. EmitEquals(leftUnionTypedVal, rightUnionTypedVal, exitBB);
  3381. }
  3382. }
  3383. else
  3384. {
  3385. BfExprEvaluator exprEvaluator(this);
  3386. BfTypedValue leftTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[0]);
  3387. BfTypedValue rightTypedVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  3388. bool hadComparison = false;
  3389. for (auto& fieldRef : compareTypeInst->mFieldInstances)
  3390. {
  3391. BfFieldInstance* fieldInstance = &fieldRef;
  3392. if (fieldInstance->mDataOffset == -1)
  3393. continue;
  3394. if (fieldInstance->mResolvedType->IsValuelessType())
  3395. continue;
  3396. BfTypedValue leftValue = ExtractValue(leftTypedVal, fieldInstance, fieldInstance->mDataIdx);
  3397. BfTypedValue rightValue = ExtractValue(rightTypedVal, fieldInstance, fieldInstance->mDataIdx);
  3398. if (!fieldInstance->mResolvedType->IsComposite())
  3399. {
  3400. leftValue = LoadValue(leftValue);
  3401. rightValue = LoadValue(rightValue);
  3402. }
  3403. EmitEquals(leftValue, rightValue, exitBB);
  3404. }
  3405. auto baseTypeInst = compareTypeInst->mBaseType;
  3406. if ((baseTypeInst != NULL) && (baseTypeInst->mTypeDef != mCompiler->mValueTypeTypeDef))
  3407. {
  3408. BfTypedValue leftOrigValue(mCurMethodState->mLocals[0]->mValue, compareTypeInst, true);
  3409. BfTypedValue rightOrigValue(mCurMethodState->mLocals[1]->mValue, compareTypeInst, true);
  3410. BfTypedValue leftValue = Cast(NULL, leftOrigValue, baseTypeInst);
  3411. BfTypedValue rightValue = Cast(NULL, rightOrigValue, baseTypeInst);
  3412. EmitEquals(leftValue, rightValue, exitBB);
  3413. }
  3414. }
  3415. mBfIRBuilder->CreateStore(GetConstValue(1, boolType), resultVal);
  3416. mBfIRBuilder->CreateBr(exitBB);
  3417. mBfIRBuilder->AddBlock(exitBB);
  3418. mBfIRBuilder->SetInsertPoint(exitBB);
  3419. auto loadedResult = mBfIRBuilder->CreateLoad(resultVal);
  3420. ClearLifetimeEnds();
  3421. mBfIRBuilder->CreateRet(loadedResult);
  3422. mCurMethodState->mHadReturn = true;
  3423. }
  3424. BfIRValue BfModule::CreateClassVDataGlobal(BfTypeInstance* typeInstance, int* outNumElements, String* outMangledName)
  3425. {
  3426. if (mBfIRBuilder->mIgnoreWrites)
  3427. return mBfIRBuilder->GetFakeVal();
  3428. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  3429. BfType* classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  3430. BfIRValue* globalVariablePtr = NULL;
  3431. mClassVDataRefs.TryGetValue(typeInstance, &globalVariablePtr);
  3432. int numElements = 1;
  3433. if ((outNumElements != NULL) || (globalVariablePtr == NULL))
  3434. {
  3435. numElements += mCompiler->mMaxInterfaceSlots;
  3436. auto maxIFaceVirtIdx = 0;
  3437. if (!typeInstance->IsInterface())
  3438. {
  3439. int dynCastDataElems = 1 + mCompiler->mMaxInterfaceSlots;
  3440. numElements += ((dynCastDataElems * 4) + mSystem->mPtrSize - 1) / mSystem->mPtrSize;
  3441. numElements += typeInstance->GetOrigVTableSize();
  3442. int ifaceMethodLen = typeInstance->GetIFaceVMethodSize();
  3443. if (typeInstance->mHotTypeData != NULL)
  3444. {
  3445. if (typeInstance->mHotTypeData->mOrigInterfaceMethodsLength != -1)
  3446. ifaceMethodLen = typeInstance->mHotTypeData->mOrigInterfaceMethodsLength;
  3447. }
  3448. numElements += ifaceMethodLen;
  3449. }
  3450. if (outNumElements != NULL)
  3451. *outNumElements = numElements;
  3452. }
  3453. StringT<128> classVDataName;
  3454. String memberName = "sBfClassVData";
  3455. if ((typeInstance->mHotTypeData != NULL) && ((typeInstance->mHotTypeData->mHadDataChange) || (typeInstance->mHotTypeData->mPendingDataChange)))
  3456. {
  3457. auto curVersion = typeInstance->mHotTypeData->GetLatestVersion();
  3458. memberName += "_";
  3459. memberName += BfTypeUtils::HashEncode64(curVersion->mDataHash.mLow);
  3460. memberName += BfTypeUtils::HashEncode64(curVersion->mDataHash.mHigh);
  3461. }
  3462. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), typeInstance, memberName, classVDataType);
  3463. if (outMangledName != NULL)
  3464. *outMangledName = classVDataName;
  3465. /*if (itr != mClassVDataRefs.end())
  3466. {
  3467. globalVariable = itr->second;
  3468. }*/
  3469. BfIRValue globalVariable;
  3470. if (globalVariablePtr != NULL)
  3471. {
  3472. globalVariable = *globalVariablePtr;
  3473. }
  3474. else
  3475. {
  3476. BfLogSysM("Creating VData %s\n", classVDataName.c_str());
  3477. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), numElements);
  3478. globalVariable = mBfIRBuilder->CreateGlobalVariable(
  3479. arrayType,
  3480. true,
  3481. BfIRLinkageType_External,
  3482. BfIRValue(),
  3483. classVDataName);
  3484. mClassVDataRefs[typeInstance] = globalVariable;
  3485. }
  3486. return globalVariable;
  3487. }
  3488. BfIRValue BfModule::GetClassVDataPtr(BfTypeInstance* typeInstance)
  3489. {
  3490. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  3491. return mBfIRBuilder->CreateBitCast(CreateClassVDataGlobal(typeInstance), mBfIRBuilder->MapType(CreatePointerType(classVDataType)));
  3492. }
  3493. BfIRValue BfModule::CreateClassVDataExtGlobal(BfTypeInstance* declTypeInst, BfTypeInstance* implTypeInst, int startVirtIdx)
  3494. {
  3495. if (mBfIRBuilder->mIgnoreWrites)
  3496. return mBfIRBuilder->GetFakeVal();
  3497. int numElements = declTypeInst->GetSelfVTableSize() - declTypeInst->GetOrigSelfVTableSize();
  3498. BF_ASSERT(numElements >= 0);
  3499. if (numElements <= 0)
  3500. return BfIRValue();
  3501. BF_ASSERT(implTypeInst->mVirtualMethodTable[startVirtIdx].mDeclaringMethod.mMethodNum == -1);
  3502. BF_ASSERT(implTypeInst->mVirtualMethodTable[startVirtIdx].mDeclaringMethod.mTypeInstance == declTypeInst);
  3503. if (declTypeInst->mInheritDepth == implTypeInst->mInheritDepth)
  3504. BF_ASSERT(declTypeInst == implTypeInst);
  3505. else
  3506. BF_ASSERT(implTypeInst->mInheritDepth > declTypeInst->mInheritDepth);
  3507. if (declTypeInst != implTypeInst)
  3508. {
  3509. BfTypeInstance* highestImpl = declTypeInst;
  3510. for (int virtIdx = startVirtIdx + 1; virtIdx < (int)declTypeInst->mVirtualMethodTable.size(); virtIdx++)
  3511. {
  3512. if (implTypeInst->mVirtualMethodTable[virtIdx].mDeclaringMethod.mMethodNum == -1)
  3513. break; // Start of an ext entry for another type
  3514. auto checkImplTypeInst = implTypeInst->mVirtualMethodTable[virtIdx].mImplementingMethod.mTypeInstance;
  3515. if ((checkImplTypeInst != NULL) && (checkImplTypeInst->mInheritDepth > highestImpl->mInheritDepth))
  3516. highestImpl = checkImplTypeInst;
  3517. }
  3518. if (highestImpl != implTypeInst)
  3519. return CreateClassVDataExtGlobal(declTypeInst, highestImpl, startVirtIdx);
  3520. }
  3521. BfVDataExtEntry mapEntry;
  3522. mapEntry.mDeclTypeInst = declTypeInst;
  3523. mapEntry.mImplTypeInst = implTypeInst;
  3524. BfIRValue* irValuePtr = NULL;
  3525. if (mClassVDataExtRefs.TryGetValue(mapEntry, &irValuePtr))
  3526. return *irValuePtr;
  3527. PopulateType(declTypeInst, BfPopulateType_DataAndMethods);
  3528. PopulateType(implTypeInst, BfPopulateType_DataAndMethods);
  3529. StringT<128> classVDataName;
  3530. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), implTypeInst, "bf_hs_replace_VDataExt");
  3531. if (declTypeInst != implTypeInst)
  3532. {
  3533. classVDataName += StrFormat("_%d", implTypeInst->mInheritDepth - declTypeInst->mInheritDepth);
  3534. }
  3535. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  3536. auto voidPtrIRType = mBfIRBuilder->MapType(voidPtrType);
  3537. SizedArray<BfIRValue, 32> vData;
  3538. auto voidPtrNull = GetDefaultValue(voidPtrType);
  3539. for (int virtIdx = startVirtIdx + declTypeInst->GetOrigSelfVTableSize(); virtIdx < (int)declTypeInst->mVirtualMethodTable.size(); virtIdx++)
  3540. {
  3541. if (implTypeInst->mVirtualMethodTable[virtIdx].mDeclaringMethod.mMethodNum == -1)
  3542. break; // Start of an ext entry for another type
  3543. BfIRValue vValue;
  3544. auto& entry = implTypeInst->mVirtualMethodTable[virtIdx];
  3545. BfMethodInstance* declaringMethodInstance = (BfMethodInstance*)entry.mDeclaringMethod;
  3546. if ((declaringMethodInstance != NULL) && (declaringMethodInstance->mMethodInstanceGroup->IsImplemented()) && (declaringMethodInstance->mIsReified))
  3547. {
  3548. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].IsImplemented());
  3549. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].mDefault->mIsReified);
  3550. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  3551. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  3552. {
  3553. BF_ASSERT(implTypeInst->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject));
  3554. auto moduleMethodInst = GetMethodInstanceAtIdx(methodInstance->mMethodInstanceGroup->mOwner, methodInstance->mMethodInstanceGroup->mMethodIdx);
  3555. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  3556. vValue = funcPtr;
  3557. }
  3558. }
  3559. if (!vValue)
  3560. vValue = voidPtrNull;
  3561. vData.Add(vValue);
  3562. }
  3563. BF_ASSERT((int)vData.size() == numElements);
  3564. BfLogSysM("Creating VDataExt %s\n", classVDataName.c_str());
  3565. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), numElements);
  3566. auto globalVariable = mBfIRBuilder->CreateGlobalVariable(arrayType, true,
  3567. BfIRLinkageType_External, BfIRValue(), classVDataName);
  3568. BfIRType extVTableType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)vData.size());
  3569. BfIRValue extVTableConst = mBfIRBuilder->CreateConstArray(extVTableType, vData);
  3570. mBfIRBuilder->GlobalVar_SetInitializer(globalVariable, extVTableConst);
  3571. mClassVDataExtRefs[mapEntry] = globalVariable;
  3572. return globalVariable;
  3573. }
  3574. BfIRValue BfModule::CreateTypeDataRef(BfType* type)
  3575. {
  3576. if (mBfIRBuilder->mIgnoreWrites)
  3577. {
  3578. return mBfIRBuilder->CreateTypeOf(type);
  3579. }
  3580. BfIRValue globalVariable;
  3581. BfIRValue* globalVariablePtr = NULL;
  3582. if (mTypeDataRefs.TryGetValue(type, &globalVariablePtr))
  3583. {
  3584. globalVariable = *globalVariablePtr;
  3585. if (globalVariable)
  3586. return globalVariable;
  3587. }
  3588. auto typeTypeDef = ResolveTypeDef(mCompiler->mTypeTypeDef);
  3589. auto typeTypeInst = typeTypeDef->ToTypeInstance();
  3590. auto typeInstance = type->ToTypeInstance();
  3591. StringT<128> typeDataName;
  3592. if (typeInstance != NULL)
  3593. {
  3594. BfMangler::MangleStaticFieldName(typeDataName, mCompiler->GetMangleKind(), typeInstance, "sBfTypeData");
  3595. }
  3596. else
  3597. {
  3598. typeDataName += "sBfTypeData.";
  3599. BfMangler::Mangle(typeDataName, mCompiler->GetMangleKind(), type);
  3600. }
  3601. BfLogSysM("Creating TypeData %s\n", typeDataName.c_str());
  3602. globalVariable = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(typeTypeInst, BfIRPopulateType_Full), true, BfIRLinkageType_External, BfIRValue(), typeDataName);
  3603. mTypeDataRefs[type] = globalVariable;
  3604. return globalVariable;
  3605. }
  3606. BfIRValue BfModule::CreateTypeData(BfType* type, Dictionary<int, int>& usedStringIdMap, bool forceReflectFields, bool needsTypeData, bool needsTypeNames, bool needsVData)
  3607. {
  3608. if ((mCompiler->IsHotCompile()) && (!type->mDirty))
  3609. return BfIRValue();
  3610. BfIRValue* irValuePtr = NULL;
  3611. if (mTypeDataRefs.TryGetValue(type, &irValuePtr))
  3612. {
  3613. return *irValuePtr;
  3614. }
  3615. BfTypeInstance* typeInstance = type->ToTypeInstance();
  3616. BfType* typeInstanceType = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef);
  3617. mBfIRBuilder->PopulateType(typeInstanceType, BfIRPopulateType_Full_ForceDefinition);
  3618. if (typeInstanceType == NULL)
  3619. {
  3620. AssertErrorState();
  3621. return BfIRValue();
  3622. }
  3623. BfIRValue typeTypeData;
  3624. int typeFlags = 0;
  3625. if (needsTypeData)
  3626. {
  3627. BfTypeInstance* typeInstanceTypeInstance = typeInstanceType->ToTypeInstance();
  3628. BfTypeInstance* typeDataSource = NULL;
  3629. if (typeInstance != NULL)
  3630. {
  3631. if (typeInstance->IsUnspecializedType())
  3632. {
  3633. typeDataSource = ResolveTypeDef(mCompiler->mReflectUnspecializedGenericType)->ToTypeInstance();
  3634. typeFlags |= BfTypeFlags_UnspecializedGeneric;
  3635. }
  3636. else if (typeInstance->IsArray())
  3637. {
  3638. typeDataSource = ResolveTypeDef(mCompiler->mReflectArrayType)->ToTypeInstance();
  3639. typeFlags |= BfTypeFlags_Array;
  3640. }
  3641. else if (typeInstance->IsGenericTypeInstance())
  3642. {
  3643. typeDataSource = ResolveTypeDef(mCompiler->mReflectSpecializedGenericType)->ToTypeInstance();
  3644. typeFlags |= BfTypeFlags_SpecializedGeneric;
  3645. }
  3646. else
  3647. typeDataSource = typeInstanceTypeInstance;
  3648. }
  3649. else if (type->IsPointer())
  3650. typeDataSource = ResolveTypeDef(mCompiler->mReflectPointerType)->ToTypeInstance();
  3651. else if (type->IsSizedArray())
  3652. typeDataSource = ResolveTypeDef(mCompiler->mReflectSizedArrayType)->ToTypeInstance();
  3653. else
  3654. typeDataSource = mContext->mBfTypeType;
  3655. if ((!mTypeDataRefs.ContainsKey(typeDataSource)) && (typeDataSource != type))
  3656. {
  3657. CreateTypeData(typeDataSource, usedStringIdMap, false, true, needsTypeNames, true);
  3658. }
  3659. typeTypeData = CreateClassVDataGlobal(typeDataSource);
  3660. }
  3661. else
  3662. typeTypeData = CreateClassVDataGlobal(typeInstanceType->ToTypeInstance());
  3663. BfType* longType = GetPrimitiveType(BfTypeCode_Int64);
  3664. BfType* intType = GetPrimitiveType(BfTypeCode_Int32);
  3665. BfType* shortType = GetPrimitiveType(BfTypeCode_Int16);
  3666. BfType* byteType = GetPrimitiveType(BfTypeCode_Int8);
  3667. BfType* typeIdType = intType;
  3668. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  3669. auto voidPtrIRType = mBfIRBuilder->MapType(voidPtrType);
  3670. auto voidPtrPtrIRType = mBfIRBuilder->GetPointerTo(voidPtrIRType);
  3671. auto voidPtrNull = GetDefaultValue(voidPtrType);
  3672. SizedArray<BfIRValue, 4> typeValueParams;
  3673. GetConstClassValueParam(typeTypeData, typeValueParams);
  3674. BfIRValue objectData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(mContext->mBfObjectType, BfIRPopulateType_Full), typeValueParams);
  3675. StringT<128> typeDataName;
  3676. if ((typeInstance != NULL) && (!typeInstance->IsTypeAlias()))
  3677. {
  3678. BfMangler::MangleStaticFieldName(typeDataName, mCompiler->GetMangleKind(), typeInstance, "sBfTypeData");
  3679. if (typeInstance->mTypeDef->IsGlobalsContainer())
  3680. typeDataName += "`G`" + typeInstance->mTypeDef->mProject->mName;
  3681. }
  3682. else
  3683. {
  3684. typeDataName += "sBfTypeData.";
  3685. BfMangler::Mangle(typeDataName, mCompiler->GetMangleKind(), type, mContext->mScratchModule);
  3686. }
  3687. int typeCode = BfTypeCode_None;
  3688. if (typeInstance != NULL)
  3689. {
  3690. typeCode = typeInstance->mTypeDef->mTypeCode;
  3691. }
  3692. else if (type->IsPrimitiveType())
  3693. {
  3694. BfPrimitiveType* primType = (BfPrimitiveType*)type;
  3695. typeCode = primType->mTypeDef->mTypeCode;
  3696. }
  3697. else if (type->IsPointer())
  3698. {
  3699. typeCode = BfTypeCode_Pointer;
  3700. typeFlags |= BfTypeFlags_Pointer;
  3701. }
  3702. if (type->IsObject())
  3703. {
  3704. typeFlags |= BfTypeFlags_Object;
  3705. BfMethodInstance* methodInstance = typeInstance->mVirtualMethodTable[mCompiler->GetVTableMethodOffset() + 0].mImplementingMethod;
  3706. if (methodInstance->GetOwner() != mContext->mBfObjectType)
  3707. typeFlags |= BfTypeFlags_HasDestructor;
  3708. }
  3709. if (type->IsStruct())
  3710. typeFlags |= BfTypeFlags_Struct;
  3711. if (type->IsBoxed())
  3712. {
  3713. typeFlags |= BfTypeFlags_Boxed;
  3714. if (((BfBoxedType*)type)->IsBoxedStructPtr())
  3715. typeFlags |= BfTypeFlags_Pointer;
  3716. }
  3717. if (type->IsPrimitiveType())
  3718. typeFlags |= BfTypeFlags_Primitive;
  3719. if (type->IsTypedPrimitive())
  3720. typeFlags |= BfTypeFlags_TypedPrimitive;
  3721. if (type->IsTuple())
  3722. typeFlags |= BfTypeFlags_Tuple;
  3723. if (type->IsNullable())
  3724. typeFlags |= BfTypeFlags_Nullable;
  3725. if (type->IsSizedArray())
  3726. typeFlags |= BfTypeFlags_SizedArray;
  3727. if (type->IsSplattable())
  3728. typeFlags |= BfTypeFlags_Splattable;
  3729. if (type->IsUnion())
  3730. typeFlags |= BfTypeFlags_Union;
  3731. if (type->IsDelegate())
  3732. typeFlags |= BfTypeFlags_Delegate;
  3733. if (type->WantsGCMarking())
  3734. typeFlags |= BfTypeFlags_WantsMarking;
  3735. int memberDataOffset = 0;
  3736. if (typeInstance != NULL)
  3737. {
  3738. for (auto& fieldInstance : typeInstance->mFieldInstances)
  3739. {
  3740. if (fieldInstance.mDataOffset != -1)
  3741. {
  3742. memberDataOffset = fieldInstance.mDataOffset;
  3743. break;
  3744. }
  3745. }
  3746. }
  3747. SizedArray<BfIRValue, 8> typeDataParams =
  3748. {
  3749. objectData,
  3750. GetConstValue(type->mSize, intType), // mSize
  3751. GetConstValue(type->mTypeId, typeIdType), // mTypeId
  3752. GetConstValue(typeFlags, intType), // mTypeFlags
  3753. GetConstValue(memberDataOffset, intType), // mMemberDataOffset
  3754. GetConstValue(typeCode, byteType), // mTypeCode
  3755. GetConstValue(type->mAlign, byteType),
  3756. };
  3757. auto typeData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(mContext->mBfTypeType, BfIRPopulateType_Full), typeDataParams);
  3758. if (typeInstance == NULL)
  3759. {
  3760. BfIRValue typeDataVar;
  3761. if (needsTypeData)
  3762. {
  3763. if (type->IsPointer())
  3764. {
  3765. auto pointerType = (BfPointerType*)type;
  3766. SizedArray<BfIRValue, 3> pointerTypeDataParms =
  3767. {
  3768. typeData,
  3769. GetConstValue(pointerType->mElementType->mTypeId, typeIdType),
  3770. };
  3771. auto reflectPointerType = ResolveTypeDef(mCompiler->mReflectPointerType)->ToTypeInstance();
  3772. auto pointerTypeData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectPointerType, BfIRPopulateType_Full), pointerTypeDataParms);
  3773. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectPointerType), true,
  3774. BfIRLinkageType_External, pointerTypeData, typeDataName);
  3775. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  3776. }
  3777. else if (type->IsSizedArray())
  3778. {
  3779. auto sizedArrayType = (BfSizedArrayType*)type;
  3780. SizedArray<BfIRValue, 3> sizedArrayTypeDataParms =
  3781. {
  3782. typeData,
  3783. GetConstValue(sizedArrayType->mElementType->mTypeId, typeIdType),
  3784. GetConstValue(sizedArrayType->mElementCount, intType)
  3785. };
  3786. auto reflectSizedArrayType = ResolveTypeDef(mCompiler->mReflectSizedArrayType)->ToTypeInstance();
  3787. auto sizedArrayTypeData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectSizedArrayType, BfIRPopulateType_Full), sizedArrayTypeDataParms);
  3788. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(reflectSizedArrayType), true,
  3789. BfIRLinkageType_External, sizedArrayTypeData, typeDataName);
  3790. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  3791. }
  3792. else
  3793. {
  3794. typeDataVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapTypeInst(mContext->mBfTypeType), true,
  3795. BfIRLinkageType_External, typeData, typeDataName);
  3796. }
  3797. }
  3798. else
  3799. typeDataVar = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(mContext->mBfTypeType));
  3800. mTypeDataRefs[typeInstance] = typeDataVar;
  3801. return typeDataVar;
  3802. }
  3803. // Reserve position
  3804. mTypeDataRefs[typeInstance] = BfIRValue();
  3805. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  3806. BfTypeDef* typeDef = typeInstance->mTypeDef;
  3807. StringT<128> mangledName;
  3808. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), typeInstance, typeInstance->mModule);
  3809. for (int methodIdx = 0; methodIdx < (int)typeDef->mMethods.size(); methodIdx++)
  3810. {
  3811. auto methodDef = typeDef->mMethods[methodIdx];
  3812. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  3813. if (methodInstance == NULL)
  3814. continue;
  3815. if (typeInstance->IsUnspecializedType())
  3816. continue;
  3817. if (!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, mProject))
  3818. {
  3819. if (methodInstance->mChainType == BfMethodChainType_ChainMember)
  3820. {
  3821. BF_ASSERT(!methodInstance->GetOwner()->IsUnspecializedType());
  3822. // We need to create an empty thunk for this chained method
  3823. BfIRFunction func = CreateFunctionFrom(methodInstance, false, methodInstance->mAlwaysInline);
  3824. mBfIRBuilder->SetActiveFunction(func);
  3825. auto block = mBfIRBuilder->CreateBlock("entry", true);
  3826. mBfIRBuilder->SetInsertPoint(block);
  3827. mBfIRBuilder->CreateRetVoid();
  3828. mBfIRBuilder->SetActiveFunction(BfIRFunction());
  3829. }
  3830. }
  3831. }
  3832. SizedArray<BfIRValue, 32> vData;
  3833. BfIRValue classVDataVar;
  3834. String classVDataName;
  3835. if (typeInstance->mSlotNum >= 0)
  3836. {
  3837. // For interfaces we ONLY emit the slot num
  3838. int virtSlotIdx = typeInstance->mSlotNum + 1 + mCompiler->GetDynCastVDataCount();
  3839. StringT<128> slotVarName;
  3840. BfMangler::MangleStaticFieldName(slotVarName, mCompiler->GetMangleKind(), typeInstance, "sBfSlotOfs");
  3841. auto intType = GetPrimitiveType(BfTypeCode_Int32);
  3842. auto slotNumVar = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(intType), true, BfIRLinkageType_External,
  3843. GetConstValue32(virtSlotIdx), slotVarName);
  3844. }
  3845. else if ((typeInstance->IsObject()) && (!typeInstance->IsUnspecializedType()) && (needsVData))
  3846. {
  3847. int dynCastDataElems = 0;
  3848. int numElements = 1;
  3849. int vDataOfs = 1; // The number of intptrs before the iface slot map
  3850. numElements += mCompiler->mMaxInterfaceSlots;
  3851. if (!typeInstance->IsInterface())
  3852. {
  3853. dynCastDataElems = 1 + mCompiler->mMaxInterfaceSlots;
  3854. numElements += mCompiler->GetDynCastVDataCount();
  3855. numElements += typeInstance->mVirtualMethodTableSize;
  3856. }
  3857. int expectNumElements = 0;
  3858. if (!typeDef->mIsStatic)
  3859. {
  3860. classVDataVar = CreateClassVDataGlobal(typeInstance, &expectNumElements, &classVDataName);
  3861. }
  3862. vData.push_back(BfIRValue()); // Type*
  3863. SizedArray<BfIRValue, 1> extVTableData;
  3864. SizedArrayImpl<BfIRValue>* vFuncDataExt = &extVTableData;
  3865. if (!typeInstance->IsInterface())
  3866. {
  3867. Array<int32> dynCastData;
  3868. if (typeInstance->IsBoxed())
  3869. {
  3870. auto underlyingType = typeInstance->GetUnderlyingType()->ToTypeInstance();
  3871. dynCastData.Add(underlyingType->mInheritanceId);
  3872. }
  3873. else
  3874. dynCastData.Add(typeInstance->mInheritanceId);
  3875. for (int i = 0; i < mCompiler->mMaxInterfaceSlots; i++)
  3876. dynCastData.Add(0);
  3877. dynCastData.Add(0);
  3878. auto checkTypeInst = typeInstance;
  3879. while (checkTypeInst != NULL)
  3880. {
  3881. for (auto&& interfaceEntry : checkTypeInst->mInterfaces)
  3882. {
  3883. if (interfaceEntry.mInterfaceType->mSlotNum >= 0)
  3884. {
  3885. if (dynCastData[interfaceEntry.mInterfaceType->mSlotNum + 1] == 0)
  3886. dynCastData[interfaceEntry.mInterfaceType->mSlotNum + 1] = interfaceEntry.mInterfaceType->mTypeId;
  3887. }
  3888. }
  3889. checkTypeInst = checkTypeInst->GetImplBaseType();
  3890. }
  3891. if (mSystem->mPtrSize == 8)
  3892. {
  3893. int intPtrCount = (dynCastDataElems + 1) / 2;
  3894. vDataOfs += intPtrCount;
  3895. uint64* intPtrData = (uint64*)&dynCastData[0];
  3896. for (int i = 0; i < intPtrCount; i++)
  3897. {
  3898. uint64 val = intPtrData[i];
  3899. if (val == 0)
  3900. {
  3901. vData.push_back(voidPtrNull);
  3902. }
  3903. else
  3904. {
  3905. auto intPtrVal = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, val);
  3906. vData.push_back(mBfIRBuilder->CreateBitCast(intPtrVal, voidPtrIRType));
  3907. }
  3908. }
  3909. }
  3910. else
  3911. {
  3912. int intPtrCount = dynCastDataElems;
  3913. vDataOfs += intPtrCount;
  3914. uint32* intPtrData = (uint32*)&dynCastData[0];
  3915. for (int i = 0; i < intPtrCount; i++)
  3916. {
  3917. uint32 val = intPtrData[i];
  3918. if (val == 0)
  3919. {
  3920. vData.push_back(voidPtrNull);
  3921. }
  3922. else
  3923. {
  3924. auto intPtrVal = mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (int)val);
  3925. vData.push_back(mBfIRBuilder->CreateBitCast(intPtrVal, voidPtrIRType));
  3926. }
  3927. }
  3928. }
  3929. }
  3930. for (int iSlotIdx = 0; iSlotIdx < mCompiler->mMaxInterfaceSlots; iSlotIdx++)
  3931. vData.push_back(voidPtrNull);
  3932. struct _InterfaceMatchEntry
  3933. {
  3934. BfTypeInterfaceEntry* mEntry;
  3935. BfTypeInstance* mEntrySource;
  3936. Array<BfTypeInterfaceEntry*> mAmbiguousEntries;
  3937. };
  3938. int highestIFaceVirtIdx = 0;
  3939. Dictionary<BfTypeInstance*, _InterfaceMatchEntry> interfaceMap;
  3940. auto checkTypeInst = typeInstance;
  3941. bool forceInterfaceSet = false;
  3942. while (checkTypeInst != NULL)
  3943. {
  3944. for (auto&& interfaceEntry : checkTypeInst->mInterfaces)
  3945. {
  3946. highestIFaceVirtIdx = BF_MAX(highestIFaceVirtIdx, interfaceEntry.mStartVirtualIdx + interfaceEntry.mInterfaceType->mVirtualMethodTableSize);
  3947. if (!typeInstance->IsTypeMemberAccessible(interfaceEntry.mDeclaringType, mProject))
  3948. continue;
  3949. _InterfaceMatchEntry* matchEntry = NULL;
  3950. if (interfaceMap.TryGetValue(interfaceEntry.mInterfaceType, &matchEntry))
  3951. {
  3952. auto prevEntry = matchEntry->mEntry;
  3953. bool isBetter = TypeIsSubTypeOf(checkTypeInst, matchEntry->mEntrySource);
  3954. bool isWorse = TypeIsSubTypeOf(matchEntry->mEntrySource, checkTypeInst);
  3955. if (forceInterfaceSet)
  3956. {
  3957. isBetter = true;
  3958. isWorse = false;
  3959. }
  3960. if (isBetter == isWorse)
  3961. CompareDeclTypes(interfaceEntry.mDeclaringType, prevEntry->mDeclaringType, isBetter, isWorse);
  3962. if (isBetter == isWorse)
  3963. {
  3964. if (matchEntry->mAmbiguousEntries.empty())
  3965. matchEntry->mAmbiguousEntries.push_back(prevEntry);
  3966. matchEntry->mAmbiguousEntries.push_back(&interfaceEntry);
  3967. continue;
  3968. }
  3969. else if (isBetter)
  3970. {
  3971. matchEntry->mEntry = &interfaceEntry;
  3972. matchEntry->mEntrySource = checkTypeInst;
  3973. matchEntry->mAmbiguousEntries.Clear();
  3974. }
  3975. else
  3976. continue;
  3977. }
  3978. else
  3979. {
  3980. _InterfaceMatchEntry matchEntry;
  3981. matchEntry.mEntry = &interfaceEntry;
  3982. matchEntry.mEntrySource = checkTypeInst;
  3983. interfaceMap[interfaceEntry.mInterfaceType] = matchEntry;
  3984. }
  3985. }
  3986. checkTypeInst = checkTypeInst->GetImplBaseType();
  3987. }
  3988. for (auto interfacePair : interfaceMap)
  3989. {
  3990. auto& interfaceMatchEntry = interfacePair.mValue;
  3991. if (!interfaceMatchEntry.mAmbiguousEntries.empty())
  3992. {
  3993. 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());
  3994. if (error != NULL)
  3995. {
  3996. for (auto ambiguiousEntry : interfaceMatchEntry.mAmbiguousEntries)
  3997. mCompiler->mPassInstance->MoreInfo("See other declaration", ambiguiousEntry->mDeclaringType->GetRefNode());
  3998. }
  3999. }
  4000. }
  4001. if ((!typeInstance->IsInterface()) && (typeInstance->mVirtualMethodTableSize > 0) && (needsVData))
  4002. {
  4003. int startTabIdx = (int)vData.size();
  4004. SizedArray<BfTypeInstance*, 8> origVirtTypeStack;
  4005. BfTypeInstance* checkTypeInst = typeInstance;
  4006. while (checkTypeInst != NULL)
  4007. {
  4008. origVirtTypeStack.push_back(checkTypeInst);
  4009. checkTypeInst = checkTypeInst->GetImplBaseType();
  4010. }
  4011. Array<BfVirtualMethodEntry> origVTable;
  4012. int origVirtIdx = 0;
  4013. if (typeInstance->mTypeDef->mIsCombinedPartial)
  4014. {
  4015. HashSet<String> reslotNames;
  4016. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  4017. {
  4018. auto& entry = typeInstance->mVirtualMethodTable[virtIdx];
  4019. if (entry.mDeclaringMethod.mMethodNum == -1)
  4020. continue;
  4021. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  4022. if ((methodInstance == NULL) || (!typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject)))
  4023. {
  4024. if (origVTable.empty())
  4025. origVTable = typeInstance->mVirtualMethodTable;
  4026. BfMethodInstance* declMethodInstance = entry.mDeclaringMethod;
  4027. if (typeInstance->IsTypeMemberAccessible(declMethodInstance->mMethodDef->mDeclaringType, mProject))
  4028. {
  4029. // Prepare to reslot...
  4030. entry.mImplementingMethod = entry.mDeclaringMethod;
  4031. reslotNames.Add(declMethodInstance->mMethodDef->mName);
  4032. }
  4033. else
  4034. {
  4035. // Decl isn't accessible, null out entry
  4036. entry.mImplementingMethod = BfMethodRef();
  4037. }
  4038. }
  4039. }
  4040. if (!reslotNames.IsEmpty())
  4041. {
  4042. BfAmbiguityContext ambiguityContext;
  4043. ambiguityContext.mTypeInstance = typeInstance;
  4044. ambiguityContext.mModule = this;
  4045. ambiguityContext.mIsProjectSpecific = true;
  4046. ambiguityContext.mIsReslotting = true;
  4047. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  4048. for (auto& methodGroup : typeInstance->mMethodInstanceGroups)
  4049. {
  4050. auto methodInstance = methodGroup.mDefault;
  4051. if ((methodInstance == NULL) || (!methodInstance->mMethodDef->mIsOverride))
  4052. continue;
  4053. if (!reslotNames.Contains(methodInstance->mMethodDef->mName))
  4054. continue;
  4055. if (!typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject))
  4056. continue;
  4057. if ((methodInstance->mChainType != BfMethodChainType_None) && (methodInstance->mChainType != BfMethodChainType_ChainHead))
  4058. continue;
  4059. SlotVirtualMethod(methodInstance, &ambiguityContext);
  4060. }
  4061. ambiguityContext.Finish();
  4062. }
  4063. }
  4064. bool isInExts = false;
  4065. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  4066. {
  4067. BfIRValue vValue = voidPtrNull;
  4068. auto& entry = typeInstance->mVirtualMethodTable[virtIdx];
  4069. BfModuleMethodInstance moduleMethodInst;
  4070. if (entry.mDeclaringMethod.mMethodNum == -1)
  4071. {
  4072. // mMethodNum of -1 indicates a vExt slot rather than an actual method reference
  4073. isInExts = true;
  4074. BfIRValue vExt = CreateClassVDataExtGlobal(entry.mDeclaringMethod.mTypeInstance, typeInstance, virtIdx);
  4075. if (vExt)
  4076. vValue = mBfIRBuilder->CreateBitCast(vExt, voidPtrIRType);
  4077. }
  4078. else
  4079. {
  4080. BfMethodInstance* declaringMethodInstance = (BfMethodInstance*)entry.mDeclaringMethod;
  4081. if ((declaringMethodInstance != NULL) && (declaringMethodInstance->mMethodInstanceGroup->IsImplemented()) && (declaringMethodInstance->mIsReified))
  4082. {
  4083. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].IsImplemented());
  4084. BF_ASSERT(entry.mImplementingMethod.mTypeInstance->mMethodInstanceGroups[entry.mImplementingMethod.mMethodNum].mDefault->mIsReified);
  4085. BfMethodInstance* methodInstance = (BfMethodInstance*)entry.mImplementingMethod;
  4086. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  4087. {
  4088. BF_ASSERT(typeInstance->IsTypeMemberAccessible(methodInstance->mMethodDef->mDeclaringType, mProject));
  4089. moduleMethodInst = GetMethodInstanceAtIdx(methodInstance->mMethodInstanceGroup->mOwner, methodInstance->mMethodInstanceGroup->mMethodIdx);
  4090. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  4091. vValue = funcPtr;
  4092. }
  4093. }
  4094. }
  4095. while (origVirtTypeStack.size() != 0)
  4096. {
  4097. BfTypeInstance* useTypeInst = origVirtTypeStack[origVirtTypeStack.size() - 1];
  4098. if (virtIdx >= useTypeInst->mVirtualMethodTableSize)
  4099. {
  4100. // Moved past current base vtable size
  4101. origVirtTypeStack.pop_back();
  4102. continue;
  4103. }
  4104. if (origVirtIdx < useTypeInst->GetOrigVTableSize())
  4105. {
  4106. // We are within the original vtable size
  4107. int idx = startTabIdx + origVirtIdx;
  4108. origVirtIdx++;
  4109. vData.push_back(vValue);
  4110. }
  4111. else
  4112. {
  4113. // This is a new entry, it only gets added to the ext
  4114. BF_ASSERT(isInExts);
  4115. }
  4116. break;
  4117. }
  4118. }
  4119. if (!origVTable.empty())
  4120. typeInstance->mVirtualMethodTable = origVTable;
  4121. }
  4122. int ifaceMethodExtStart = (int)typeInstance->GetIFaceVMethodSize();
  4123. if (typeInstance->mHotTypeData != NULL)
  4124. {
  4125. if (typeInstance->mHotTypeData->mOrigInterfaceMethodsLength != -1)
  4126. ifaceMethodExtStart = typeInstance->mHotTypeData->mOrigInterfaceMethodsLength;
  4127. }
  4128. SizedArray<BfIRValue, 32> ifaceMethodExtData;
  4129. int iFaceMethodStartIdx = (int)vData.size();
  4130. vData.resize(iFaceMethodStartIdx + ifaceMethodExtStart);
  4131. for (int i = iFaceMethodStartIdx; i < iFaceMethodStartIdx + ifaceMethodExtStart; i++)
  4132. vData[i] = voidPtrNull;
  4133. if (expectNumElements != 0)
  4134. BF_ASSERT(expectNumElements == vData.size());
  4135. //BF_ASSERT(vData.size() == expectNumElements);
  4136. // for (int i = 0; i < (int)typeInstance->mInterfaceMethodTable.size() - ifaceMethodExtStart; i++)
  4137. // ifaceMethodExtData.Add(voidPtrNull);
  4138. int ifaceEntryIdx = iFaceMethodStartIdx;
  4139. for (auto& interfacePair : interfaceMap)
  4140. {
  4141. auto interfaceEntry = interfacePair.mValue.mEntry;
  4142. bool makeEmpty = false;
  4143. if (!typeInstance->IsTypeMemberAccessible(interfaceEntry->mDeclaringType, mProject))
  4144. makeEmpty = true;
  4145. int endVirtualIdx = interfaceEntry->mStartVirtualIdx + interfaceEntry->mInterfaceType->mVirtualMethodTableSize;
  4146. bool useExt = endVirtualIdx > ifaceMethodExtStart;
  4147. for (int methodIdx = 0; methodIdx < (int)interfaceEntry->mInterfaceType->mMethodInstanceGroups.size(); methodIdx++)
  4148. {
  4149. BfIRValue pushValue;
  4150. BfMethodInstance* ifaceMethodInstance = interfaceEntry->mInterfaceType->mMethodInstanceGroups[methodIdx].mDefault;
  4151. if ((ifaceMethodInstance == NULL) || (ifaceMethodInstance->mVirtualTableIdx == -1))
  4152. continue;
  4153. if ((!ifaceMethodInstance->mIsReified) || (!ifaceMethodInstance->mMethodInstanceGroup->IsImplemented()))
  4154. continue;
  4155. if (makeEmpty)
  4156. {
  4157. pushValue = voidPtrNull;
  4158. }
  4159. else
  4160. {
  4161. auto& methodRef = typeInstance->mInterfaceMethodTable[interfaceEntry->mStartInterfaceTableIdx + methodIdx].mMethodRef;
  4162. auto methodInstance = (BfMethodInstance*)methodRef;
  4163. if ((methodInstance != NULL) && (!methodInstance->mMethodDef->mIsAbstract))
  4164. {
  4165. BF_ASSERT(methodInstance->mIsReified);
  4166. // This doesn't work because we may have FOREIGN methods from implicit interface methods
  4167. //auto moduleMethodInst = GetMethodInstanceAtIdx(methodRef.mTypeInstance, methodRef.mMethodNum);
  4168. auto moduleMethodInst = ReferenceExternalMethodInstance(methodInstance);
  4169. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  4170. pushValue = funcPtr;
  4171. }
  4172. else
  4173. {
  4174. pushValue = voidPtrNull;
  4175. }
  4176. }
  4177. int idx = interfaceEntry->mStartVirtualIdx + ifaceMethodInstance->mVirtualTableIdx;
  4178. if (idx < ifaceMethodExtStart)
  4179. {
  4180. BF_ASSERT(iFaceMethodStartIdx + idx < (int)vData.size());
  4181. vData[iFaceMethodStartIdx + idx] = pushValue;
  4182. }
  4183. else
  4184. {
  4185. BF_ASSERT(useExt);
  4186. int extIdx = idx - ifaceMethodExtStart;
  4187. while (extIdx >= ifaceMethodExtData.size())
  4188. ifaceMethodExtData.Add(voidPtrNull);
  4189. ifaceMethodExtData[extIdx] = pushValue;
  4190. }
  4191. }
  4192. }
  4193. if (typeInstance->IsBoxed())
  4194. {
  4195. BfBoxedType* boxedType = (BfBoxedType*)typeInstance;
  4196. if (boxedType->IsBoxedStructPtr())
  4197. {
  4198. // Force override of GetHashCode so we use the pointer address as the hash code
  4199. checkTypeInst = CreateBoxedType(ResolveTypeDef(mCompiler->mPointerTypeDef));
  4200. // Force override of GetHashCode so we use the pointer address as the hash code
  4201. for (auto& checkIFace : checkTypeInst->mInterfaces)
  4202. {
  4203. for (int methodIdx = 0; methodIdx < (int)checkIFace.mInterfaceType->mMethodInstanceGroups.size(); methodIdx++)
  4204. {
  4205. BfIRValue pushValue;
  4206. BfMethodInstance* ifaceMethodInstance = checkIFace.mInterfaceType->mMethodInstanceGroups[methodIdx].mDefault;
  4207. if ((ifaceMethodInstance == NULL) || (ifaceMethodInstance->mVirtualTableIdx == -1))
  4208. continue;
  4209. if ((!ifaceMethodInstance->mIsReified) || (!ifaceMethodInstance->mMethodInstanceGroup->IsImplemented()))
  4210. continue;
  4211. auto& methodRef = checkTypeInst->mInterfaceMethodTable[checkIFace.mStartInterfaceTableIdx + methodIdx].mMethodRef;
  4212. auto methodInstance = (BfMethodInstance*)methodRef;
  4213. BF_ASSERT(methodInstance->mIsReified);
  4214. // This doesn't work because we may have FOREIGN methods from implicit interface methods
  4215. //auto moduleMethodInst = GetMethodInstanceAtIdx(methodRef.mTypeInstance, methodRef.mMethodNum);
  4216. auto moduleMethodInst = ReferenceExternalMethodInstance(methodInstance);
  4217. auto funcPtr = mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, voidPtrIRType);
  4218. int idx = checkIFace.mStartVirtualIdx + ifaceMethodInstance->mVirtualTableIdx;
  4219. vData[iFaceMethodStartIdx + idx] = funcPtr;
  4220. }
  4221. }
  4222. }
  4223. }
  4224. if ((needsVData) && (!typeInstance->mTypeDef->mIsStatic))
  4225. {
  4226. BfIRValue ifaceMethodExtVar;
  4227. if (!ifaceMethodExtData.IsEmpty())
  4228. {
  4229. StringT<128> classVDataName;
  4230. BfMangler::MangleStaticFieldName(classVDataName, mCompiler->GetMangleKind(), typeInstance, "bf_hs_replace_IFaceExt");
  4231. auto arrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr), (int)ifaceMethodExtData.size());
  4232. ifaceMethodExtVar = mBfIRBuilder->CreateGlobalVariable(arrayType, true,
  4233. BfIRLinkageType_External, BfIRValue(), classVDataName);
  4234. BfIRType extVTableType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)ifaceMethodExtData.size());
  4235. BfIRValue extVTableConst = mBfIRBuilder->CreateConstArray(extVTableType, ifaceMethodExtData);
  4236. mBfIRBuilder->GlobalVar_SetInitializer(ifaceMethodExtVar, extVTableConst);
  4237. }
  4238. for (auto& ifaceInstPair : interfaceMap)
  4239. {
  4240. auto interfaceEntry = ifaceInstPair.mValue.mEntry;
  4241. int slotNum = interfaceEntry->mInterfaceType->mSlotNum;
  4242. if (slotNum >= 0)
  4243. {
  4244. BfIRValue vtablePtr;
  4245. int idx = interfaceEntry->mStartVirtualIdx;
  4246. int endVirtualIdx = interfaceEntry->mStartVirtualIdx + interfaceEntry->mInterfaceType->mVirtualMethodTableSize;
  4247. if (endVirtualIdx > ifaceMethodExtStart)
  4248. vtablePtr = mBfIRBuilder->CreateInBoundsGEP(ifaceMethodExtVar, 0, interfaceEntry->mStartVirtualIdx - ifaceMethodExtStart);
  4249. else
  4250. vtablePtr = mBfIRBuilder->CreateInBoundsGEP(classVDataVar, 0, iFaceMethodStartIdx + interfaceEntry->mStartVirtualIdx);
  4251. int slotVirtIdx = slotNum + vDataOfs;
  4252. if (vData[slotVirtIdx] == voidPtrNull)
  4253. {
  4254. vData[slotVirtIdx] = mBfIRBuilder->CreateBitCast(vtablePtr, voidPtrIRType);
  4255. }
  4256. else
  4257. {
  4258. if (mCompiler->IsHotCompile())
  4259. Fail("Interface slot collision error. Restart program or undo interface changes.", typeDef->GetRefNode());
  4260. else
  4261. Fail("Interface slot collision error", typeDef->GetRefNode());
  4262. }
  4263. }
  4264. }
  4265. }
  4266. }
  4267. BfIRValue typeNameConst;
  4268. BfIRValue namespaceConst;
  4269. if (needsTypeNames)
  4270. {
  4271. typeNameConst = GetStringObjectValue(typeDef->mName->mString, true);
  4272. namespaceConst = GetStringObjectValue(typeDef->mNamespace.ToString(), true);
  4273. }
  4274. else
  4275. {
  4276. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  4277. typeNameConst = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(stringType));
  4278. namespaceConst = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(stringType));
  4279. }
  4280. int baseTypeId = 0;
  4281. if (typeInstance->mBaseType != NULL)
  4282. {
  4283. baseTypeId = typeInstance->mBaseType->mTypeId;
  4284. }
  4285. SizedArray<BfIRValue, 16> customAttrs;
  4286. BfTypeInstance* attributeType = mContext->mUnreifiedModule->ResolveTypeDef(mCompiler->mAttributeTypeDef)->ToTypeInstance();
  4287. BfIRValue castedClassVData;
  4288. if (classVDataVar)
  4289. castedClassVData = mBfIRBuilder->CreateBitCast(classVDataVar, mBfIRBuilder->MapType(mContext->mBfClassVDataPtrType));
  4290. else
  4291. castedClassVData = GetDefaultValue(mContext->mBfClassVDataPtrType);
  4292. bool freflectIncludeTypeData = false;
  4293. bool reflectIncludeAllFields = false;
  4294. bool reflectIncludeAllMethods = false;
  4295. if (TypeIsSubTypeOf(typeInstance, attributeType))
  4296. {
  4297. reflectIncludeAllFields = true;
  4298. reflectIncludeAllMethods = true;
  4299. }
  4300. enum ReflectKind
  4301. {
  4302. ReflectKind_None = 0,
  4303. ReflectKind_Type = 1,
  4304. ReflectKind_NonStaticFields = 2,
  4305. ReflectKind_StaticFields = 4,
  4306. ReflectKind_DefaultConstructor = 8,
  4307. ReflectKind_Constructors = 0x10,
  4308. ReflectKind_StaticMethods = 0x20,
  4309. ReflectKind_Methods = 0x40,
  4310. ReflectKind_User = 0x80,
  4311. ReflectKind_All = 0x7F,
  4312. ReflectKind_ApplyToInnerTypes = 0x80
  4313. };
  4314. ReflectKind reflectKind = ReflectKind_Type;
  4315. auto _GetReflectUser = [&](BfTypeInstance* attrType)
  4316. {
  4317. ReflectKind reflectKind = ReflectKind_None;
  4318. if (attrType->mCustomAttributes != NULL)
  4319. {
  4320. for (auto& customAttr : attrType->mCustomAttributes->mAttributes)
  4321. {
  4322. if (customAttr.mType->mTypeDef->mName->ToString() == "AttributeUsageAttribute")
  4323. {
  4324. for (auto& prop : customAttr.mSetProperties)
  4325. {
  4326. auto propDef = prop.mPropertyRef.mTypeInstance->mTypeDef->mProperties[prop.mPropertyRef.mPropIdx];
  4327. if (propDef->mName == "ReflectUser")
  4328. {
  4329. if (prop.mParam.mValue.IsConst())
  4330. {
  4331. auto constant = attrType->mConstHolder->GetConstant(prop.mParam.mValue);
  4332. reflectKind = (ReflectKind)(reflectKind | (ReflectKind)constant->mInt32);
  4333. }
  4334. }
  4335. }
  4336. // Check for Flags arg
  4337. if (customAttr.mCtorArgs.size() < 2)
  4338. continue;
  4339. auto constant = attrType->mConstHolder->GetConstant(customAttr.mCtorArgs[1]);
  4340. if (constant == NULL)
  4341. continue;
  4342. if (constant->mTypeCode == BfTypeCode_Boolean)
  4343. continue;
  4344. if ((constant->mInt8 & BfCustomAttributeFlags_ReflectAttribute) != 0)
  4345. reflectKind = (ReflectKind)(reflectKind | ReflectKind_User);
  4346. }
  4347. }
  4348. }
  4349. return reflectKind;
  4350. };
  4351. auto _GetReflectUserFromDirective = [&](BfAttributeDirective* attributesDirective, BfAttributeTargets attrTarget)
  4352. {
  4353. ReflectKind reflectKind = ReflectKind_None;
  4354. auto customAttrs = GetCustomAttributes(attributesDirective, attrTarget);
  4355. if (customAttrs != NULL)
  4356. {
  4357. for (auto& attr : customAttrs->mAttributes)
  4358. {
  4359. reflectKind = (ReflectKind)(reflectKind | _GetReflectUser(attr.mType));
  4360. }
  4361. }
  4362. return reflectKind;
  4363. };
  4364. //
  4365. {
  4366. auto checkTypeInstance = typeInstance;
  4367. while (checkTypeInstance != NULL)
  4368. {
  4369. if (checkTypeInstance->mCustomAttributes != NULL)
  4370. {
  4371. auto checkReflectKind = ReflectKind_None;
  4372. for (auto& customAttr : checkTypeInstance->mCustomAttributes->mAttributes)
  4373. {
  4374. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  4375. {
  4376. if (customAttr.mCtorArgs.size() > 0)
  4377. {
  4378. auto constant = checkTypeInstance->mConstHolder->GetConstant(customAttr.mCtorArgs[0]);
  4379. checkReflectKind = (ReflectKind)((int)checkReflectKind | constant->mInt32);
  4380. }
  4381. else
  4382. {
  4383. checkReflectKind = ReflectKind_All;
  4384. }
  4385. }
  4386. else
  4387. {
  4388. auto userReflectKind = _GetReflectUser(customAttr.mType);
  4389. checkReflectKind = (ReflectKind)(checkReflectKind | userReflectKind);
  4390. }
  4391. }
  4392. if ((checkTypeInstance == typeInstance) ||
  4393. ((checkReflectKind & ReflectKind_ApplyToInnerTypes) != 0))
  4394. {
  4395. reflectKind = (ReflectKind)(reflectKind | checkReflectKind);
  4396. }
  4397. }
  4398. checkTypeInstance = GetOuterType(checkTypeInstance);
  4399. }
  4400. }
  4401. // Fields
  4402. BfType* reflectFieldDataType = ResolveTypeDef(mCompiler->mReflectFieldDataDef);
  4403. BfIRValue emptyValueType = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance()->mBaseType), SizedArray<BfIRValue, 1>());
  4404. auto _HandleCustomAttrs = [&](BfCustomAttributes* customAttributes)
  4405. {
  4406. if (customAttributes == NULL)
  4407. return -1;
  4408. Array<BfCustomAttribute*> reflectAttributes;
  4409. for (auto& attr : customAttributes->mAttributes)
  4410. {
  4411. bool wantAttribute = false;
  4412. if (attr.mType->mCustomAttributes != NULL)
  4413. {
  4414. auto usageAttribute = attr.mType->mCustomAttributes->Get(mCompiler->mAttributeUsageAttributeTypeDef);
  4415. if (usageAttribute != NULL)
  4416. {
  4417. // Check for Flags arg
  4418. if (usageAttribute->mCtorArgs.size() < 2)
  4419. continue;
  4420. auto constant = attr.mType->mConstHolder->GetConstant(usageAttribute->mCtorArgs[1]);
  4421. if (constant == NULL)
  4422. continue;
  4423. if (constant->mTypeCode == BfTypeCode_Boolean)
  4424. continue;
  4425. if ((constant->mInt8 & BfCustomAttributeFlags_ReflectAttribute) != 0)
  4426. wantAttribute = true;
  4427. }
  4428. }
  4429. if ((wantAttribute) && (attr.mType->mIsReified))
  4430. {
  4431. reflectAttributes.Add(&attr);
  4432. }
  4433. }
  4434. if (reflectAttributes.size() == 0)
  4435. return -1;
  4436. #define PUSH_INT8(val) data.push_back((uint8)val)
  4437. #define PUSH_INT16(val) { data.push_back(val & 0xFF); data.push_back((val >> 8) & 0xFF); }
  4438. #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); }
  4439. #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); \
  4440. data.push_back((val >> 32) & 0xFF); data.push_back((val >> 40) & 0xFF); data.push_back((val >> 48) & 0xFF); data.push_back((val >> 56) & 0xFF); }
  4441. SizedArray<uint8, 16> data;
  4442. int customAttrIdx = (int)customAttrs.size();
  4443. data.push_back((uint8)reflectAttributes.size());
  4444. for (auto attr : reflectAttributes)
  4445. {
  4446. // Size prefix
  4447. int sizeIdx = (int)data.size();
  4448. PUSH_INT16(0); // mSize
  4449. PUSH_INT32(attr->mType->mTypeId); // mType
  4450. PUSH_INT16(attr->mCtor->mIdx);
  4451. auto ctorMethodInstance = GetRawMethodInstanceAtIdx(attr->mType, attr->mCtor->mIdx);
  4452. int argIdx = 0;
  4453. for (auto arg : attr->mCtorArgs)
  4454. {
  4455. auto constant = typeInstance->mConstHolder->GetConstant(arg);
  4456. bool handled = false;
  4457. if (constant != NULL)
  4458. {
  4459. auto argType = ctorMethodInstance->GetParamType(argIdx);
  4460. if (argType->IsObject())
  4461. {
  4462. BF_ASSERT(argType->ToTypeInstance()->mTypeDef == mCompiler->mStringTypeDef);
  4463. int stringId = constant->mInt32;
  4464. int* orderedIdPtr;
  4465. if (usedStringIdMap.TryAdd(stringId, NULL, &orderedIdPtr))
  4466. {
  4467. *orderedIdPtr = (int)usedStringIdMap.size() - 1;
  4468. }
  4469. GetStringObjectValue(stringId);
  4470. PUSH_INT8(0xFF); // String
  4471. PUSH_INT32(*orderedIdPtr);
  4472. continue;
  4473. }
  4474. PUSH_INT8(constant->mTypeCode);
  4475. if ((constant->mTypeCode == BfTypeCode_Int64) ||
  4476. (constant->mTypeCode == BfTypeCode_UInt64) ||
  4477. (constant->mTypeCode == BfTypeCode_Double))
  4478. {
  4479. PUSH_INT64(constant->mInt64);
  4480. }
  4481. else if ((constant->mTypeCode == BfTypeCode_Int32) ||
  4482. (constant->mTypeCode == BfTypeCode_UInt32))
  4483. {
  4484. PUSH_INT32(constant->mInt32);
  4485. }
  4486. else if (constant->mTypeCode == BfTypeCode_Single)
  4487. {
  4488. float val = (float)constant->mDouble;
  4489. PUSH_INT32(*(int*)&val);
  4490. }
  4491. else if ((constant->mTypeCode == BfTypeCode_Int16) ||
  4492. (constant->mTypeCode == BfTypeCode_UInt16))
  4493. {
  4494. PUSH_INT16(constant->mInt16);
  4495. }
  4496. else if ((constant->mTypeCode == BfTypeCode_Int8) ||
  4497. (constant->mTypeCode == BfTypeCode_UInt8))
  4498. {
  4499. PUSH_INT8(constant->mInt8);
  4500. }
  4501. else if (constant->mTypeCode == BfTypeCode_Object)
  4502. {
  4503. BF_FATAL("Unhandled");
  4504. }
  4505. else
  4506. {
  4507. BF_FATAL("Unhandled");
  4508. }
  4509. }
  4510. else if (!handled)
  4511. {
  4512. BF_FATAL("Unhandled");
  4513. }
  4514. argIdx++;
  4515. }
  4516. int size = (int)data.size() - sizeIdx;
  4517. *((uint16*)&data[sizeIdx]) = size;
  4518. }
  4519. #undef PUSH_INT8
  4520. #undef PUSH_INT16
  4521. #undef PUSH_INT32
  4522. SizedArray<BfIRValue, 16> dataValues;
  4523. for (uint8 val : data)
  4524. dataValues.push_back(GetConstValue8(val));
  4525. auto dataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(byteType), (int)data.size());
  4526. auto customAttrConst = mBfIRBuilder->CreateConstArray(dataArrayType, dataValues);
  4527. BfIRValue customAttrArray = mBfIRBuilder->CreateGlobalVariable(dataArrayType, true, BfIRLinkageType_Internal,
  4528. customAttrConst, typeDataName + StrFormat(".customAttr%d", customAttrIdx));
  4529. BfIRValue customAttrArrayPtr = mBfIRBuilder->CreateBitCast(customAttrArray, voidPtrIRType);
  4530. customAttrs.push_back(customAttrArrayPtr);
  4531. return customAttrIdx;
  4532. };
  4533. int typeCustomAttrIdx = _HandleCustomAttrs(typeInstance->mCustomAttributes);
  4534. SizedArray<int, 16> reflectFieldIndices;
  4535. for (int pass = 0; pass < 2; pass++)
  4536. {
  4537. bool skippedField = false;
  4538. reflectFieldIndices.clear();
  4539. for (int fieldIdx = 0; fieldIdx < (int)typeInstance->mFieldInstances.size(); fieldIdx++)
  4540. {
  4541. BfFieldInstance* fieldInstance = &typeInstance->mFieldInstances[fieldIdx];
  4542. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  4543. if (fieldDef == NULL)
  4544. continue;
  4545. auto fieldReflectKind = (ReflectKind)(reflectKind & ~ReflectKind_User);
  4546. bool includeField = reflectIncludeAllFields;
  4547. if (fieldInstance->mCustomAttributes != NULL)
  4548. {
  4549. for (auto& customAttr : fieldInstance->mCustomAttributes->mAttributes)
  4550. {
  4551. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  4552. {
  4553. includeField = true;
  4554. }
  4555. else
  4556. {
  4557. auto userReflectKind = _GetReflectUser(customAttr.mType);
  4558. fieldReflectKind = (ReflectKind)(fieldReflectKind | userReflectKind);
  4559. }
  4560. }
  4561. }
  4562. if ((fieldReflectKind & ReflectKind_User) != 0)
  4563. includeField = true;
  4564. if ((!fieldDef->mIsStatic) && ((fieldReflectKind & ReflectKind_NonStaticFields) != 0))
  4565. includeField = true;
  4566. if ((fieldDef->mIsStatic) && ((fieldReflectKind & ReflectKind_StaticFields) != 0))
  4567. includeField = true;
  4568. includeField |= forceReflectFields;
  4569. if (!includeField)
  4570. {
  4571. skippedField = true;
  4572. continue;
  4573. }
  4574. reflectFieldIndices.Add(fieldIdx);
  4575. }
  4576. // For a splattable type, we need to either include all fields or zero fields. This is to allow us to correctly splat
  4577. // params for reflected method calls even if we don't have reflection field info for the splatted type. This is
  4578. // possible because we write out a SplatData structure containing just TypeIds in that case
  4579. if (pass == 0)
  4580. {
  4581. if (!typeInstance->IsSplattable())
  4582. break;
  4583. if (!skippedField)
  4584. break;
  4585. if (reflectFieldIndices.size() == 0)
  4586. break;
  4587. }
  4588. }
  4589. SizedArray<BfIRValue, 16> fieldTypes;
  4590. enum FieldFlags
  4591. {
  4592. FieldFlags_Protected = 3,
  4593. FieldFlags_Public = 6,
  4594. FieldFlags_Static = 0x10,
  4595. FieldFlags_Const = 0x40,
  4596. FieldFlags_SpecialName = 0x80,
  4597. FieldFlags_EnumPayload = 0x100,
  4598. FieldFlags_EnumDiscriminator = 0x200
  4599. };
  4600. if ((typeInstance->IsPayloadEnum()) && (!typeInstance->IsBoxed()))
  4601. {
  4602. BfType* payloadType = typeInstance->GetUnionInnerType();
  4603. if (!payloadType->IsValuelessType())
  4604. {
  4605. BfIRValue payloadNameConst = GetStringObjectValue("$payload", true);
  4606. SizedArray<BfIRValue, 8> payloadFieldVals =
  4607. {
  4608. emptyValueType,
  4609. payloadNameConst, // mName
  4610. GetConstValue(0, longType), // mConstValue
  4611. GetConstValue(0, intType), // mDataOffset
  4612. GetConstValue(payloadType->mTypeId, typeIdType), // mFieldTypeId
  4613. GetConstValue(FieldFlags_SpecialName | FieldFlags_EnumPayload, shortType), // mFlags
  4614. GetConstValue(-1, intType), // mCustomAttributesIdx
  4615. };
  4616. auto payloadFieldData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance(), BfIRPopulateType_Full), payloadFieldVals);
  4617. fieldTypes.push_back(payloadFieldData);
  4618. }
  4619. BfType* dscrType = typeInstance->GetDiscriminatorType();
  4620. BfIRValue dscrNameConst = GetStringObjectValue("$discriminator", true);
  4621. SizedArray<BfIRValue, 8> dscrFieldVals =
  4622. {
  4623. emptyValueType,
  4624. dscrNameConst, // mName
  4625. GetConstValue(0, longType), // mConstValue
  4626. GetConstValue(BF_ALIGN(payloadType->mSize, dscrType->mAlign), intType), // mDataOffset
  4627. GetConstValue(dscrType->mTypeId, typeIdType), // mFieldTypeId
  4628. GetConstValue(FieldFlags_SpecialName | FieldFlags_EnumDiscriminator, shortType), // mFlags
  4629. GetConstValue(-1, intType), // mCustomAttributesIdx
  4630. };
  4631. auto dscrFieldData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance(), BfIRPopulateType_Full), dscrFieldVals);
  4632. fieldTypes.push_back(dscrFieldData);
  4633. }
  4634. for (auto fieldIdx : reflectFieldIndices)
  4635. {
  4636. if (!needsTypeData)
  4637. break;
  4638. BfFieldInstance* fieldInstance = &typeInstance->mFieldInstances[fieldIdx];
  4639. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  4640. BfIRValue fieldNameConst = GetStringObjectValue(fieldDef->mName, true);
  4641. int typeId = 0;
  4642. auto fieldType = fieldInstance->GetResolvedType();
  4643. if (fieldType->IsGenericParam())
  4644. {
  4645. //TODO:
  4646. }
  4647. else
  4648. typeId = fieldType->mTypeId;
  4649. FieldFlags fieldFlags = (FieldFlags)0;
  4650. if (fieldDef->mProtection == BfProtection_Protected)
  4651. fieldFlags = (FieldFlags)(fieldFlags | FieldFlags_Protected);
  4652. if (fieldDef->mProtection == BfProtection_Public)
  4653. fieldFlags = (FieldFlags)(fieldFlags | FieldFlags_Public);
  4654. if (fieldDef->mIsStatic)
  4655. fieldFlags = (FieldFlags)(fieldFlags | FieldFlags_Static);
  4656. if (fieldDef->mIsConst)
  4657. fieldFlags = (FieldFlags)(fieldFlags | FieldFlags_Const);
  4658. int customAttrIdx = _HandleCustomAttrs(fieldInstance->mCustomAttributes);
  4659. BfIRValue constValue = GetConstValue(0, longType);
  4660. if (fieldInstance->GetFieldDef()->mIsConst)
  4661. {
  4662. if (fieldInstance->mConstIdx != -1)
  4663. {
  4664. auto constant = typeInstance->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  4665. constValue = mBfIRBuilder->CreateConst(BfTypeCode_UInt64, constant->mUInt64);
  4666. }
  4667. }
  4668. SizedArray<BfIRValue, 8> fieldVals =
  4669. {
  4670. emptyValueType,
  4671. fieldNameConst, // mName
  4672. constValue, // mConstValue
  4673. GetConstValue(fieldInstance->mDataOffset, intType), // mDataOffset
  4674. GetConstValue(typeId, typeIdType), // mFieldTypeId
  4675. GetConstValue(fieldFlags, shortType), // mFlags
  4676. GetConstValue(customAttrIdx, intType), // mCustomAttributesIdx
  4677. };
  4678. auto fieldData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectFieldDataType->ToTypeInstance(), BfIRPopulateType_Full), fieldVals);
  4679. fieldTypes.push_back(fieldData);
  4680. }
  4681. auto reflectFieldDataIRType = mBfIRBuilder->MapType(reflectFieldDataType);
  4682. BfIRValue fieldDataPtr;
  4683. BfIRType fieldDataPtrType = mBfIRBuilder->GetPointerTo(reflectFieldDataIRType);
  4684. if (fieldTypes.size() == 0)
  4685. {
  4686. if ((type->IsSplattable()) && (type->IsStruct()) && (!type->IsValuelessType()))
  4687. {
  4688. BfTypeInstance* reflectFieldSplatDataType = ResolveTypeDef(mCompiler->mReflectFieldSplatDataDef)->ToTypeInstance();
  4689. SizedArray<BfIRValue, 3> splatTypes;
  4690. SizedArray<BfIRValue, 3> splatOffsets;
  4691. std::function<void(BfType*, int)> _CheckSplat = [&](BfType* checkType, int offset)
  4692. {
  4693. auto checkTypeInstance = checkType->ToTypeInstance();
  4694. if ((checkTypeInstance != NULL) && (checkTypeInstance->IsValueType()) && (checkTypeInstance->IsDataIncomplete()))
  4695. PopulateType(checkTypeInstance);
  4696. if (checkType->IsStruct())
  4697. {
  4698. int dataEnd = offset;
  4699. if (checkTypeInstance->mBaseType != NULL)
  4700. _CheckSplat(checkTypeInstance->mBaseType, offset);
  4701. if (checkTypeInstance->mIsUnion)
  4702. {
  4703. BfType* unionInnerType = checkTypeInstance->GetUnionInnerType();
  4704. _CheckSplat(unionInnerType, offset);
  4705. }
  4706. else
  4707. {
  4708. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  4709. {
  4710. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  4711. if (fieldInstance->mDataIdx >= 0)
  4712. {
  4713. _CheckSplat(fieldInstance->GetResolvedType(), offset + fieldInstance->mDataOffset);
  4714. dataEnd = offset + fieldInstance->mDataOffset + fieldInstance->mResolvedType->mSize;
  4715. }
  4716. }
  4717. }
  4718. if (checkTypeInstance->IsEnum())
  4719. {
  4720. // Add discriminator
  4721. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  4722. if (!checkTypeInstance->mIsPacked)
  4723. dataEnd = BF_ALIGN(dataEnd, dscrType->mAlign);
  4724. _CheckSplat(dscrType, dataEnd);
  4725. }
  4726. }
  4727. else if (checkType->IsMethodRef())
  4728. {
  4729. // auto methodRefType = (BfMethodRefType*)checkType;
  4730. // for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  4731. // {
  4732. // if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  4733. // _CheckSplat(methodRefType->GetCaptureType(dataIdx), offsetof);
  4734. // else
  4735. // dataLambda(methodRefType->GetCaptureType(dataIdx));
  4736. // }
  4737. }
  4738. else if (!checkType->IsValuelessType())
  4739. {
  4740. splatTypes.Add(GetConstValue(checkType->mTypeId, typeIdType));
  4741. splatOffsets.Add(GetConstValue(offset, intType));
  4742. }
  4743. };
  4744. _CheckSplat(type, 0);
  4745. while (splatTypes.size() < 3)
  4746. {
  4747. splatTypes.Add(GetConstValue(0, typeIdType));
  4748. splatOffsets.Add(GetConstValue(0, intType));
  4749. }
  4750. BfIRValue splatTypesConst = mBfIRBuilder->CreateConstArray(mBfIRBuilder->MapType(reflectFieldSplatDataType->mFieldInstances[0].mResolvedType), splatTypes);
  4751. BfIRValue splatOffsetsConst = mBfIRBuilder->CreateConstArray(mBfIRBuilder->MapType(reflectFieldSplatDataType->mFieldInstances[1].mResolvedType), splatOffsets);
  4752. SizedArray<BfIRValue, 8> splatVals =
  4753. {
  4754. emptyValueType,
  4755. splatTypesConst,
  4756. splatOffsetsConst
  4757. };
  4758. auto fieldSplatData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectFieldSplatDataType->ToTypeInstance(), BfIRPopulateType_Full), splatVals);
  4759. BfIRValue fieldDataArray = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(reflectFieldSplatDataType), true, BfIRLinkageType_Internal,
  4760. fieldSplatData, typeDataName + ".splats");
  4761. fieldDataPtr = mBfIRBuilder->CreateBitCast(fieldDataArray, fieldDataPtrType);
  4762. }
  4763. else
  4764. fieldDataPtr = mBfIRBuilder->CreateConstNull(fieldDataPtrType);
  4765. }
  4766. else
  4767. {
  4768. BfIRType fieldDataConstType = mBfIRBuilder->GetSizedArrayType(reflectFieldDataIRType, (int)fieldTypes.size());
  4769. BfIRValue fieldDataConst = mBfIRBuilder->CreateConstArray(fieldDataConstType, fieldTypes);
  4770. BfIRValue fieldDataArray = mBfIRBuilder->CreateGlobalVariable(fieldDataConstType, true, BfIRLinkageType_Internal,
  4771. fieldDataConst, "fields." + typeDataName);
  4772. fieldDataPtr = mBfIRBuilder->CreateBitCast(fieldDataArray, fieldDataPtrType);
  4773. }
  4774. /// Methods
  4775. BfType* reflectMethodDataType = ResolveTypeDef(mCompiler->mReflectMethodDataDef);
  4776. BfType* reflectParamDataType = ResolveTypeDef(mCompiler->mReflectParamDataDef);
  4777. BfType* reflectParamDataPtrType = CreatePointerType(reflectParamDataType);
  4778. SizedArray<BfIRValue, 16> methodTypes;
  4779. for (int methodIdx = 0; methodIdx < (int)typeDef->mMethods.size(); methodIdx++)
  4780. {
  4781. if (!needsTypeData)
  4782. break;
  4783. auto methodInstanceGroup = &typeInstance->mMethodInstanceGroups[methodIdx];
  4784. if (!methodInstanceGroup->IsImplemented())
  4785. continue;
  4786. auto methodDef = typeDef->mMethods[methodIdx];
  4787. if (methodDef->mNoReflect)
  4788. continue;
  4789. auto defaultMethod = methodInstanceGroup->mDefault;
  4790. if (defaultMethod == NULL)
  4791. continue;
  4792. if (defaultMethod->mIsUnspecialized)
  4793. continue;
  4794. if (!defaultMethod->mIsReified)
  4795. continue;
  4796. if ((defaultMethod->mChainType == BfMethodChainType_ChainMember) || (defaultMethod->mChainType == BfMethodChainType_ChainSkip))
  4797. continue;
  4798. if (defaultMethod->mMethodDef->mMethodType == BfMethodType_CtorNoBody)
  4799. continue;
  4800. auto methodReflectKind = (ReflectKind)(reflectKind & ~ReflectKind_User);
  4801. bool includeMethod = reflectIncludeAllMethods;
  4802. BfCustomAttributes* methodCustomAttributes = NULL;
  4803. if ((defaultMethod->mMethodInfoEx != NULL) && (defaultMethod->mMethodInfoEx->mMethodCustomAttributes != NULL) && (defaultMethod->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes != NULL))
  4804. {
  4805. methodCustomAttributes = defaultMethod->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes;
  4806. for (auto& customAttr : defaultMethod->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes->mAttributes)
  4807. {
  4808. if (customAttr.mType->mTypeDef->mName->ToString() == "ReflectAttribute")
  4809. {
  4810. includeMethod = true;
  4811. }
  4812. else
  4813. {
  4814. auto userReflectKind = _GetReflectUser(customAttr.mType);
  4815. methodReflectKind = (ReflectKind)(methodReflectKind | userReflectKind);
  4816. }
  4817. }
  4818. }
  4819. if (!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, mProject))
  4820. continue;
  4821. if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  4822. {
  4823. for (BfParameterDeclaration* paramDecl : methodDeclaration->mParams)
  4824. {
  4825. if (paramDecl->mAttributes != NULL)
  4826. methodReflectKind = (ReflectKind)(methodReflectKind | _GetReflectUserFromDirective(paramDecl->mAttributes, BfAttributeTargets_Parameter));
  4827. }
  4828. if (methodDeclaration->mReturnAttributes != NULL)
  4829. methodReflectKind = (ReflectKind)(methodReflectKind | _GetReflectUserFromDirective(methodDeclaration->mReturnAttributes, BfAttributeTargets_ReturnValue));
  4830. }
  4831. if ((methodReflectKind & (ReflectKind_Methods | ReflectKind_User)) != 0)
  4832. includeMethod = true;
  4833. if ((methodDef->mIsStatic) && ((methodReflectKind & ReflectKind_StaticMethods) != 0))
  4834. includeMethod = true;
  4835. if (!includeMethod)
  4836. continue;
  4837. BfModuleMethodInstance moduleMethodInstance;
  4838. BfIRValue funcVal = voidPtrNull;
  4839. if (((!typeInstance->IsBoxed()) || (!methodDef->mIsStatic)) &&
  4840. (!typeInstance->IsUnspecializedType()) &&
  4841. (methodDef->mMethodType != BfMethodType_Ignore) &&
  4842. (methodDef->mMethodType != BfMethodType_Mixin) &&
  4843. (!methodDef->mIsAbstract) &&
  4844. (methodDef->mGenericParams.size() == 0))
  4845. {
  4846. moduleMethodInstance = GetMethodInstanceAtIdx(typeInstance, methodIdx);
  4847. if (moduleMethodInstance.mFunc)
  4848. funcVal = mBfIRBuilder->CreateBitCast(moduleMethodInstance.mFunc, voidPtrIRType);
  4849. }
  4850. BfIRValue methodNameConst = GetStringObjectValue(methodDef->mName, true);
  4851. enum MethodFlags
  4852. {
  4853. MethodFlags_Protected = 3,
  4854. MethodFlags_Public = 6,
  4855. MethodFlags_Static = 0x10,
  4856. MethodFlags_Virtual = 0x40,
  4857. MethodFlags_StdCall = 0x1000,
  4858. MethodFlags_FastCall = 0x2000,
  4859. MethodFlags_Mutating = 0x4000,
  4860. };
  4861. MethodFlags methodFlags = (MethodFlags)0;
  4862. if (methodDef->mProtection == BfProtection_Protected)
  4863. methodFlags = (MethodFlags)(methodFlags | MethodFlags_Protected);
  4864. if (methodDef->mProtection == BfProtection_Public)
  4865. methodFlags = (MethodFlags)(methodFlags | MethodFlags_Public);
  4866. if (methodDef->mIsStatic)
  4867. methodFlags = (MethodFlags)(methodFlags | MethodFlags_Static);
  4868. if (methodDef->mIsVirtual)
  4869. methodFlags = (MethodFlags)(methodFlags | MethodFlags_Virtual);
  4870. if (methodDef->mCallingConvention == BfCallingConvention_Fastcall)
  4871. methodFlags = (MethodFlags)(methodFlags | MethodFlags_FastCall);
  4872. if (methodDef->mIsMutating)
  4873. methodFlags = (MethodFlags)(methodFlags | MethodFlags_Mutating);
  4874. int customAttrIdx = _HandleCustomAttrs(methodCustomAttributes);
  4875. enum ParamFlags
  4876. {
  4877. ParamFlag_None = 0,
  4878. ParamFlag_Splat = 1,
  4879. ParamFlag_Implicit = 2,
  4880. };
  4881. SizedArray<BfIRValue, 8> paramVals;
  4882. for (int paramIdx = 0; paramIdx < defaultMethod->GetParamCount(); paramIdx++)
  4883. {
  4884. String paramName = defaultMethod->GetParamName(paramIdx);
  4885. BfType* paramType = defaultMethod->GetParamType(paramIdx);
  4886. ParamFlags paramFlags = ParamFlag_None;
  4887. if (defaultMethod->GetParamIsSplat(paramIdx))
  4888. paramFlags = (ParamFlags)(paramFlags | ParamFlag_Splat);
  4889. BfIRValue paramNameConst = GetStringObjectValue(paramName, true);
  4890. SizedArray<BfIRValue, 8> paramDataVals =
  4891. {
  4892. emptyValueType,
  4893. paramNameConst,
  4894. GetConstValue(paramType->mTypeId, typeIdType),
  4895. GetConstValue((int32)paramFlags, shortType),
  4896. GetConstValue(customAttrIdx, intType) // defaultIdx
  4897. };
  4898. auto paramData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapType(reflectParamDataType, BfIRPopulateType_Full), paramDataVals);
  4899. paramVals.Add(paramData);
  4900. }
  4901. BfIRValue paramsVal;
  4902. if (paramVals.size() > 0)
  4903. {
  4904. BfIRType paramDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(reflectParamDataType, BfIRPopulateType_Full), (int)paramVals.size());
  4905. BfIRValue paramDataConst = mBfIRBuilder->CreateConstArray(paramDataArrayType, paramVals);
  4906. BfIRValue paramDataArray = mBfIRBuilder->CreateGlobalVariable(paramDataArrayType, true, BfIRLinkageType_Internal,
  4907. paramDataConst, typeDataName + StrFormat(".params%d", methodIdx));
  4908. paramsVal = mBfIRBuilder->CreateBitCast(paramDataArray, mBfIRBuilder->MapType(reflectParamDataPtrType));
  4909. }
  4910. else
  4911. paramsVal = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(reflectParamDataPtrType));
  4912. int vDataVal = -1;
  4913. if (defaultMethod->mVirtualTableIdx != -1)
  4914. {
  4915. int vDataIdx = -1;
  4916. vDataIdx = 1 + mCompiler->GetDynCastVDataCount() + mCompiler->mMaxInterfaceSlots;
  4917. if ((mCompiler->mOptions.mHasVDataExtender) && (mCompiler->IsHotCompile()))
  4918. {
  4919. auto typeInst = defaultMethod->mMethodInstanceGroup->mOwner;
  4920. int extMethodIdx = (defaultMethod->mVirtualTableIdx - typeInst->GetBaseVTableSize()) - typeInst->GetOrigSelfVTableSize();
  4921. if (extMethodIdx >= 0)
  4922. {
  4923. // Extension?
  4924. int vExtOfs = typeInst->GetOrigBaseVTableSize();
  4925. vDataVal = ((vDataIdx + vExtOfs + 1) << 20) | (extMethodIdx);
  4926. }
  4927. else
  4928. {
  4929. // Map this new virtual index back to the original index
  4930. vDataIdx += (defaultMethod->mVirtualTableIdx - typeInst->GetBaseVTableSize()) + typeInst->GetOrigBaseVTableSize();
  4931. }
  4932. }
  4933. else
  4934. {
  4935. vDataIdx += defaultMethod->mVirtualTableIdx;
  4936. }
  4937. if (vDataVal == -1)
  4938. vDataVal = vDataIdx * mSystem->mPtrSize;
  4939. }
  4940. SizedArray<BfIRValue, 8> methodDataVals =
  4941. {
  4942. emptyValueType,
  4943. methodNameConst, // mName
  4944. funcVal, // mFuncPtr
  4945. paramsVal,
  4946. GetConstValue(defaultMethod->mReturnType->mTypeId, typeIdType),
  4947. GetConstValue((int)paramVals.size(), shortType),
  4948. GetConstValue(methodFlags, shortType),
  4949. GetConstValue(vDataVal, intType),
  4950. GetConstValue(-1, intType),
  4951. };
  4952. auto methodData = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapTypeInst(reflectMethodDataType->ToTypeInstance(), BfIRPopulateType_Full), methodDataVals);
  4953. methodTypes.push_back(methodData);
  4954. }
  4955. BfIRValue methodDataPtr;
  4956. BfIRType methodDataPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(reflectMethodDataType));
  4957. if (methodTypes.size() == 0)
  4958. methodDataPtr = mBfIRBuilder->CreateConstNull(methodDataPtrType);
  4959. else
  4960. {
  4961. BfIRType methodDataArrayType = mBfIRBuilder->GetSizedArrayType(mBfIRBuilder->MapType(reflectMethodDataType, BfIRPopulateType_Full), (int)methodTypes.size());
  4962. BfIRValue methodDataConst = mBfIRBuilder->CreateConstArray(methodDataArrayType, methodTypes);
  4963. BfIRValue methodDataArray = mBfIRBuilder->CreateGlobalVariable(methodDataArrayType, true, BfIRLinkageType_Internal,
  4964. methodDataConst, "methods." + typeDataName);
  4965. methodDataPtr = mBfIRBuilder->CreateBitCast(methodDataArray, methodDataPtrType);
  4966. }
  4967. /////
  4968. int underlyingType = 0;
  4969. if ((typeInstance->IsTypedPrimitive()) || (typeInstance->IsBoxed()))
  4970. {
  4971. underlyingType = typeInstance->GetUnderlyingType()->mTypeId;
  4972. }
  4973. int outerTypeId = 0;
  4974. auto outerType = GetOuterType(typeInstance);
  4975. if (outerType != NULL)
  4976. outerTypeId = outerType->mTypeId;
  4977. BfIRValue customAttrDataPtr;
  4978. if (customAttrs.size() > 0)
  4979. {
  4980. BfIRType customAttrsArrayType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)customAttrs.size());
  4981. BfIRValue customAttrsConst = mBfIRBuilder->CreateConstArray(customAttrsArrayType, customAttrs);
  4982. BfIRValue customAttrsArray = mBfIRBuilder->CreateGlobalVariable(customAttrsArrayType, true, BfIRLinkageType_Internal,
  4983. customAttrsConst, "customAttrs." + typeDataName);
  4984. customAttrDataPtr = mBfIRBuilder->CreateBitCast(customAttrsArray, voidPtrPtrIRType);
  4985. }
  4986. else
  4987. {
  4988. customAttrDataPtr = mBfIRBuilder->CreateConstNull(voidPtrPtrIRType);
  4989. }
  4990. SizedArray<BfIRValue, 32> typeDataVals =
  4991. {
  4992. typeData,
  4993. castedClassVData, // mTypeClassVData
  4994. typeNameConst, // mName
  4995. namespaceConst, // mNamespace
  4996. GetConstValue(typeInstance->mInstSize, intType), // mInstSize
  4997. GetConstValue(typeInstance->mInstAlign, intType), // mInstAlign
  4998. GetConstValue(typeCustomAttrIdx, intType), // mCustomAttributes
  4999. GetConstValue(baseTypeId, typeIdType), // mBaseType
  5000. GetConstValue(underlyingType, typeIdType), // mUnderlyingType
  5001. GetConstValue(outerTypeId, typeIdType), // mOuterType
  5002. GetConstValue(typeInstance->mInheritanceId, intType), // mInheritanceId
  5003. GetConstValue(typeInstance->mInheritanceCount, intType), // mInheritanceCount
  5004. GetConstValue(typeInstance->mSlotNum, byteType), // mInterfaceSlot
  5005. GetConstValue(0, byteType), // mInterfaceCount
  5006. GetConstValue((int)methodTypes.size(), shortType), // mMethodDataCount
  5007. GetConstValue(0, shortType), // mPropertyDataCount
  5008. GetConstValue((int)fieldTypes.size(), shortType), // mFieldDataCount
  5009. GetConstValue(0, shortType), // mConstructorDataCount
  5010. voidPtrNull, // mInterfaceDataPtr
  5011. methodDataPtr, // mMethodDataPtr
  5012. voidPtrNull, // mPropertyDataPtr
  5013. fieldDataPtr, // mFieldDataPtr
  5014. voidPtrNull, // mConstructorDataPtr
  5015. customAttrDataPtr, // mCustomAttrDataPtr
  5016. };
  5017. BfIRType typeInstanceDataType = mBfIRBuilder->MapTypeInst(typeInstanceType->ToTypeInstance(), BfIRPopulateType_Full);
  5018. auto typeInstanceData = mBfIRBuilder->CreateConstStruct(typeInstanceDataType, typeDataVals);
  5019. if (!needsTypeData)
  5020. {
  5021. // No need for anything beyond typeInstanceData
  5022. }
  5023. else if ((typeInstance->IsGenericTypeInstance()) && (typeInstance->IsUnspecializedType()))
  5024. {
  5025. auto genericTypeInstance = typeInstance->ToGenericTypeInstance();
  5026. SizedArray<BfIRValue, 4> unspecializedData =
  5027. {
  5028. typeInstanceData,
  5029. GetConstValue((int)genericTypeInstance->mTypeGenericArguments.size(), byteType), // mGenericParamCount
  5030. };
  5031. auto reflectUnspecializedGenericType = ResolveTypeDef(mCompiler->mReflectUnspecializedGenericType);
  5032. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectUnspecializedGenericType->ToTypeInstance(), BfIRPopulateType_Full);
  5033. typeInstanceData = mBfIRBuilder->CreateConstStruct(typeInstanceDataType, unspecializedData);
  5034. }
  5035. else if (typeInstance->IsGenericTypeInstance())
  5036. {
  5037. auto genericTypeInstance = typeInstance->ToGenericTypeInstance();
  5038. auto reflectSpecializedGenericType = ResolveTypeDef(mCompiler->mReflectSpecializedGenericType);
  5039. auto unspecializedType = ResolveTypeDef(typeInstance->mTypeDef);
  5040. SizedArray<BfIRValue, 4> resolvedTypes;
  5041. for (auto typeGenericArg : genericTypeInstance->mTypeGenericArguments)
  5042. resolvedTypes.push_back(GetConstValue(typeGenericArg->mTypeId, typeIdType));
  5043. auto typeIRType = mBfIRBuilder->MapType(typeIdType);
  5044. auto typePtrIRType = mBfIRBuilder->GetPointerTo(typeIRType);
  5045. auto genericArrayType = mBfIRBuilder->GetSizedArrayType(typeIRType, (int)resolvedTypes.size());
  5046. BfIRValue resolvedTypesConst = mBfIRBuilder->CreateConstArray(genericArrayType, resolvedTypes);
  5047. BfIRValue resolvedTypesArray = mBfIRBuilder->CreateGlobalVariable(genericArrayType, true, BfIRLinkageType_Internal,
  5048. resolvedTypesConst, "resolvedTypes." + typeDataName);
  5049. BfIRValue resovledTypesPtr = mBfIRBuilder->CreateBitCast(resolvedTypesArray, typePtrIRType);
  5050. SizedArray<BfIRValue, 3> specGenericData =
  5051. {
  5052. typeInstanceData,
  5053. GetConstValue(unspecializedType->mTypeId, typeIdType), // mUnspecialziedType
  5054. resovledTypesPtr, // mFieldDataPtr
  5055. };
  5056. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectSpecializedGenericType->ToTypeInstance(), BfIRPopulateType_Full);
  5057. typeInstanceData = mBfIRBuilder->CreateConstStruct(typeInstanceDataType, specGenericData);
  5058. if (typeInstance->IsArray())
  5059. {
  5060. auto arrayType = (BfArrayType*)typeInstance;
  5061. BfType* elementType = genericTypeInstance->mTypeGenericArguments[0];
  5062. BfFieldInstance* elementFieldInstance = &genericTypeInstance->mFieldInstances[0];
  5063. SizedArray<BfIRValue, 4> arrayData =
  5064. {
  5065. typeInstanceData,
  5066. GetConstValue(elementType->mSize, intType), // mElementSize
  5067. GetConstValue(1, byteType), // mRank
  5068. GetConstValue(elementFieldInstance->mDataOffset, byteType), // mElementsDataOffset
  5069. };
  5070. auto reflectArrayType = ResolveTypeDef(mCompiler->mReflectArrayType);
  5071. typeInstanceDataType = mBfIRBuilder->MapTypeInst(reflectArrayType->ToTypeInstance(), BfIRPopulateType_Full);
  5072. typeInstanceData = mBfIRBuilder->CreateConstStruct(typeInstanceDataType, arrayData);
  5073. }
  5074. }
  5075. BfIRValue typeDataVar;
  5076. if (needsTypeData)
  5077. {
  5078. typeDataVar = mBfIRBuilder->CreateGlobalVariable(typeInstanceDataType, true,
  5079. BfIRLinkageType_External, typeInstanceData, typeDataName);
  5080. if (mBfIRBuilder->DbgHasInfo())
  5081. {
  5082. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, typeDataName, typeDataName, NULL, 0, mBfIRBuilder->DbgGetTypeInst(typeInstanceType->ToTypeInstance()), false, typeDataVar);
  5083. }
  5084. }
  5085. else
  5086. {
  5087. typeDataVar = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(mContext->mBfTypeType));
  5088. }
  5089. typeDataVar = mBfIRBuilder->CreateBitCast(typeDataVar, mBfIRBuilder->MapType(mContext->mBfTypeType));
  5090. mTypeDataRefs[typeInstance] = typeDataVar;
  5091. if (classVDataVar)
  5092. {
  5093. BF_ASSERT(!classVDataName.IsEmpty());
  5094. vData[0] = mBfIRBuilder->CreateBitCast(typeDataVar, voidPtrIRType);
  5095. auto classVDataConstDataType = mBfIRBuilder->GetSizedArrayType(voidPtrIRType, (int)vData.size());
  5096. auto classVDataConstData = mBfIRBuilder->CreateConstArray(classVDataConstDataType, vData);
  5097. mBfIRBuilder->GlobalVar_SetInitializer(classVDataVar, classVDataConstData);
  5098. if (mCompiler->mOptions.mObjectHasDebugFlags)
  5099. mBfIRBuilder->GlobalVar_SetAlignment(classVDataVar, 256);
  5100. else
  5101. mBfIRBuilder->GlobalVar_SetAlignment(classVDataVar, mContext->mBfClassVDataPtrType->mAlign);
  5102. if (mBfIRBuilder->DbgHasInfo())
  5103. {
  5104. BfType* voidType = GetPrimitiveType(BfTypeCode_None);
  5105. BfType* voidPtrType = CreatePointerType(voidType);
  5106. BfType* classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  5107. BfIRMDNode arrayType = mBfIRBuilder->DbgCreateArrayType(vData.size() * mSystem->mPtrSize * 8, mSystem->mPtrSize * 8, mBfIRBuilder->DbgGetType(voidPtrType), vData.size());
  5108. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, classVDataName, classVDataName, NULL, 0, arrayType, false, classVDataVar);
  5109. }
  5110. }
  5111. return typeDataVar;
  5112. }
  5113. BfIRValue BfModule::FixClassVData(BfIRValue value)
  5114. {
  5115. if (!mCompiler->mOptions.mObjectHasDebugFlags)
  5116. return value;
  5117. auto intptrValue = mBfIRBuilder->CreatePtrToInt(value, BfTypeCode_IntPtr);
  5118. auto maskedValue = mBfIRBuilder->CreateAnd(intptrValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)~0xFFULL));
  5119. return mBfIRBuilder->CreateIntToPtr(maskedValue, mBfIRBuilder->GetType(value));
  5120. }
  5121. void BfModule::CheckStaticAccess(BfTypeInstance* typeInstance)
  5122. {
  5123. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  5124. //TODO: Create a hashset of these, we don't need to repeatedly call static ctors for a given type
  5125. // When we access classes with static constructors FROM a static constructor,
  5126. // we call that other class's static constructor first. Recursion cannot occur, since
  5127. // we simply ignore subsequent attempts to re-enter the constructor
  5128. if (!typeInstance->mHasStaticInitMethod)
  5129. return;
  5130. if ((mCurMethodInstance == NULL) || ((mCurMethodInstance->mMethodDef->mMethodType != BfMethodType_Ctor) || (!mCurMethodInstance->mMethodDef->mIsStatic)))
  5131. return;
  5132. if (mCurMethodInstance->mMethodInstanceGroup->mOwner == typeInstance)
  5133. return;
  5134. auto checkTypeDef = typeInstance->mTypeDef;
  5135. checkTypeDef->PopulateMemberSets();
  5136. BfMethodDef* nextMethodDef = NULL;
  5137. BfMemberSetEntry* entry;
  5138. if (checkTypeDef->mMethodSet.TryGetWith(String("__BfStaticCtor"), &entry))
  5139. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  5140. while (nextMethodDef != NULL)
  5141. {
  5142. auto checkMethod = nextMethodDef;
  5143. nextMethodDef = nextMethodDef->mNextWithSameName;
  5144. auto methodModule = GetMethodInstance(typeInstance, checkMethod, BfTypeVector());
  5145. if (methodModule)
  5146. {
  5147. auto methodInstance = methodModule.mMethodInstance;
  5148. if ((methodInstance != NULL) &&
  5149. (methodInstance->mMethodDef->mIsStatic) &&
  5150. (methodInstance->mMethodDef->mMethodType == BfMethodType_Ctor) &&
  5151. ((methodInstance->mChainType == BfMethodChainType_ChainHead) || (methodInstance->mChainType == BfMethodChainType_None)))
  5152. {
  5153. mBfIRBuilder->CreateCall(methodModule.mFunc, SizedArray<BfIRValue, 0>());
  5154. break;
  5155. }
  5156. }
  5157. }
  5158. }
  5159. BfIRFunction BfModule::GetIntrinsic(BfMethodInstance* methodInstance, bool reportFailure)
  5160. {
  5161. auto methodOwner = methodInstance->GetOwner();
  5162. auto methodDef = methodInstance->mMethodDef;
  5163. auto methodDeclaration = methodDef->GetMethodDeclaration();
  5164. bool hasExternSpecifier = (methodDeclaration != NULL) && (methodDeclaration->mExternSpecifier != NULL);
  5165. if (!hasExternSpecifier)
  5166. return BfIRFunction();
  5167. if (methodInstance->GetCustomAttributes() == NULL)
  5168. return BfIRFunction();
  5169. for (auto& customAttribute : methodInstance->GetCustomAttributes()->mAttributes)
  5170. {
  5171. String typeName = TypeToString(customAttribute.mType);
  5172. if ((typeName == "System.IntrinsicAttribute") && (customAttribute.mCtorArgs.size() > 0))
  5173. {
  5174. methodInstance->mIsIntrinsic = true;
  5175. auto constant = methodOwner->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  5176. String error;
  5177. if ((constant != NULL) && (BfIRConstHolder::IsInt(constant->mTypeCode)))
  5178. {
  5179. int stringId = constant->mInt32;
  5180. auto entry = mContext->mStringObjectIdMap[stringId];
  5181. int intrinId = BfIRCodeGen::GetIntrinsicId(entry.mString);
  5182. if (intrinId != -1)
  5183. {
  5184. if (intrinId == BfIRIntrinsic_Malloc)
  5185. {
  5186. return GetBuiltInFunc(BfBuiltInFuncType_Malloc);
  5187. }
  5188. else if (intrinId == BfIRIntrinsic_Free)
  5189. {
  5190. return GetBuiltInFunc(BfBuiltInFuncType_Free);
  5191. }
  5192. SizedArray<BfIRType, 2> paramTypes;
  5193. for (auto& param : methodInstance->mParams)
  5194. paramTypes.push_back(mBfIRBuilder->MapType(param.mResolvedType));
  5195. return mBfIRBuilder->GetIntrinsic(intrinId, paramTypes);
  5196. }
  5197. else if (reportFailure)
  5198. error = StrFormat("Unable to find intrinsic '%s'", entry.mString.c_str());
  5199. }
  5200. else if (reportFailure)
  5201. error = "Intrinsic name must be a constant string";
  5202. if (reportFailure)
  5203. {
  5204. BfAstNode* ref = methodDeclaration->mAttributes;
  5205. Fail(error, ref);
  5206. }
  5207. }
  5208. }
  5209. return BfIRFunction();
  5210. }
  5211. BfIRFunction BfModule::GetBuiltInFunc(BfBuiltInFuncType funcTypeId)
  5212. {
  5213. if (mBfIRBuilder->mIgnoreWrites)
  5214. return mBfIRBuilder->GetFakeFunction();
  5215. if (!mBuiltInFuncs[(int)funcTypeId])
  5216. {
  5217. SizedArray<BfIRType, 4> paramTypes;
  5218. auto nullPtrType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr));
  5219. auto intType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_IntPtr));
  5220. auto int32Type = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int32));
  5221. auto intPtrType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_IntPtr));
  5222. auto byteType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int8));
  5223. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  5224. auto objType = mBfIRBuilder->MapType(mContext->mBfObjectType);
  5225. BfIRFunctionType funcType;
  5226. BfIRFunction func;
  5227. switch (funcTypeId)
  5228. {
  5229. case BfBuiltInFuncType_PrintF:
  5230. funcType = mBfIRBuilder->CreateFunctionType(int32Type, paramTypes, true);
  5231. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, "PrintF");
  5232. break;
  5233. case BfBuiltInFuncType_Malloc:
  5234. {
  5235. if (mCompiler->mOptions.mDebugAlloc)
  5236. {
  5237. func = GetInternalMethod("Dbg_RawAlloc", 1).mFunc;
  5238. }
  5239. else
  5240. {
  5241. String funcName = mCompiler->mOptions.mMallocLinkName;
  5242. if (funcName.IsEmpty())
  5243. funcName = "malloc";
  5244. func = mBfIRBuilder->GetFunction(funcName);
  5245. if (!func)
  5246. {
  5247. paramTypes.clear();
  5248. paramTypes.push_back(intType);
  5249. funcType = mBfIRBuilder->CreateFunctionType(nullPtrType, paramTypes);
  5250. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, funcName);
  5251. mBfIRBuilder->Func_SetParamName(func, 1, "size");
  5252. }
  5253. }
  5254. }
  5255. break;
  5256. case BfBuiltInFuncType_Free:
  5257. {
  5258. if (mCompiler->mOptions.mDebugAlloc)
  5259. {
  5260. func = GetInternalMethod("Dbg_RawFree").mFunc;
  5261. }
  5262. else
  5263. {
  5264. String funcName = mCompiler->mOptions.mFreeLinkName;
  5265. if (funcName.IsEmpty())
  5266. funcName = "free";
  5267. func = mBfIRBuilder->GetFunction(funcName);
  5268. if (!func)
  5269. {
  5270. paramTypes.clear();
  5271. paramTypes.push_back(nullPtrType);
  5272. funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  5273. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, funcName);
  5274. mBfIRBuilder->Func_SetParamName(func, 1, "ptr");
  5275. }
  5276. }
  5277. }
  5278. break;
  5279. case BfBuiltInFuncType_LoadSharedLibraries:
  5280. paramTypes.clear();
  5281. funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  5282. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, "BfLoadSharedLibraries");
  5283. break;
  5284. default: break;
  5285. }
  5286. mBuiltInFuncs[(int)funcTypeId] = func;
  5287. return func;
  5288. }
  5289. return mBuiltInFuncs[(int)funcTypeId];
  5290. }
  5291. void BfModule::ResolveGenericParamConstraints(BfGenericParamInstance* genericParamInstance, bool isUnspecialized)
  5292. {
  5293. BfGenericParamDef* genericParamDef = genericParamInstance->GetGenericParamDef();
  5294. BfExternalConstraintDef* externConstraintDef = genericParamInstance->GetExternConstraintDef();
  5295. BfConstraintDef* constraintDef = genericParamInstance->GetConstraintDef();
  5296. BfType* startingTypeConstraint = genericParamInstance->mTypeConstraint;
  5297. BfAutoComplete* bfAutocomplete = NULL;
  5298. if ((mCompiler->mResolvePassData != NULL) && (isUnspecialized))
  5299. bfAutocomplete = mCompiler->mResolvePassData->mAutoComplete;
  5300. if ((bfAutocomplete != NULL) && (genericParamDef != NULL))
  5301. {
  5302. for (int nameIdx = 0; nameIdx < (int)genericParamDef->mNameNodes.size(); nameIdx++)
  5303. {
  5304. auto nameNode = genericParamDef->mNameNodes[nameIdx];
  5305. if (bfAutocomplete->IsAutocompleteNode(nameNode))
  5306. {
  5307. String filter = nameNode->ToString();
  5308. bfAutocomplete->mInsertStartIdx = nameNode->GetSrcStart();
  5309. bfAutocomplete->mInsertEndIdx = nameNode->GetSrcEnd();
  5310. if (nameIdx != 0)
  5311. {
  5312. bfAutocomplete->AddEntry(AutoCompleteEntry("generic", nameNode->ToString().c_str()), filter);
  5313. }
  5314. }
  5315. }
  5316. }
  5317. for (auto constraint : constraintDef->mConstraints)
  5318. {
  5319. if (auto opConstraint = BfNodeDynCast<BfGenericOperatorConstraint>(constraint))
  5320. {
  5321. BfGenericOperatorConstraintInstance opConstraintInstance;
  5322. if (opConstraint->mLeftType != NULL)
  5323. {
  5324. if (bfAutocomplete != NULL)
  5325. bfAutocomplete->CheckTypeRef(opConstraint->mLeftType, false);
  5326. opConstraintInstance.mLeftType = ResolveTypeRef(opConstraint->mLeftType);
  5327. if (opConstraintInstance.mLeftType == NULL)
  5328. continue;
  5329. }
  5330. if (opConstraint->mRightType == NULL)
  5331. {
  5332. // We had a failure in parsing
  5333. continue;
  5334. }
  5335. if (opConstraint->mRightType != NULL)
  5336. {
  5337. if (bfAutocomplete != NULL)
  5338. bfAutocomplete->CheckTypeRef(opConstraint->mRightType, false);
  5339. opConstraintInstance.mRightType = ResolveTypeRef(opConstraint->mRightType);
  5340. if (opConstraintInstance.mRightType == NULL)
  5341. continue;
  5342. }
  5343. if (opConstraint->mOpToken == NULL)
  5344. {
  5345. FailAfter("Missing operator", (opConstraint->mLeftType != NULL) ? (BfAstNode*)opConstraint->mLeftType : (BfAstNode*)opConstraint->mOperatorToken);
  5346. continue;
  5347. }
  5348. if (opConstraint->mLeftType != NULL)
  5349. {
  5350. if (opConstraint->mRightType == NULL)
  5351. {
  5352. // Parse should have failed
  5353. continue;
  5354. }
  5355. opConstraintInstance.mBinaryOp = BfTokenToBinaryOp(opConstraint->mOpToken->mToken);
  5356. if (opConstraintInstance.mBinaryOp == BfBinaryOp_None)
  5357. {
  5358. Fail("Invalid binary operator", opConstraint->mOpToken);
  5359. continue;
  5360. }
  5361. }
  5362. else if ((opConstraint->mOpToken->mToken == BfToken_Implicit) || (opConstraint->mOpToken->mToken == BfToken_Explicit))
  5363. {
  5364. opConstraintInstance.mCastToken = opConstraint->mOpToken->mToken;
  5365. }
  5366. else
  5367. {
  5368. opConstraintInstance.mUnaryOp = BfTokenToUnaryOp(opConstraint->mOpToken->mToken);
  5369. if (opConstraintInstance.mUnaryOp == BfUnaryOp_None)
  5370. {
  5371. Fail("Invalid unary operator", opConstraint->mOpToken);
  5372. continue;
  5373. }
  5374. }
  5375. if ((constraintDef->mGenericParamFlags & BfGenericParamFlag_Equals) != 0)
  5376. genericParamInstance->mGenericParamFlags = (BfGenericParamFlags)(genericParamInstance->mGenericParamFlags | BfGenericParamFlag_Equals_Op);
  5377. genericParamInstance->mOperatorConstraints.Add(opConstraintInstance);
  5378. continue;
  5379. }
  5380. auto constraintTypeRef = BfNodeDynCast<BfTypeReference>(constraint);
  5381. if (bfAutocomplete != NULL)
  5382. bfAutocomplete->CheckTypeRef(constraintTypeRef, true);
  5383. //TODO: Constraints may refer to other generic params (of either type or method)
  5384. // TO allow resolution, perhaps move this generic param initalization into GetMethodInstance (passing a genericPass bool)
  5385. auto constraintType = ResolveTypeRef(constraintTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_AllowGenericMethodParamConstValue);
  5386. if (constraintType != NULL)
  5387. {
  5388. if ((constraintDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  5389. {
  5390. bool isValidTypeCode = false;
  5391. BfTypeCode typeCode = BfTypeCode_None;
  5392. if (constraintType->IsTypedPrimitive())
  5393. {
  5394. auto underlyingType = constraintType->GetUnderlyingType();
  5395. if (underlyingType->IsPrimitiveType())
  5396. typeCode = ((BfPrimitiveType*)underlyingType)->mTypeDef->mTypeCode;
  5397. }
  5398. if (constraintType->IsPrimitiveType())
  5399. typeCode = ((BfPrimitiveType*)constraintType)->mTypeDef->mTypeCode;
  5400. switch (typeCode)
  5401. {
  5402. case BfTypeCode_Int8:
  5403. case BfTypeCode_UInt8:
  5404. case BfTypeCode_Int16:
  5405. case BfTypeCode_UInt16:
  5406. case BfTypeCode_Int32:
  5407. case BfTypeCode_UInt32:
  5408. case BfTypeCode_Int64:
  5409. case BfTypeCode_UInt64:
  5410. case BfTypeCode_IntPtr:
  5411. case BfTypeCode_UIntPtr:
  5412. case BfTypeCode_IntUnknown:
  5413. case BfTypeCode_UIntUnknown:
  5414. case BfTypeCode_Single:
  5415. case BfTypeCode_Double:
  5416. case BfTypeCode_Char8:
  5417. case BfTypeCode_Char16:
  5418. case BfTypeCode_Char32:
  5419. isValidTypeCode = true;
  5420. break;
  5421. default: break;
  5422. }
  5423. if (isValidTypeCode)
  5424. {
  5425. genericParamInstance->mTypeConstraint = constraintType;
  5426. }
  5427. else
  5428. {
  5429. Fail("Const constraint must be a primitive type", constraintTypeRef);
  5430. }
  5431. }
  5432. else
  5433. {
  5434. bool checkEquality = false;
  5435. if (constraintType->IsPrimitiveType())
  5436. {
  5437. if (isUnspecialized)
  5438. {
  5439. Fail("Primitive constraints are not allowed unless preceded with 'const'", constraintTypeRef);
  5440. continue;
  5441. }
  5442. checkEquality = true;
  5443. }
  5444. if (constraintType->IsArray())
  5445. {
  5446. if (isUnspecialized)
  5447. {
  5448. 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);
  5449. continue;
  5450. }
  5451. checkEquality = true;
  5452. }
  5453. if (constraintType->IsGenericParam())
  5454. {
  5455. continue;
  5456. }
  5457. if ((!constraintType->IsTypeInstance()) && (!constraintType->IsSizedArray()))
  5458. {
  5459. if (isUnspecialized)
  5460. {
  5461. Fail(StrFormat("Type '%s' is not allowed as a generic constraint", TypeToString(constraintType).c_str()), constraintTypeRef);
  5462. continue;
  5463. }
  5464. checkEquality = true;
  5465. }
  5466. if ((constraintDef->mGenericParamFlags & BfGenericParamFlag_Equals) != 0)
  5467. {
  5468. genericParamInstance->mGenericParamFlags = (BfGenericParamFlags)(genericParamInstance->mGenericParamFlags | BfGenericParamFlag_Equals_Type);
  5469. checkEquality = true;
  5470. }
  5471. if (checkEquality)
  5472. {
  5473. genericParamInstance->mTypeConstraint = constraintType;
  5474. }
  5475. else if (constraintType->IsInterface())
  5476. {
  5477. if ((constraintDef->mGenericParamFlags & BfGenericParamFlag_Equals) != 0)
  5478. genericParamInstance->mGenericParamFlags = (BfGenericParamFlags)(genericParamInstance->mGenericParamFlags | BfGenericParamFlag_Equals_IFace);
  5479. genericParamInstance->mInterfaceConstraints.push_back(constraintType->ToTypeInstance());
  5480. }
  5481. else
  5482. {
  5483. auto constraintTypeInst = constraintType->ToTypeInstance();
  5484. if (genericParamInstance->mTypeConstraint != NULL)
  5485. {
  5486. if ((constraintTypeInst != NULL) && (TypeIsSubTypeOf(constraintTypeInst, genericParamInstance->mTypeConstraint->ToTypeInstance(), false)))
  5487. {
  5488. // Allow more specific type
  5489. genericParamInstance->mTypeConstraint = constraintTypeInst;
  5490. }
  5491. else if ((constraintTypeInst != NULL) && (TypeIsSubTypeOf(genericParamInstance->mTypeConstraint->ToTypeInstance(), constraintTypeInst, false)))
  5492. {
  5493. // Silently ignore less-specific type
  5494. if ((startingTypeConstraint != NULL) && (startingTypeConstraint->IsDelegate()))
  5495. {
  5496. // 'System.Delegate' means that we are expecting an actual delegate instance. Simulate this by wanting a class.
  5497. genericParamInstance->mGenericParamFlags |= BfGenericParamFlag_Class;
  5498. }
  5499. }
  5500. else
  5501. {
  5502. Fail("Only one concrete type constraint may be specified", constraintTypeRef);
  5503. return;
  5504. }
  5505. }
  5506. else
  5507. genericParamInstance->mTypeConstraint = constraintType;
  5508. }
  5509. }
  5510. }
  5511. }
  5512. if (((constraintDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0) &&
  5513. (genericParamInstance->mTypeConstraint == NULL))
  5514. genericParamInstance->mTypeConstraint = GetPrimitiveType(BfTypeCode_IntPtr);
  5515. }
  5516. String BfModule::GenericParamSourceToString(const BfGenericParamSource & genericParamSource)
  5517. {
  5518. if (genericParamSource.mMethodInstance != NULL)
  5519. {
  5520. auto methodInst = GetUnspecializedMethodInstance(genericParamSource.mMethodInstance);
  5521. SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, methodInst);
  5522. return MethodToString(methodInst);
  5523. }
  5524. else
  5525. {
  5526. auto typeInst = GetUnspecializedTypeInstance(genericParamSource.mTypeInstance);
  5527. SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, NULL);
  5528. SetAndRestoreValue<BfTypeInstance*> prevTypeInst(mCurTypeInstance, typeInst);
  5529. return TypeToString(typeInst);
  5530. }
  5531. }
  5532. bool BfModule::CheckGenericConstraints(const BfGenericParamSource& genericParamSource, BfType* checkArgType, BfAstNode* checkArgTypeRef, BfGenericParamInstance* genericParamInst, BfTypeVector* methodGenericArgs, BfError** errorOut)
  5533. {
  5534. bool ignoreErrors = mIgnoreErrors || (errorOut == NULL) ||
  5535. ((genericParamSource.mMethodInstance == NULL) && (genericParamSource.mTypeInstance == NULL));
  5536. BfType* origCheckArgType = checkArgType;
  5537. if (origCheckArgType->IsRef())
  5538. origCheckArgType = origCheckArgType->GetUnderlyingType();
  5539. bool argMayBeReferenceType = false;
  5540. int checkGenericParamFlags = 0;
  5541. if (checkArgType->IsGenericParam())
  5542. {
  5543. auto checkGenericParamInst = GetGenericParamInstance((BfGenericParamType*)checkArgType);
  5544. checkGenericParamFlags = checkGenericParamInst->mGenericParamFlags;
  5545. if (checkGenericParamInst->mTypeConstraint != NULL)
  5546. checkArgType = checkGenericParamInst->mTypeConstraint;
  5547. if ((checkGenericParamFlags & (BfGenericParamFlag_Struct | BfGenericParamFlag_StructPtr)) != 0)
  5548. {
  5549. argMayBeReferenceType = false;
  5550. }
  5551. else
  5552. {
  5553. argMayBeReferenceType = true;
  5554. }
  5555. }
  5556. if (checkArgType->IsObjectOrInterface())
  5557. argMayBeReferenceType = true;
  5558. BfTypeInstance* typeConstraintInst = NULL;
  5559. if (genericParamInst->mTypeConstraint != NULL)
  5560. typeConstraintInst = genericParamInst->mTypeConstraint->ToTypeInstance();
  5561. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Struct) &&
  5562. ((checkGenericParamFlags & (BfGenericParamFlag_Struct | BfGenericParamFlag_Var)) == 0) && (!checkArgType->IsValueType()))
  5563. {
  5564. if (!ignoreErrors)
  5565. *errorOut = Fail(StrFormat("The type '%s' must be a value type in order to use it as parameter '%s' for '%s'",
  5566. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5567. return false;
  5568. }
  5569. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_StructPtr) &&
  5570. ((checkGenericParamFlags & (BfGenericParamFlag_StructPtr | BfGenericParamFlag_Var)) == 0) && (!checkArgType->IsPointer()))
  5571. {
  5572. if (!ignoreErrors)
  5573. *errorOut = Fail(StrFormat("The type '%s' must be a pointer type in order to use it as parameter '%s' for '%s'",
  5574. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5575. return false;
  5576. }
  5577. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Class) &&
  5578. ((checkGenericParamFlags & (BfGenericParamFlag_Class | BfGenericParamFlag_Var)) == 0) && (!argMayBeReferenceType))
  5579. {
  5580. if (!ignoreErrors)
  5581. *errorOut = Fail(StrFormat("The type '%s' must be a reference type in order to use it as parameter '%s' for '%s'",
  5582. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5583. return false;
  5584. }
  5585. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  5586. {
  5587. if (((checkGenericParamFlags & BfGenericParamFlag_Const) == 0) && (!checkArgType->IsConstExprValue()))
  5588. {
  5589. if (!ignoreErrors)
  5590. *errorOut = Fail(StrFormat("The type '%s' must be a const value in order to use it as parameter '%s' for '%s'",
  5591. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5592. return false;
  5593. }
  5594. }
  5595. else
  5596. {
  5597. if (checkArgType->IsConstExprValue())
  5598. {
  5599. if (!ignoreErrors)
  5600. *errorOut = Fail(StrFormat("The value '%s' cannot be used for generic type parameter '%s' for '%s'",
  5601. TypeToString(origCheckArgType).c_str(), genericParamInst->GetName().c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5602. return false;
  5603. }
  5604. }
  5605. if ((genericParamInst->mInterfaceConstraints.IsEmpty()) && (genericParamInst->mOperatorConstraints.IsEmpty()) && (genericParamInst->mTypeConstraint == NULL))
  5606. return true;
  5607. if (checkArgType->IsPointer())
  5608. {
  5609. auto ptrType = (BfPointerType*)checkArgType;
  5610. checkArgType = ptrType->mElementType;
  5611. }
  5612. if (genericParamInst->mTypeConstraint != NULL)
  5613. {
  5614. bool constraintMatched = false;
  5615. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  5616. {
  5617. if (checkArgType->IsConstExprValue())
  5618. {
  5619. auto constExprValueType = (BfConstExprValueType*)checkArgType;
  5620. if (genericParamInst->mTypeConstraint->IsPrimitiveType())
  5621. {
  5622. auto primType = (BfPrimitiveType*)genericParamInst->mTypeConstraint;
  5623. // Let either an exact typematch or an undef pass through. Eventually instead of undefs we may want to do
  5624. // actual expression comparisons, but we are overly permissive now and then we may fail on specialization
  5625. if ((constExprValueType->mValue.mTypeCode != primType->mTypeDef->mTypeCode) &&
  5626. (constExprValueType->mValue.mTypeCode != BfTypeCode_Let) &&
  5627. (primType->mTypeDef->mTypeCode != BfTypeCode_Let))
  5628. {
  5629. if (BfIRConstHolder::IsInt(constExprValueType->mValue.mTypeCode))
  5630. {
  5631. if (BfIRConstHolder::IsInt(primType->mTypeDef->mTypeCode))
  5632. {
  5633. if (!mCompiler->mSystem->DoesLiteralFit(primType->mTypeDef->mTypeCode, constExprValueType->mValue.mInt64))
  5634. {
  5635. if (!ignoreErrors)
  5636. *errorOut = Fail(StrFormat("Const generic argument '%s', declared with const '%lld', does not fit into const constraint '%s' for '%s'", genericParamInst->GetName().c_str(),
  5637. constExprValueType->mValue.mInt64, TypeToString(genericParamInst->mTypeConstraint).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5638. return false;
  5639. }
  5640. }
  5641. else
  5642. {
  5643. if (!ignoreErrors)
  5644. *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(),
  5645. constExprValueType->mValue.mInt64, TypeToString(genericParamInst->mTypeConstraint).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5646. return false;
  5647. }
  5648. }
  5649. else
  5650. {
  5651. if (BfIRConstHolder::IsInt(primType->mTypeDef->mTypeCode))
  5652. {
  5653. char valStr[64];
  5654. ExactMinimalDoubleToStr(constExprValueType->mValue.mDouble, valStr);
  5655. if (!ignoreErrors)
  5656. *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(),
  5657. valStr, TypeToString(genericParamInst->mTypeConstraint).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5658. return false;
  5659. }
  5660. }
  5661. }
  5662. }
  5663. }
  5664. }
  5665. else
  5666. {
  5667. BfType* convCheckConstraint = genericParamInst->mTypeConstraint;
  5668. if ((convCheckConstraint->IsUnspecializedType()) && (methodGenericArgs != NULL))
  5669. convCheckConstraint = ResolveGenericType(convCheckConstraint, *methodGenericArgs);
  5670. if ((checkArgType->IsMethodRef()) && (convCheckConstraint->IsDelegate()))
  5671. {
  5672. auto methodRefType = (BfMethodRefType*)checkArgType;
  5673. auto invokeMethod = GetRawMethodInstanceAtIdx(convCheckConstraint->ToTypeInstance(), 0, "Invoke");
  5674. BfExprEvaluator exprEvaluator(this);
  5675. if (exprEvaluator.IsExactMethodMatch(methodRefType->mMethodRef, invokeMethod))
  5676. constraintMatched = true;
  5677. }
  5678. else if (CanImplicitlyCast(GetFakeTypedValue(checkArgType), convCheckConstraint))
  5679. {
  5680. constraintMatched = true;
  5681. }
  5682. else if (origCheckArgType->IsWrappableType())
  5683. {
  5684. if (origCheckArgType->IsSizedArray())
  5685. {
  5686. auto sizedArrayType = (BfSizedArrayType*)origCheckArgType;
  5687. if (convCheckConstraint->IsGenericTypeInstance())
  5688. {
  5689. auto convCheckConstraintInst = (BfGenericTypeInstance*)convCheckConstraint;
  5690. if (convCheckConstraintInst->mTypeDef == mCompiler->mSizedArrayTypeDef)
  5691. {
  5692. if (convCheckConstraintInst->mTypeGenericArguments[0] == sizedArrayType->mElementType)
  5693. {
  5694. auto constExprValueType = (BfConstExprValueType*)convCheckConstraintInst->mTypeGenericArguments[1];
  5695. if (sizedArrayType->mElementCount == constExprValueType->mValue.mInt64)
  5696. constraintMatched = true;
  5697. }
  5698. }
  5699. }
  5700. }
  5701. if (!constraintMatched)
  5702. {
  5703. BfType* wrappedStructType = GetWrappedStructType(origCheckArgType, false);
  5704. if (CanImplicitlyCast(GetFakeTypedValue(wrappedStructType), convCheckConstraint))
  5705. constraintMatched = true;
  5706. }
  5707. }
  5708. if (!constraintMatched)
  5709. {
  5710. if (!ignoreErrors)
  5711. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must derive from '%s'", genericParamInst->GetName().c_str(),
  5712. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(), TypeToString(convCheckConstraint).c_str(),
  5713. TypeToString(genericParamInst->mTypeConstraint).c_str()), checkArgTypeRef);
  5714. return false;
  5715. }
  5716. }
  5717. }
  5718. if ((genericParamInst->mInterfaceConstraints.size() > 0) && (origCheckArgType->IsInterface()))
  5719. {
  5720. PopulateType(origCheckArgType);
  5721. auto checkTypeInst = origCheckArgType->ToTypeInstance();
  5722. if (checkTypeInst->mTypeDef->mIsConcrete)
  5723. {
  5724. if (!ignoreErrors)
  5725. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be concrete interface '%s' for '%s', must be a concrete type", genericParamInst->GetName().c_str(),
  5726. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str()), checkArgTypeRef);
  5727. return false;
  5728. }
  5729. }
  5730. for (auto checkConstraint : genericParamInst->mInterfaceConstraints)
  5731. {
  5732. BfType* convCheckConstraint = checkConstraint;
  5733. if (convCheckConstraint->IsUnspecializedType())
  5734. convCheckConstraint = ResolveGenericType(convCheckConstraint, *methodGenericArgs);
  5735. BfTypeInstance* typeConstraintInst = convCheckConstraint->ToTypeInstance();
  5736. bool implementsInterface = false;
  5737. if (origCheckArgType != checkArgType)
  5738. {
  5739. implementsInterface = CanImplicitlyCast(BfTypedValue(BfIRValue::sValueless, origCheckArgType), convCheckConstraint);
  5740. }
  5741. if (!implementsInterface)
  5742. implementsInterface = CanImplicitlyCast(BfTypedValue(BfIRValue::sValueless, checkArgType), convCheckConstraint);
  5743. if ((!implementsInterface) && (origCheckArgType->IsWrappableType()))
  5744. {
  5745. BfTypeInstance* wrappedStructType = GetWrappedStructType(origCheckArgType, false);
  5746. if (TypeIsSubTypeOf(wrappedStructType, typeConstraintInst))
  5747. implementsInterface = true;
  5748. }
  5749. if ((!implementsInterface) && (origCheckArgType->IsTypedPrimitive()))
  5750. {
  5751. auto underlyingType = origCheckArgType->GetUnderlyingType();
  5752. BfTypeInstance* wrappedStructType = GetWrappedStructType(underlyingType, false);
  5753. if (TypeIsSubTypeOf(wrappedStructType, typeConstraintInst))
  5754. implementsInterface = true;
  5755. }
  5756. if (!implementsInterface)
  5757. {
  5758. if (!ignoreErrors)
  5759. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must implement '%s'", genericParamInst->GetName().c_str(),
  5760. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(), TypeToString(checkConstraint).c_str()), checkArgTypeRef);
  5761. return false;
  5762. }
  5763. }
  5764. for (auto& checkOpConstraint : genericParamInst->mOperatorConstraints)
  5765. {
  5766. auto leftType = checkOpConstraint.mLeftType;
  5767. if ((leftType != NULL) && (leftType->IsUnspecializedType()))
  5768. leftType = ResolveGenericType(leftType, *methodGenericArgs);
  5769. if (leftType != NULL)
  5770. leftType = FixIntUnknown(leftType);
  5771. auto rightType = checkOpConstraint.mRightType;
  5772. if ((rightType != NULL) && (rightType->IsUnspecializedType()))
  5773. rightType = ResolveGenericType(rightType, *methodGenericArgs);
  5774. if (rightType != NULL)
  5775. rightType = FixIntUnknown(rightType);
  5776. BfConstraintState constraintSet;
  5777. constraintSet.mPrevState = mContext->mCurConstraintState;
  5778. constraintSet.mGenericParamInstance = genericParamInst;
  5779. constraintSet.mLeftType = leftType;
  5780. constraintSet.mRightType = rightType;
  5781. SetAndRestoreValue<BfConstraintState*> prevConstraintSet(mContext->mCurConstraintState, &constraintSet);
  5782. if (!CheckConstraintState(NULL))
  5783. return false;
  5784. if (checkOpConstraint.mBinaryOp != BfBinaryOp_None)
  5785. {
  5786. BfExprEvaluator exprEvaluator(this);
  5787. BfTypedValue leftValue(mBfIRBuilder->GetFakeVal(), leftType);
  5788. BfTypedValue rightValue(mBfIRBuilder->GetFakeVal(), rightType);
  5789. //
  5790. {
  5791. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  5792. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  5793. exprEvaluator.PerformBinaryOperation(NULL, NULL, checkOpConstraint.mBinaryOp, NULL, BfBinOpFlag_NoClassify, leftValue, rightValue);
  5794. }
  5795. if ((!exprEvaluator.mResult) ||
  5796. (!CanImplicitlyCast(exprEvaluator.mResult, origCheckArgType)))
  5797. {
  5798. if (!ignoreErrors)
  5799. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must result from binary operation '%s %s %s'", genericParamInst->GetName().c_str(),
  5800. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(),
  5801. TypeToString(leftType).c_str(), BfGetOpName(checkOpConstraint.mBinaryOp), TypeToString(rightType).c_str()
  5802. ), checkArgTypeRef);
  5803. return false;
  5804. }
  5805. }
  5806. else
  5807. {
  5808. BfTypedValue rightValue(mBfIRBuilder->GetFakeVal(), rightType);
  5809. StringT<128> failedOpName;
  5810. if (checkOpConstraint.mCastToken == BfToken_Implicit)
  5811. {
  5812. if (!CanImplicitlyCast(rightValue, origCheckArgType, BfCastFlags_SilentFail))
  5813. failedOpName = "implicit conversion from '";
  5814. }
  5815. else
  5816. {
  5817. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  5818. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  5819. if (checkOpConstraint.mCastToken == BfToken_Explicit)
  5820. {
  5821. if (!CastToValue(NULL, rightValue, origCheckArgType, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_SilentFail)))
  5822. failedOpName = "explicit conversion from '";
  5823. }
  5824. else
  5825. {
  5826. BfExprEvaluator exprEvaluator(this);
  5827. exprEvaluator.mResult = rightValue;
  5828. exprEvaluator.PerformUnaryOperation(NULL, checkOpConstraint.mUnaryOp, NULL);
  5829. if ((!exprEvaluator.mResult) ||
  5830. (!CanImplicitlyCast(exprEvaluator.mResult, origCheckArgType)))
  5831. {
  5832. failedOpName += "unary operation '";
  5833. failedOpName += BfGetOpName(checkOpConstraint.mUnaryOp);
  5834. }
  5835. }
  5836. }
  5837. if (!failedOpName.IsEmpty())
  5838. {
  5839. if (!ignoreErrors)
  5840. *errorOut = Fail(StrFormat("Generic argument '%s', declared to be '%s' for '%s', must result from %s%s'", genericParamInst->GetName().c_str(),
  5841. TypeToString(origCheckArgType).c_str(), GenericParamSourceToString(genericParamSource).c_str(),
  5842. failedOpName.c_str(), TypeToString(rightType).c_str()
  5843. ), checkArgTypeRef);
  5844. return false;
  5845. }
  5846. }
  5847. }
  5848. return true;
  5849. }
  5850. BfGenericParamType* BfModule::GetGenericParamType(BfGenericParamKind paramKind, int paramIdx)
  5851. {
  5852. if (paramIdx < (int)mContext->mGenericParamTypes[paramKind].size())
  5853. {
  5854. auto genericParamType = mContext->mGenericParamTypes[paramKind][paramIdx];
  5855. return genericParamType;
  5856. }
  5857. auto genericParamType = new BfGenericParamType();
  5858. genericParamType->mContext = mContext;
  5859. genericParamType->mGenericParamKind = paramKind;
  5860. genericParamType->mGenericParamIdx = paramIdx;
  5861. PopulateType(genericParamType);
  5862. BF_ASSERT(paramIdx == (int)mContext->mGenericParamTypes[paramKind].size());
  5863. mContext->mGenericParamTypes[paramKind].push_back(genericParamType);
  5864. BfResolvedTypeSet::LookupContext lookupCtx;
  5865. lookupCtx.mModule = this;
  5866. BfResolvedTypeSet::Entry* typeEntry = NULL;
  5867. auto inserted = mContext->mResolvedTypes.Insert(genericParamType, &lookupCtx, &typeEntry);
  5868. BF_ASSERT(inserted);
  5869. typeEntry->mValue = genericParamType;
  5870. return genericParamType;
  5871. }
  5872. static int sValueFromExprIdx = 0;
  5873. BfTypedValue BfModule::FlushNullConditional(BfTypedValue result, bool ignoreNullable)
  5874. {
  5875. auto pendingNullCond = mCurMethodState->mPendingNullConditional;
  5876. if ((result) && (!ignoreNullable))
  5877. {
  5878. auto notNullBB = mBfIRBuilder->GetInsertBlock();
  5879. //TODO: Make this work, needed for 'void' and such
  5880. BfType* nullableType = NULL;
  5881. if ((result.mType->IsValueType()) && (!result.mType->IsNullable()))
  5882. {
  5883. BfTypeVector typeVec;
  5884. typeVec.push_back(result.mType);
  5885. nullableType = ResolveTypeDef(mCompiler->mNullableTypeDef, typeVec);
  5886. BF_ASSERT(nullableType != NULL);
  5887. }
  5888. // Go back to start and do any setup we need
  5889. mBfIRBuilder->SetInsertPoint(pendingNullCond->mPrevBB);
  5890. BfTypedValue nullableTypedValue;
  5891. if (nullableType != NULL)
  5892. {
  5893. nullableTypedValue = BfTypedValue(CreateAlloca(nullableType, true, "nullCond.nullable"), nullableType, true);
  5894. mBfIRBuilder->CreateMemSet(nullableTypedValue.mValue, GetConstValue(0, GetPrimitiveType(BfTypeCode_Int8)),
  5895. GetConstValue(nullableType->mSize), nullableType->mAlign);
  5896. }
  5897. mBfIRBuilder->CreateBr(pendingNullCond->mCheckBB);
  5898. // Now that we have the nullableTypedValue we can set that, or just jump if we didn't need it
  5899. mBfIRBuilder->SetInsertPoint(notNullBB);
  5900. result = LoadValue(result);
  5901. if (nullableTypedValue)
  5902. {
  5903. auto elementType = nullableType->GetUnderlyingType();
  5904. if (elementType->IsValuelessType())
  5905. {
  5906. BfIRValue ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 1); // mHasValue
  5907. mBfIRBuilder->CreateStore(GetConstValue(1, GetPrimitiveType(BfTypeCode_Boolean)), ptrValue);
  5908. result = nullableTypedValue;
  5909. }
  5910. else
  5911. {
  5912. BfIRValue ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 1); // mValue
  5913. mBfIRBuilder->CreateStore(result.mValue, ptrValue);
  5914. ptrValue = mBfIRBuilder->CreateInBoundsGEP(nullableTypedValue.mValue, 0, 2); // mHasValue
  5915. mBfIRBuilder->CreateStore(GetConstValue(1, GetPrimitiveType(BfTypeCode_Boolean)), ptrValue);
  5916. result = nullableTypedValue;
  5917. }
  5918. }
  5919. mBfIRBuilder->CreateBr(pendingNullCond->mDoneBB);
  5920. AddBasicBlock(pendingNullCond->mDoneBB);
  5921. if (nullableType == NULL)
  5922. {
  5923. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapType(result.mType), 2);
  5924. mBfIRBuilder->AddPhiIncoming(phi, result.mValue, notNullBB);
  5925. mBfIRBuilder->AddPhiIncoming(phi, GetDefaultValue(result.mType), pendingNullCond->mCheckBB);
  5926. result.mValue = phi;
  5927. }
  5928. }
  5929. else
  5930. {
  5931. mBfIRBuilder->CreateBr(pendingNullCond->mDoneBB);
  5932. mBfIRBuilder->SetInsertPoint(pendingNullCond->mPrevBB);
  5933. mBfIRBuilder->CreateBr(pendingNullCond->mCheckBB);
  5934. AddBasicBlock(pendingNullCond->mDoneBB);
  5935. }
  5936. delete mCurMethodState->mPendingNullConditional;
  5937. mCurMethodState->mPendingNullConditional = NULL;
  5938. return result;
  5939. }
  5940. BF_NOINLINE void BfModule::EvaluateWithNewScope(BfExprEvaluator& exprEvaluator, BfExpression* expr, BfEvalExprFlags flags)
  5941. {
  5942. BfScopeData newScope;
  5943. newScope.mOuterIsConditional = true;
  5944. newScope.mAllowTargeting = false;
  5945. mCurMethodState->AddScope(&newScope);
  5946. NewScopeState();
  5947. exprEvaluator.mBfEvalExprFlags = flags;
  5948. exprEvaluator.Evaluate(expr, (flags & BfEvalExprFlags_PropogateNullConditional) != 0, (flags & BfEvalExprFlags_IgnoreNullConditional) != 0, true);
  5949. RestoreScopeState();
  5950. }
  5951. BfTypedValue BfModule::CreateValueFromExpression(BfExprEvaluator& exprEvaluator, BfExpression* expr, BfType* wantTypeRef, BfEvalExprFlags flags, BfType** outOrigType)
  5952. {
  5953. //
  5954. {
  5955. BP_ZONE("CreateValueFromExpression:CheckStack");
  5956. StackHelper stackHelper;
  5957. if (!stackHelper.CanStackExpand(64 * 1024))
  5958. {
  5959. BfTypedValue result;
  5960. if (!stackHelper.Execute([&]()
  5961. {
  5962. result = CreateValueFromExpression(exprEvaluator, expr, wantTypeRef, flags, outOrigType);
  5963. }))
  5964. {
  5965. Fail("Expression too complex to compile", expr);
  5966. }
  5967. return result;
  5968. }
  5969. }
  5970. BP_ZONE("BfModule::CreateValueFromExpression");
  5971. if (outOrigType != NULL)
  5972. *outOrigType = NULL;
  5973. exprEvaluator.mExpectingType = wantTypeRef;
  5974. exprEvaluator.mBfEvalExprFlags = flags;
  5975. exprEvaluator.mExplicitCast = (flags & BfEvalExprFlags_ExplicitCast) != 0;
  5976. if ((flags & BfEvalExprFlags_CreateConditionalScope) != 0)
  5977. {
  5978. EvaluateWithNewScope(exprEvaluator, expr, flags);
  5979. }
  5980. else
  5981. exprEvaluator.Evaluate(expr, (flags & BfEvalExprFlags_PropogateNullConditional) != 0, (flags & BfEvalExprFlags_IgnoreNullConditional) != 0, true);
  5982. if (!exprEvaluator.mResult)
  5983. {
  5984. if (!mCompiler->mPassInstance->HasFailed())
  5985. Fail("INTERNAL ERROR: No expression result returned but no error caught in expression evaluator", expr);
  5986. return BfTypedValue();
  5987. }
  5988. auto typedVal = exprEvaluator.mResult;
  5989. if (typedVal.mKind == BfTypedValueKind_GenericConstValue)
  5990. {
  5991. BF_ASSERT(typedVal.mType->IsGenericParam());
  5992. auto genericParamDef = GetGenericParamInstance((BfGenericParamType*)typedVal.mType);
  5993. bool handled = false;
  5994. if ((genericParamDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  5995. {
  5996. auto genericTypeConstraint = genericParamDef->mTypeConstraint;
  5997. if (genericTypeConstraint != NULL)
  5998. {
  5999. auto primType = genericTypeConstraint->ToPrimitiveType();
  6000. if (primType != NULL)
  6001. {
  6002. BfTypedValue result;
  6003. result.mKind = BfTypedValueKind_Value;
  6004. result.mType = genericTypeConstraint;
  6005. result.mValue = mBfIRBuilder->GetUndefConstValue(primType->mTypeDef->mTypeCode);
  6006. typedVal = result;
  6007. handled = true;
  6008. }
  6009. }
  6010. }
  6011. if (!handled)
  6012. {
  6013. //Fail("Only const generic parameters can be used as values", expr);
  6014. AssertErrorState();
  6015. return BfTypedValue();
  6016. }
  6017. }
  6018. if ((flags & BfEvalExprFlags_AllowIntUnknown) == 0)
  6019. FixIntUnknown(typedVal);
  6020. exprEvaluator.CheckResultForReading(typedVal);
  6021. if ((wantTypeRef == NULL) || (!wantTypeRef->IsRef()))
  6022. {
  6023. if ((flags & BfEvalExprFlags_NoCast) == 0)
  6024. {
  6025. // Only allow a 'ref' type if we have an explicit 'ref' operator
  6026. bool allowRef = false;
  6027. BfExpression* checkExpr = expr;
  6028. while (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(checkExpr))
  6029. checkExpr = parenExpr->mExpression;
  6030. if (auto unaryOp = BfNodeDynCast<BfUnaryOperatorExpression>(checkExpr))
  6031. {
  6032. if ((unaryOp->mOp == BfUnaryOp_Ref) || (unaryOp->mOp == BfUnaryOp_Mut))
  6033. allowRef = true;
  6034. }
  6035. if (!allowRef)
  6036. typedVal = RemoveRef(typedVal);
  6037. }
  6038. }
  6039. if (!typedVal.mType->IsComposite()) // Load non-structs by default
  6040. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  6041. if (wantTypeRef != NULL)
  6042. {
  6043. if (outOrigType != NULL)
  6044. *outOrigType = typedVal.mType;
  6045. if ((flags & BfEvalExprFlags_NoCast) == 0)
  6046. {
  6047. BfCastFlags castFlags = ((flags & BfEvalExprFlags_ExplicitCast) != 0) ? BfCastFlags_Explicit : BfCastFlags_None;
  6048. if ((flags & BfEvalExprFlags_FieldInitializer) != 0)
  6049. castFlags = (BfCastFlags)(castFlags | BfCastFlags_WarnOnBox);
  6050. typedVal = Cast(expr, typedVal, wantTypeRef, castFlags);
  6051. if (!typedVal)
  6052. return typedVal;
  6053. }
  6054. //WTF- why did we have this?
  6055. /*if ((flags & BfEvalExprFlags_ExplicitCast) == 0)
  6056. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);*/
  6057. if (exprEvaluator.mIsVolatileReference)
  6058. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  6059. }
  6060. // if ((typedVal.IsSplat()) && ((flags & BfEvalExprFlags_AllowSplat) == 0))
  6061. // typedVal = MakeAddressable(typedVal);
  6062. //typedVal = AggregateSplat(typedVal);
  6063. if ((typedVal.mType->IsValueType()) && ((flags & BfEvalExprFlags_NoValueAddr) != 0))
  6064. typedVal = LoadValue(typedVal, 0, exprEvaluator.mIsVolatileReference);
  6065. return typedVal;
  6066. }
  6067. BfTypedValue BfModule::CreateValueFromExpression(BfExpression* expr, BfType* wantTypeRef, BfEvalExprFlags flags, BfType** outOrigType)
  6068. {
  6069. BfExprEvaluator exprEvaluator(this);
  6070. return CreateValueFromExpression(exprEvaluator, expr, wantTypeRef, flags, outOrigType);
  6071. }
  6072. BfTypedValue BfModule::GetOrCreateVarAddr(BfExpression* expr)
  6073. {
  6074. BfExprEvaluator exprEvaluator(this);
  6075. exprEvaluator.Evaluate(expr);
  6076. if (!exprEvaluator.mResult)
  6077. {
  6078. Fail("Invalid expression type", expr);
  6079. return BfTypedValue();
  6080. }
  6081. if (!exprEvaluator.mResult.IsAddr())
  6082. {
  6083. Fail("Cannot assign to value", expr);
  6084. return BfTypedValue();
  6085. }
  6086. return exprEvaluator.mResult;
  6087. }
  6088. // Clear memory, set classVData, call init. Actual ctor is called elsewhere.
  6089. void BfModule::InitTypeInst(BfTypedValue typedValue, BfScopeData* scopeData, bool zeroMemory, BfIRValue sizeValue)
  6090. {
  6091. auto typeInstance = typedValue.mType->ToTypeInstance();
  6092. if (zeroMemory)
  6093. {
  6094. int zeroAlign = typedValue.mType->mAlign;
  6095. if (typeInstance != NULL)
  6096. zeroAlign = typeInstance->mInstAlign;
  6097. mBfIRBuilder->CreateMemSet(typedValue.mValue, GetConstValue8(0), sizeValue, zeroAlign);
  6098. }
  6099. if (!typedValue.mType->IsObject())
  6100. {
  6101. return;
  6102. }
  6103. if ((scopeData == NULL) && (mCurMethodState != NULL))
  6104. return; // Handled in heap alloc funcs
  6105. auto typeDef = typeInstance->mTypeDef;
  6106. mBfIRBuilder->PopulateType(typedValue.mType);
  6107. auto vObjectAddr = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, 0);
  6108. bool isAutocomplete = mCompiler->IsAutocomplete();
  6109. BfIRValue vDataRef;
  6110. if (!isAutocomplete)
  6111. {
  6112. vDataRef = GetClassVDataPtr(typeInstance);
  6113. }
  6114. auto i8Type = GetPrimitiveType(BfTypeCode_Int8);
  6115. auto ptrType = CreatePointerType(i8Type);
  6116. auto ptrPtrType = CreatePointerType(ptrType);
  6117. PopulateType(ptrPtrType, BfPopulateType_Declaration);
  6118. PopulateType(ptrType, BfPopulateType_Declaration);
  6119. auto destAddr = mBfIRBuilder->CreateBitCast(vObjectAddr, mBfIRBuilder->MapType(ptrPtrType));
  6120. if (!isAutocomplete)
  6121. {
  6122. if (mCompiler->mOptions.mObjectHasDebugFlags)
  6123. {
  6124. auto objectPtr = mBfIRBuilder->CreateBitCast(destAddr, mBfIRBuilder->MapType(mContext->mBfObjectType));
  6125. SizedArray<BfIRValue, 4> llvmArgs;
  6126. llvmArgs.push_back(objectPtr);
  6127. llvmArgs.push_back(vDataRef);
  6128. auto objectStackInitMethod = GetInternalMethod("Dbg_ObjectStackInit");
  6129. if (objectStackInitMethod)
  6130. mBfIRBuilder->CreateCall(objectStackInitMethod.mFunc, llvmArgs);
  6131. }
  6132. else
  6133. {
  6134. auto srcVal = mBfIRBuilder->CreateBitCast(vDataRef, mBfIRBuilder->MapType(ptrType));
  6135. auto objectPtr = mBfIRBuilder->CreateBitCast(destAddr, mBfIRBuilder->MapType(ptrType));
  6136. mBfIRBuilder->CreateStore(srcVal, destAddr);
  6137. }
  6138. }
  6139. }
  6140. BfIRValue BfModule::AllocBytes(BfAstNode* refNode, const BfAllocTarget& allocTarget, BfType* type, BfIRValue sizeValue, BfIRValue alignValue, BfAllocFlags allocFlags/*, bool zeroMemory, bool defaultToMalloc*/)
  6141. {
  6142. BfIRValue result;
  6143. BfType* ptrType;
  6144. if ((type->IsObject()) && ((allocFlags & BfAllocFlags_RawArray) == 0))
  6145. ptrType = type;
  6146. else
  6147. ptrType = CreatePointerType(type);
  6148. if ((allocTarget.mScopedInvocationTarget != NULL) || (allocTarget.mCustomAllocator))
  6149. {
  6150. auto intType = GetPrimitiveType(BfTypeCode_IntPtr);
  6151. SizedArray<BfExpression*, 2> argExprs;
  6152. BfTypedValueExpression typedValueExpr;
  6153. typedValueExpr.Init(BfTypedValue(sizeValue, intType));
  6154. typedValueExpr.mRefNode = refNode;
  6155. argExprs.push_back(&typedValueExpr);
  6156. BfTypedValueExpression appendSizeValueExpr;
  6157. appendSizeValueExpr.Init(BfTypedValue(alignValue, intType));
  6158. appendSizeValueExpr.mRefNode = refNode;
  6159. argExprs.push_back(&appendSizeValueExpr);
  6160. BfExprEvaluator exprEvaluator(this);
  6161. BfTypedValue allocResult;
  6162. if (allocTarget.mScopedInvocationTarget != NULL)
  6163. {
  6164. SizedArray<BfTypeReference*, 2> genericArgs;
  6165. exprEvaluator.DoInvocation(allocTarget.mScopedInvocationTarget, NULL, argExprs, NULL);
  6166. allocResult = LoadValue(exprEvaluator.mResult);
  6167. }
  6168. else if (allocTarget.mCustomAllocator)
  6169. {
  6170. auto customTypeInst = allocTarget.mCustomAllocator.mType->ToTypeInstance();
  6171. if (customTypeInst != NULL)
  6172. {
  6173. BfTypedValueExpression typeValueExpr;
  6174. String allocMethodName = "Alloc";
  6175. if (GetRawMethodByName(customTypeInst, "AllocTyped", -1, true, true))
  6176. {
  6177. allocMethodName = "AllocTyped";
  6178. auto typeType = ResolveTypeDef(mCompiler->mTypeTypeDef);
  6179. auto typeRefVal = CreateTypeDataRef(type);
  6180. typeValueExpr.Init(BfTypedValue(typeRefVal, typeType));
  6181. typeValueExpr.mRefNode = refNode;
  6182. argExprs.Insert(0, &typeValueExpr);
  6183. }
  6184. if (HasMixin(customTypeInst, allocMethodName, 2))
  6185. {
  6186. BfSizedArray<BfExpression*> argExprArr;
  6187. argExprArr.mSize = (int)argExprs.size();
  6188. argExprArr.mVals = &argExprs[0];
  6189. exprEvaluator.InjectMixin(refNode, allocTarget.mCustomAllocator, false, allocMethodName, argExprs, {});
  6190. allocResult = exprEvaluator.GetResult();
  6191. }
  6192. else
  6193. {
  6194. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  6195. BfResolvedArgs argValues(&sizedArgExprs);
  6196. exprEvaluator.ResolveArgValues(argValues);
  6197. SetAndRestoreValue<bool> prevNoBind(mCurMethodState->mNoBind, true);
  6198. allocResult = exprEvaluator.MatchMethod(refNode, NULL, allocTarget.mCustomAllocator, false, false, allocMethodName, argValues, NULL);
  6199. }
  6200. }
  6201. }
  6202. if (allocResult)
  6203. {
  6204. if (allocResult.mType->IsVoidPtr())
  6205. result = mBfIRBuilder->CreateBitCast(allocResult.mValue, mBfIRBuilder->MapType(ptrType));
  6206. else
  6207. result = CastToValue(refNode, allocResult, ptrType, BfCastFlags_Explicit);
  6208. return result;
  6209. }
  6210. }
  6211. if ((allocFlags & BfAllocFlags_NoDefaultToMalloc) != 0)
  6212. return result;
  6213. if (mCompiler->mOptions.mDebugAlloc)
  6214. {
  6215. BfIRValue allocData = GetDbgRawAllocData(type);
  6216. BfModuleMethodInstance allocMethod = GetInternalMethod("Dbg_RawAlloc", 2);
  6217. SizedArray<BfIRValue, 2> llvmArgs;
  6218. llvmArgs.push_back(sizeValue);
  6219. llvmArgs.push_back(allocData);
  6220. BfIRValue bitData = mBfIRBuilder->CreateCall(allocMethod.mFunc, llvmArgs);
  6221. return mBfIRBuilder->CreateBitCast(bitData, mBfIRBuilder->MapType(ptrType));
  6222. }
  6223. BfModuleMethodInstance moduleMethodInstance;
  6224. moduleMethodInstance = GetInternalMethod("Malloc");
  6225. SizedArray<BfIRValue, 1> llvmArgs;
  6226. llvmArgs.push_back(sizeValue);
  6227. auto func = moduleMethodInstance.mFunc;
  6228. if ((!func) || (func.IsFake()))
  6229. {
  6230. BF_ASSERT((mCompiler->mIsResolveOnly) || (mBfIRBuilder->mIgnoreWrites));
  6231. return mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(ptrType));
  6232. }
  6233. BfIRValue bitData = mBfIRBuilder->CreateCall(func, llvmArgs);
  6234. if ((allocFlags & BfAllocFlags_ZeroMemory) != 0)
  6235. mBfIRBuilder->CreateMemSet(bitData, GetConstValue8(0), sizeValue, alignValue);
  6236. result = mBfIRBuilder->CreateBitCast(bitData, mBfIRBuilder->MapType(ptrType));
  6237. return result;
  6238. }
  6239. BfIRValue BfModule::GetMarkFuncPtr(BfType* type)
  6240. {
  6241. if (type->IsStruct())
  6242. {
  6243. auto typeInstance = type->ToTypeInstance();
  6244. BfModuleMethodInstance moduleMethodInst = GetMethodByName(typeInstance, BF_METHODNAME_MARKMEMBERS, 0, true);
  6245. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  6246. }
  6247. else if (type->IsObjectOrInterface())
  6248. {
  6249. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  6250. BfModuleMethodInstance moduleMethodInst = GetMethodByName(gcType, "MarkDerefedObject");
  6251. BF_ASSERT(moduleMethodInst.mFunc);
  6252. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  6253. }
  6254. else
  6255. {
  6256. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  6257. BfExprEvaluator exprEvaluator(this);
  6258. SizedArray<BfResolvedArg, 1> resolvedArgs;
  6259. BfResolvedArg resolvedArg;
  6260. resolvedArg.mTypedValue = BfTypedValue(mBfIRBuilder->GetFakeVal(), type, type->IsComposite());
  6261. resolvedArgs.Add(resolvedArg);
  6262. BfMethodMatcher methodMatcher(NULL, this, "Mark", resolvedArgs, NULL);
  6263. methodMatcher.CheckType(gcType, BfTypedValue(), false);
  6264. BfModuleMethodInstance moduleMethodInst = exprEvaluator.GetSelectedMethod(NULL, methodMatcher.mBestMethodTypeInstance, methodMatcher.mBestMethodDef, methodMatcher);
  6265. BF_ASSERT(moduleMethodInst.mFunc);
  6266. return mBfIRBuilder->CreateBitCast(moduleMethodInst.mFunc, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  6267. }
  6268. return BfIRValue();
  6269. }
  6270. BfIRValue BfModule::GetDbgRawAllocData(BfType* type)
  6271. {
  6272. BfIRValue allocDataValue;
  6273. if (mDbgRawAllocDataRefs.TryGetValue(type, &allocDataValue))
  6274. return allocDataValue;
  6275. BfIRValue markFuncPtr;
  6276. if (type->WantsGCMarking())
  6277. markFuncPtr = GetMarkFuncPtr(type);
  6278. else
  6279. markFuncPtr = mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  6280. BfIRValue typeDataRef = CreateTypeDataRef(type);
  6281. auto dbgRawAllocDataType = ResolveTypeDef(mCompiler->mDbgRawAllocDataTypeDef)->ToTypeInstance();
  6282. BfTypeInstance* typeInstance = type->ToTypeInstance();
  6283. if (typeInstance == NULL)
  6284. {
  6285. typeInstance = GetWrappedStructType(type);
  6286. if (typeInstance != NULL)
  6287. AddDependency(typeInstance, mCurTypeInstance, BfDependencyMap::DependencyFlag_Allocates);
  6288. }
  6289. if (typeInstance != NULL)
  6290. PopulateType(typeInstance);
  6291. int stackCount = mCompiler->mOptions.mAllocStackCount;
  6292. if ((typeInstance != NULL) && (typeInstance->mTypeOptionsIdx != -1))
  6293. {
  6294. auto typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  6295. stackCount = BfTypeOptions::Apply(stackCount, typeOptions->mAllocStackTraceDepth);
  6296. }
  6297. SizedArray<BfIRValue, 2> dataValues;
  6298. dataValues.Add(mBfIRBuilder->CreateConstStructZero(mBfIRBuilder->MapType(dbgRawAllocDataType->mBaseType, BfIRPopulateType_Full)));
  6299. dataValues.Add(typeDataRef);
  6300. dataValues.Add(markFuncPtr);
  6301. dataValues.Add(mBfIRBuilder->CreateConst(BfTypeCode_Int32, stackCount));
  6302. BfIRValue dataStruct = mBfIRBuilder->CreateConstStruct(mBfIRBuilder->MapType(dbgRawAllocDataType, BfIRPopulateType_Full), dataValues);
  6303. allocDataValue = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(dbgRawAllocDataType), true, BfIRLinkageType_Internal, dataStruct, "__allocData_" + BfSafeMangler::Mangle(type));
  6304. mDbgRawAllocDataRefs.TryAdd(type, allocDataValue);
  6305. return allocDataValue;
  6306. }
  6307. BfIRValue BfModule::AllocFromType(BfType* type, const BfAllocTarget& allocTarget, BfIRValue appendSizeValue, BfIRValue arraySize, int arrayDim, BfAllocFlags allocFlags, int alignOverride)
  6308. {
  6309. BP_ZONE("AllocFromType");
  6310. BfScopeData* scopeData = allocTarget.mScopeData;
  6311. auto typeInstance = type->ToTypeInstance();
  6312. if ((typeInstance == NULL) && (type->IsGenericParam()))
  6313. typeInstance = mContext->mBfObjectType;
  6314. bool isHeapAlloc = scopeData == NULL;
  6315. bool isScopeAlloc = scopeData != NULL;
  6316. bool isLoopedAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsLooped(scopeData));
  6317. bool isDynAlloc = (scopeData != NULL) && (mCurMethodState->mCurScope->IsDyn(scopeData));
  6318. bool isRawArrayAlloc = (allocFlags & BfAllocFlags_RawArray) != 0;
  6319. bool zeroMemory = (allocFlags & BfAllocFlags_ZeroMemory) != 0;
  6320. bool noDtorCall = (allocFlags & BfAllocFlags_NoDtorCall) != 0;
  6321. if ((type->IsValuelessType()) && ((!arraySize) || (isRawArrayAlloc)))
  6322. {
  6323. BfPointerType* ptrType = CreatePointerType(type);
  6324. auto val = mBfIRBuilder->CreateIntToPtr(mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1), mBfIRBuilder->MapType(ptrType));
  6325. return val;
  6326. }
  6327. if (typeInstance != NULL)
  6328. mBfIRBuilder->PopulateType(typeInstance);
  6329. bool hasCustomAllocator = (allocTarget.mCustomAllocator) || (allocTarget.mScopedInvocationTarget != NULL);
  6330. if ((!hasCustomAllocator) && (mBfIRBuilder->mIgnoreWrites))
  6331. {
  6332. if (arraySize)
  6333. {
  6334. if (isRawArrayAlloc)
  6335. {
  6336. BfPointerType* ptrType = CreatePointerType(type);
  6337. return GetDefaultValue(ptrType);
  6338. }
  6339. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  6340. return GetDefaultValue(arrayType);
  6341. }
  6342. if (type->IsValueType())
  6343. {
  6344. BfPointerType* ptrType = CreatePointerType(type);
  6345. return GetDefaultValue(ptrType);
  6346. }
  6347. return mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type));
  6348. }
  6349. AddDependency(type, mCurTypeInstance, BfDependencyMap::DependencyFlag_Allocates);
  6350. BfIRValue sizeValue;
  6351. BfIRType allocType = mBfIRBuilder->MapType(type);
  6352. int allocSize = type->mSize;
  6353. int allocAlign = type->mAlign;
  6354. if (typeInstance != NULL)
  6355. {
  6356. if (!mBfIRBuilder->mIgnoreWrites)
  6357. typeInstance->mHasBeenInstantiated = true;
  6358. allocSize = typeInstance->mInstSize;
  6359. allocAlign = typeInstance->mInstAlign;
  6360. //if (typeInstance->IsEnum())
  6361. //allocType = typeInstance->mIRType;
  6362. allocType = mBfIRBuilder->MapTypeInst(typeInstance);
  6363. }
  6364. if (alignOverride != -1)
  6365. allocAlign = alignOverride;
  6366. // The "dynSize" cases:
  6367. // If we are not dyn, but we are a variable size and could be looped over multiple times then we attempt to reuse
  6368. // the last stack space. We won't use StackSave and StackRestore because a scoped alloc that occurs after this but
  6369. // needs to be retained after the current scopeData (ie: scopeData::), then it would cause these allocs to accumulate even
  6370. // though we'd expect their stack space to be released
  6371. auto _CreateDynAlloc = [&](const BfIRValue& sizeValue, int align)
  6372. {
  6373. MarkDynStack(scopeData);
  6374. BfType* intType = GetPrimitiveType(BfTypeCode_IntPtr);
  6375. // For dynamically sized scoped allocs, we need to check the previous size to see if we need to realloc
  6376. BfType* voidType = GetPrimitiveType(BfTypeCode_None);
  6377. BfType* voidPtrType = CreatePointerType(voidType);
  6378. if (!mCurMethodState->mDynStackRevIdx)
  6379. {
  6380. mCurMethodState->mDynStackRevIdx = CreateAlloca(intType, false, "curDynStackRevIdx");
  6381. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  6382. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  6383. auto storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), mCurMethodState->mDynStackRevIdx);
  6384. mBfIRBuilder->ClearDebugLocation(storeInst);
  6385. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  6386. }
  6387. auto byteType = GetPrimitiveType(BfTypeCode_Int8);
  6388. auto bytePtrType = CreatePointerType(byteType);
  6389. auto dynSizeAllocaInst = CreateAlloca(intType, false, "dynSize");
  6390. auto dynStackRevIdx = CreateAlloca(intType, false, "dynStackRevIdx");
  6391. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  6392. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  6393. auto storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), dynSizeAllocaInst);
  6394. mBfIRBuilder->ClearDebugLocation(storeInst);
  6395. storeInst = mBfIRBuilder->CreateStore(GetConstValue(0), dynStackRevIdx);
  6396. mBfIRBuilder->ClearDebugLocation(storeInst);
  6397. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  6398. auto dynPtrAllocaInst = CreateAlloca(bytePtrType, false, "dynPtr");
  6399. if (IsTargetingBeefBackend())
  6400. {
  6401. // Since we don't allocate a debug variable for this, with LifetimeExtends, the easiest way
  6402. // to ensure there isn't any register collision during looping is just to not allow it to
  6403. // bind to a register at all
  6404. mBfIRBuilder->SetAllocaForceMem(dynSizeAllocaInst);
  6405. mBfIRBuilder->SetAllocaForceMem(dynPtrAllocaInst);
  6406. }
  6407. auto resizeBB = mBfIRBuilder->CreateBlock("dynAlloc.resize");
  6408. auto endBB = mBfIRBuilder->CreateBlock("dynAlloc.end");
  6409. auto verCheckBB = mBfIRBuilder->CreateBlock("dynAlloc.verCheck");
  6410. auto curDynStackRevIdx = mBfIRBuilder->CreateLoad(mCurMethodState->mDynStackRevIdx);
  6411. auto prevSize = mBfIRBuilder->CreateLoad(dynSizeAllocaInst);
  6412. auto isGreater = mBfIRBuilder->CreateCmpGT(sizeValue, prevSize, true);
  6413. mBfIRBuilder->CreateCondBr(isGreater, resizeBB, verCheckBB);
  6414. mBfIRBuilder->AddBlock(verCheckBB);
  6415. mBfIRBuilder->SetInsertPoint(verCheckBB);
  6416. auto prevDynStackRevIdx = mBfIRBuilder->CreateLoad(dynStackRevIdx);
  6417. auto dynStackChanged = mBfIRBuilder->CreateCmpNE(prevDynStackRevIdx, curDynStackRevIdx);
  6418. mBfIRBuilder->CreateCondBr(dynStackChanged, resizeBB, endBB);
  6419. mBfIRBuilder->AddBlock(resizeBB);
  6420. mBfIRBuilder->SetInsertPoint(resizeBB);
  6421. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  6422. mBfIRBuilder->SetAllocaAlignment(allocaInst, align);
  6423. mBfIRBuilder->CreateStore(allocaInst, dynPtrAllocaInst);
  6424. mBfIRBuilder->CreateStore(sizeValue, dynSizeAllocaInst);
  6425. mBfIRBuilder->CreateStore(curDynStackRevIdx, dynStackRevIdx);
  6426. mBfIRBuilder->CreateBr(endBB);
  6427. mBfIRBuilder->AddBlock(endBB);
  6428. mBfIRBuilder->SetInsertPoint(endBB);
  6429. return mBfIRBuilder->CreateLoad(dynPtrAllocaInst);
  6430. };
  6431. if (isScopeAlloc)
  6432. {
  6433. if (arraySize)
  6434. {
  6435. bool isConstantArraySize = arraySize.IsConst();
  6436. if (isRawArrayAlloc)
  6437. {
  6438. BfPointerType* ptrType = CreatePointerType(type);
  6439. if ((!isDynAlloc) && (!isConstantArraySize) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  6440. {
  6441. BfIRValue sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  6442. auto loadedPtr = _CreateDynAlloc(sizeValue, type->mAlign);
  6443. InitTypeInst(BfTypedValue(loadedPtr, ptrType), scopeData, zeroMemory, sizeValue);
  6444. return mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(type)));
  6445. }
  6446. else
  6447. {
  6448. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  6449. isDynAlloc = (isDynAlloc) || (!arraySize.IsConst());
  6450. if (!isDynAlloc)
  6451. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  6452. else
  6453. {
  6454. MarkDynStack(scopeData);
  6455. SaveStackState(scopeData);
  6456. }
  6457. int typeSize = type->GetStride();
  6458. BfIRValue allocaInst;
  6459. BfIRValue result;
  6460. if ((typeInstance == NULL) || (typeInstance->mIsCRepr))
  6461. {
  6462. sizeValue = mBfIRBuilder->CreateMul(GetConstValue(typeSize), arraySize);
  6463. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(type), arraySize);
  6464. result = allocaInst;
  6465. }
  6466. else
  6467. {
  6468. if (typeInstance->IsStruct())
  6469. typeSize = typeInstance->GetInstStride();
  6470. auto byteType = GetPrimitiveStructType(BfTypeCode_Int8);
  6471. sizeValue = mBfIRBuilder->CreateMul(GetConstValue(typeSize), arraySize);
  6472. allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  6473. auto ptrType = CreatePointerType(typeInstance);
  6474. result = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(ptrType));
  6475. if (!isDynAlloc)
  6476. mBfIRBuilder->ClearDebugLocation(result);
  6477. }
  6478. if (!isDynAlloc)
  6479. mBfIRBuilder->ClearDebugLocation(allocaInst);
  6480. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  6481. if (!isDynAlloc)
  6482. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  6483. auto typedVal = BfTypedValue(result, type, BfTypedValueKind_Addr);
  6484. if (arraySize.IsConst())
  6485. {
  6486. auto constant = mBfIRBuilder->GetConstant(arraySize);
  6487. if (constant->mInt64 == 0)
  6488. noDtorCall = true;
  6489. }
  6490. if (!noDtorCall)
  6491. {
  6492. bool isConstSize = arraySize.IsConst();
  6493. BfIRBlock clearBlock;
  6494. BfIRBlock contBlock;
  6495. if (!isConstSize)
  6496. {
  6497. clearBlock = mBfIRBuilder->CreateBlock("clear");
  6498. contBlock = mBfIRBuilder->CreateBlock("clearCont");
  6499. mBfIRBuilder->CreateCondBr(mBfIRBuilder->CreateCmpNE(arraySize, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0)), clearBlock, contBlock);
  6500. mBfIRBuilder->AddBlock(clearBlock);
  6501. mBfIRBuilder->SetInsertPoint(clearBlock);
  6502. }
  6503. AddStackAlloc(typedVal, NULL, scopeData, false, true);
  6504. if (!isConstSize)
  6505. {
  6506. mBfIRBuilder->CreateBr(contBlock);
  6507. mBfIRBuilder->AddBlock(contBlock);
  6508. mBfIRBuilder->SetInsertPoint(contBlock);
  6509. }
  6510. }
  6511. //InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  6512. return result;
  6513. }
  6514. }
  6515. else
  6516. {
  6517. if ((!isDynAlloc) && (!arraySize.IsConst()) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  6518. {
  6519. // Generate and check new size
  6520. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  6521. auto firstElementField = &arrayType->mFieldInstances.back();
  6522. int arrayClassSize = firstElementField->mDataOffset;
  6523. sizeValue = GetConstValue(arrayClassSize);
  6524. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  6525. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  6526. auto loadedPtr = _CreateDynAlloc(sizeValue, arrayType->mAlign);
  6527. auto typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->MapType(arrayType)), arrayType);
  6528. if (!noDtorCall)
  6529. AddStackAlloc(typedVal, NULL, scopeData, false, true);
  6530. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  6531. return typedVal.mValue;
  6532. }
  6533. else
  6534. {
  6535. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  6536. auto firstElementField = &arrayType->mFieldInstances.back();
  6537. int arrayClassSize = firstElementField->mDataOffset;
  6538. sizeValue = GetConstValue(arrayClassSize);
  6539. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  6540. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  6541. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  6542. isDynAlloc = (isDynAlloc) || (!sizeValue.IsConst());
  6543. if (!isDynAlloc)
  6544. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  6545. else
  6546. {
  6547. MarkDynStack(scopeData);
  6548. SaveStackState(scopeData);
  6549. }
  6550. BfType* byteType = GetPrimitiveType(BfTypeCode_Int8);
  6551. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(byteType), sizeValue);
  6552. if (!isDynAlloc)
  6553. mBfIRBuilder->ClearDebugLocation(allocaInst);
  6554. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  6555. auto typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(arrayType)), arrayType);
  6556. mBfIRBuilder->ClearDebugLocation_Last();
  6557. if (!isDynAlloc)
  6558. mBfIRBuilder->SetInsertPoint(prevBlock);
  6559. if (!noDtorCall)
  6560. AddStackAlloc(typedVal, NULL, scopeData, false, true);
  6561. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  6562. return typedVal.mValue;
  6563. }
  6564. }
  6565. }
  6566. else if (appendSizeValue)
  6567. {
  6568. // It may seem that we should check IsLooped against only the requested scope, BUT- if later on we perform
  6569. // a scoped alloc that crosses our boundary then we won't be able to reclaim the stack space, so we always
  6570. // use the "dynSize" version conservatively
  6571. if ((!isDynAlloc) && (!appendSizeValue.IsConst()) && (mCurMethodState->mCurScope->IsLooped(NULL)))
  6572. {
  6573. // Generate and check new size
  6574. sizeValue = GetConstValue(typeInstance->mInstSize);
  6575. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  6576. auto loadedPtr = _CreateDynAlloc(sizeValue, typeInstance->mAlign);
  6577. auto typedVal = BfTypedValue(mBfIRBuilder->CreateBitCast(loadedPtr, mBfIRBuilder->MapTypeInstPtr(typeInstance)), typeInstance);
  6578. if (!noDtorCall)
  6579. AddStackAlloc(typedVal, NULL, scopeData, mCurMethodState->mInConditionalBlock, true);
  6580. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  6581. return typedVal.mValue;
  6582. }
  6583. else // stack alloc, unlooped, with append
  6584. {
  6585. sizeValue = GetConstValue(typeInstance->mInstSize);
  6586. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  6587. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  6588. bool wasDynAlloc = isDynAlloc;
  6589. isDynAlloc = (isDynAlloc) || (!sizeValue.IsConst());
  6590. if (!isDynAlloc)
  6591. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  6592. else
  6593. {
  6594. MarkDynStack(scopeData);
  6595. SaveStackState(scopeData);
  6596. }
  6597. auto sbyteType = GetPrimitiveType(BfTypeCode_Int8);
  6598. auto allocaInst = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(sbyteType), sizeValue);
  6599. if (!isDynAlloc)
  6600. {
  6601. mBfIRBuilder->ClearDebugLocation(allocaInst);
  6602. }
  6603. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  6604. bool mayBeLarge = false;
  6605. if (sizeValue.IsConst())
  6606. {
  6607. auto constantInt = mBfIRBuilder->GetConstant(sizeValue);
  6608. if (constantInt->mInt64 >= 4096)
  6609. mayBeLarge = true;
  6610. }
  6611. else
  6612. mayBeLarge = true;
  6613. if (((type->IsObject() && (!mayBeLarge))) ||
  6614. // If we create a memset that can fill in backwards (or at least 4k chunked backward) then we can remove the '!mayBeLarge' cond
  6615. ((zeroMemory) && (!mayBeLarge)))
  6616. {
  6617. mBfIRBuilder->SetAllocaNoChkStkHint(allocaInst);
  6618. }
  6619. BfIRValue castedVal;
  6620. if (!isDynAlloc)
  6621. {
  6622. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  6623. castedVal = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapTypeInstPtr(typeInstance));
  6624. mBfIRBuilder->ClearDebugLocation(castedVal);
  6625. mBfIRBuilder->SetInsertPoint(prevBlock);
  6626. if (WantsLifetimes())
  6627. {
  6628. mBfIRBuilder->CreateLifetimeStart(allocaInst);
  6629. scopeData->mDeferredLifetimeEnds.push_back(allocaInst);
  6630. }
  6631. }
  6632. else
  6633. {
  6634. castedVal = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapTypeInstPtr(typeInstance));
  6635. }
  6636. auto typedVal = BfTypedValue(castedVal, typeInstance);
  6637. if (!noDtorCall)
  6638. {
  6639. bool doCondAlloca = false;
  6640. if (!IsTargetingBeefBackend())
  6641. doCondAlloca = !wasDynAlloc && isDynAlloc && mCurMethodState->mInConditionalBlock;
  6642. AddStackAlloc(typedVal, NULL, scopeData, doCondAlloca, true);
  6643. }
  6644. InitTypeInst(typedVal, scopeData, zeroMemory, sizeValue);
  6645. return typedVal.mValue;
  6646. }
  6647. }
  6648. else // "Normal" stack alloc
  6649. {
  6650. BF_ASSERT(!sizeValue);
  6651. //TODO: If sizeValue is a constant then do this in the head IR builder
  6652. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  6653. if (!isLoopedAlloc)
  6654. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  6655. else
  6656. {
  6657. MarkDynStack(scopeData);
  6658. SaveStackState(scopeData);
  6659. }
  6660. auto allocaInst = mBfIRBuilder->CreateAlloca(allocType);
  6661. if (!isLoopedAlloc)
  6662. mBfIRBuilder->ClearDebugLocation(allocaInst);
  6663. mBfIRBuilder->SetAllocaAlignment(allocaInst, allocAlign);
  6664. bool mayBeLarge = allocSize >= 4096;
  6665. if (((typeInstance != NULL) && (typeInstance->IsObject()) && (!mayBeLarge)) ||
  6666. // If we create a memset that can fill in backwards (or at least 4k chunked backward) then we can remove the '!mayBeLarge' cond
  6667. ((zeroMemory) && (!mayBeLarge)))
  6668. {
  6669. // With an object, we know we will at least set the vdata pointer which will probe the start of the new address,
  6670. // and memset is always safe
  6671. mBfIRBuilder->SetAllocaNoChkStkHint(allocaInst);
  6672. }
  6673. auto typedVal = BfTypedValue(allocaInst, type);
  6674. if (!isLoopedAlloc)
  6675. {
  6676. mBfIRBuilder->ClearDebugLocation(allocaInst);
  6677. mBfIRBuilder->SetInsertPoint(prevBlock);
  6678. if (WantsLifetimes())
  6679. {
  6680. mBfIRBuilder->CreateLifetimeStart(allocaInst);
  6681. scopeData->mDeferredLifetimeEnds.push_back(allocaInst);
  6682. }
  6683. }
  6684. if (!noDtorCall)
  6685. AddStackAlloc(typedVal, NULL, scopeData, false, true);
  6686. if (typeInstance != NULL)
  6687. {
  6688. InitTypeInst(typedVal, scopeData, zeroMemory, GetConstValue(typeInstance->mInstSize));
  6689. }
  6690. else
  6691. {
  6692. mBfIRBuilder->CreateMemSet(allocaInst, GetConstValue8(0), GetConstValue(allocSize), allocAlign);
  6693. }
  6694. return allocaInst;
  6695. }
  6696. }
  6697. else if (arraySize)
  6698. {
  6699. if (isRawArrayAlloc)
  6700. {
  6701. sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  6702. return AllocBytes(allocTarget.mRefNode, allocTarget, type, sizeValue, GetConstValue(allocAlign), allocFlags);
  6703. }
  6704. else
  6705. {
  6706. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  6707. typeInstance = arrayType;
  6708. BfIRValue arraySizeMinusOne = mBfIRBuilder->CreateSub(arraySize, GetConstValue(1));
  6709. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySizeMinusOne);
  6710. appendSizeValue = elementDataSize;
  6711. if (!type->IsSizeAligned())
  6712. {
  6713. appendSizeValue = mBfIRBuilder->CreateAdd(appendSizeValue, GetConstValue(type->GetStride() - type->mSize));
  6714. }
  6715. }
  6716. }
  6717. if ((typeInstance != NULL) && (typeInstance->IsObject()))
  6718. {
  6719. auto vDataRef = GetClassVDataPtr(typeInstance);
  6720. BfIRValue result;
  6721. bool isResultInitialized = false;
  6722. int stackCount = mCompiler->mOptions.mAllocStackCount;
  6723. if (typeInstance->mTypeOptionsIdx != -1)
  6724. {
  6725. auto typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  6726. stackCount = BfTypeOptions::Apply(stackCount, typeOptions->mAllocStackTraceDepth);
  6727. }
  6728. if (!sizeValue)
  6729. sizeValue = GetConstValue(typeInstance->mInstSize);
  6730. if (appendSizeValue)
  6731. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, appendSizeValue);
  6732. BfIRValue origSizeValue = sizeValue;
  6733. bool isAllocEx = hasCustomAllocator && (stackCount > 1);
  6734. if (isAllocEx)
  6735. {
  6736. auto prepareStackTraceMethod = GetInternalMethod("Dbg_PrepareStackTrace");
  6737. if (prepareStackTraceMethod)
  6738. {
  6739. SizedArray<BfIRValue, 2> irArgs;
  6740. irArgs.Add(sizeValue);
  6741. irArgs.Add(GetConstValue(stackCount));
  6742. auto addlBytes = mBfIRBuilder->CreateCall(prepareStackTraceMethod.mFunc, irArgs);
  6743. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, addlBytes);
  6744. }
  6745. }
  6746. if (allocTarget.mCustomAllocator)
  6747. {
  6748. auto customAlloc = allocTarget.mCustomAllocator.mType->ToTypeInstance();
  6749. // Use AllocObject if we have it, otherwise we just use AllocBytes further down
  6750. if ((customAlloc != NULL) && (GetRawMethodByName(customAlloc, "AllocObject", -1, true, true) != NULL))
  6751. {
  6752. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  6753. mBfIRBuilder->PopulateType(classVDataType);
  6754. auto typeInstType = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef)->ToTypeInstance();
  6755. mBfIRBuilder->PopulateType(typeInstType);
  6756. auto typePtrPtr = mBfIRBuilder->CreateInBoundsGEP(vDataRef, 0, 1); // mType
  6757. auto typePtr = mBfIRBuilder->CreateLoad(typePtrPtr);
  6758. auto typeInstPtr = mBfIRBuilder->CreateBitCast(typePtr, mBfIRBuilder->MapTypeInstPtr(typeInstType));
  6759. BfTypedValueExpression typedValueExpr;
  6760. typedValueExpr.Init(BfTypedValue(typeInstPtr, typeInstType));
  6761. typedValueExpr.mRefNode = allocTarget.mRefNode;
  6762. BfExprEvaluator exprEvaluator(this);
  6763. SizedArray<BfExpression*, 2> argExprs;
  6764. argExprs.push_back(&typedValueExpr);
  6765. BfTypedValueExpression sizeValueExpr;
  6766. sizeValueExpr.Init(BfTypedValue(sizeValue, GetPrimitiveType(BfTypeCode_IntPtr)));
  6767. sizeValueExpr.mRefNode = allocTarget.mRefNode;
  6768. argExprs.push_back(&sizeValueExpr);
  6769. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  6770. BfResolvedArgs argValues(&sizedArgExprs);
  6771. exprEvaluator.ResolveArgValues(argValues);
  6772. exprEvaluator.mNoBind = true;
  6773. BfTypedValue allocResult = exprEvaluator.MatchMethod(allocTarget.mRefNode, NULL, allocTarget.mCustomAllocator, false, false, "AllocObject", argValues, NULL);
  6774. if (allocResult)
  6775. {
  6776. if ((allocResult.mType->IsVoidPtr()) || (allocResult.mType == mContext->mBfObjectType))
  6777. result = mBfIRBuilder->CreateBitCast(allocResult.mValue, mBfIRBuilder->MapType(typeInstance));
  6778. else
  6779. result = CastToValue(allocTarget.mRefNode, allocResult, typeInstance, BfCastFlags_Explicit);
  6780. isResultInitialized = true;
  6781. }
  6782. }
  6783. }
  6784. if (!result)
  6785. {
  6786. if (hasCustomAllocator)
  6787. result = AllocBytes(allocTarget.mRefNode, allocTarget, typeInstance, sizeValue, GetConstValue(typeInstance->mInstAlign), (BfAllocFlags)(BfAllocFlags_ZeroMemory | BfAllocFlags_NoDefaultToMalloc));
  6788. }
  6789. if (result)
  6790. {
  6791. if (mCompiler->mOptions.mObjectHasDebugFlags)
  6792. {
  6793. auto objectPtr = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapTypeInstPtr(mContext->mBfObjectType));
  6794. SizedArray<BfIRValue, 4> llvmArgs;
  6795. llvmArgs.push_back(objectPtr);
  6796. llvmArgs.push_back(origSizeValue);
  6797. llvmArgs.push_back(vDataRef);
  6798. auto objectCreatedMethod = GetInternalMethod(isAllocEx ?
  6799. (isResultInitialized ? "Dbg_ObjectCreatedEx" : "Dbg_ObjectAllocatedEx") :
  6800. (isResultInitialized ? "Dbg_ObjectCreated" : "Dbg_ObjectAllocated"));
  6801. mBfIRBuilder->CreateCall(objectCreatedMethod.mFunc, llvmArgs);
  6802. }
  6803. else
  6804. {
  6805. auto ptrType = mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr);
  6806. auto vDataPtr = mBfIRBuilder->CreateBitCast(vDataRef, ptrType);
  6807. auto vDataMemberPtr = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->GetPointerTo(ptrType));
  6808. mBfIRBuilder->CreateStore(vDataPtr, vDataMemberPtr);
  6809. }
  6810. }
  6811. else
  6812. {
  6813. if ((mBfIRBuilder->mIgnoreWrites) || (mCompiler->mIsResolveOnly))
  6814. return GetDefaultValue(typeInstance);
  6815. auto classVDataType = ResolveTypeDef(mCompiler->mClassVDataTypeDef);
  6816. auto vData = mBfIRBuilder->CreateBitCast(vDataRef, mBfIRBuilder->MapTypeInstPtr(classVDataType->ToTypeInstance()));
  6817. if (mCompiler->mOptions.mObjectHasDebugFlags)
  6818. {
  6819. SizedArray<BfIRValue, 4> llvmArgs;
  6820. llvmArgs.push_back(vData);
  6821. llvmArgs.push_back(sizeValue);
  6822. llvmArgs.push_back(GetConstValue(typeInstance->mAlign));
  6823. llvmArgs.push_back(GetConstValue(stackCount));
  6824. auto moduleMethodInstance = GetInternalMethod("Dbg_ObjectAlloc", 4);
  6825. BfIRValue objectVal = mBfIRBuilder->CreateCall(moduleMethodInstance.mFunc, llvmArgs);
  6826. result = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(typeInstance));
  6827. }
  6828. else
  6829. {
  6830. SizedArray<BfIRValue, 4> llvmArgs;
  6831. llvmArgs.push_back(sizeValue);
  6832. BfIRFunction irFunc;
  6833. if (mCompiler->mOptions.mDebugAlloc)
  6834. {
  6835. auto moduleMethodInstance = GetInternalMethod("Dbg_RawObjectAlloc", 1);
  6836. irFunc = moduleMethodInstance.mFunc;
  6837. }
  6838. if (!irFunc)
  6839. irFunc = GetBuiltInFunc(BfBuiltInFuncType_Malloc);
  6840. BfIRValue objectVal = mBfIRBuilder->CreateCall(irFunc, llvmArgs);
  6841. auto objResult = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(mContext->mBfObjectType, BfIRPopulateType_Full));
  6842. auto vdataPtr = mBfIRBuilder->CreateInBoundsGEP(objResult, 0, 0);
  6843. mBfIRBuilder->CreateStore(vData, vdataPtr);
  6844. result = mBfIRBuilder->CreateBitCast(objectVal, mBfIRBuilder->MapType(typeInstance));
  6845. }
  6846. }
  6847. if ((zeroMemory) && (arraySize))
  6848. {
  6849. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  6850. typeInstance = arrayType;
  6851. auto firstElementField = &arrayType->mFieldInstances.back();
  6852. int arrayClassSize = firstElementField->mDataOffset;
  6853. BfIRValue elementDataSize;
  6854. bool skipZero = false;
  6855. if (arraySize.IsConst())
  6856. {
  6857. BfIRValue arraySizeMinusOne = mBfIRBuilder->CreateSub(arraySize, GetConstValue(1));
  6858. elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySizeMinusOne);
  6859. elementDataSize = mBfIRBuilder->CreateAdd(elementDataSize, GetConstValue(type->mSize));
  6860. auto constVal = mBfIRBuilder->GetConstant(elementDataSize);
  6861. if (constVal->mInt64 <= 0)
  6862. skipZero = true;
  6863. }
  6864. else
  6865. {
  6866. // For non const, don't use an unpadded last element - saves us checking against negative numbers going into memset for the zero-length case
  6867. elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->GetStride()), arraySize);
  6868. }
  6869. if (!skipZero)
  6870. {
  6871. auto i8Type = GetPrimitiveType(BfTypeCode_Int8);
  6872. auto ptrType = CreatePointerType(i8Type);
  6873. auto ptrVal = mBfIRBuilder->CreateBitCast(result, mBfIRBuilder->MapType(ptrType));
  6874. ptrVal = mBfIRBuilder->CreateInBoundsGEP(ptrVal, arrayClassSize);
  6875. mBfIRBuilder->CreateMemSet(ptrVal, GetConstValue8(0), elementDataSize, type->mAlign);
  6876. appendSizeValue = elementDataSize;
  6877. }
  6878. }
  6879. return result;
  6880. }
  6881. else
  6882. {
  6883. if (!sizeValue)
  6884. sizeValue = GetConstValue(allocSize);
  6885. return AllocBytes(allocTarget.mRefNode, allocTarget, type, sizeValue, GetConstValue(allocAlign), zeroMemory ? BfAllocFlags_ZeroMemory : BfAllocFlags_None);
  6886. }
  6887. }
  6888. void BfModule::ValidateAllocation(BfType* type, BfAstNode* refNode)
  6889. {
  6890. if ((type == NULL) || (refNode == NULL))
  6891. return;
  6892. auto typeInstance = type->ToTypeInstance();
  6893. if ((typeInstance != NULL) && (typeInstance->mTypeDef->mIsOpaque))
  6894. Fail(StrFormat("Unable to allocate opaque type '%s'", TypeToString(type).c_str()), refNode);
  6895. }
  6896. void BfModule::EmitAlign(BfIRValue& appendCurIdx, int align)
  6897. {
  6898. appendCurIdx = mBfIRBuilder->CreateAdd(appendCurIdx, GetConstValue(align - 1));
  6899. appendCurIdx = mBfIRBuilder->CreateAnd(appendCurIdx, GetConstValue(~(align - 1)));
  6900. }
  6901. void BfModule::EmitAppendAlign(int align, int sizeMultiple)
  6902. {
  6903. if (sizeMultiple == 0)
  6904. sizeMultiple = align;
  6905. if ((mCurMethodState->mCurAppendAlign != 0) && (mCurMethodState->mCurAppendAlign % align != 0))
  6906. {
  6907. if (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Ctor)
  6908. {
  6909. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  6910. BF_ASSERT(localVar->mName == "appendIdx");
  6911. auto appendIdxVal = BfTypedValue(localVar->mValue, localVar->mResolvedType, true);
  6912. BfIRValue appendCurIdx = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  6913. if (align > 1)
  6914. {
  6915. appendCurIdx = mBfIRBuilder->CreateAdd(appendCurIdx, GetConstValue(align - 1));
  6916. appendCurIdx = mBfIRBuilder->CreateAnd(appendCurIdx, GetConstValue(~(align - 1)));
  6917. }
  6918. mBfIRBuilder->CreateStore(appendCurIdx, appendIdxVal.mValue);
  6919. }
  6920. else
  6921. {
  6922. BF_ASSERT(mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend);
  6923. BfIRValue appendCurIdxPtr = mCurMethodState->mRetVal.mValue;
  6924. BfIRValue appendCurIdx = mBfIRBuilder->CreateLoad(appendCurIdxPtr);
  6925. appendCurIdx = mBfIRBuilder->CreateAdd(appendCurIdx, GetConstValue(align - 1));
  6926. appendCurIdx = mBfIRBuilder->CreateAnd(appendCurIdx, GetConstValue(~(align - 1)));
  6927. mBfIRBuilder->CreateStore(appendCurIdx, appendCurIdxPtr);
  6928. }
  6929. }
  6930. if (mCurMethodState->mCurAppendAlign == 0)
  6931. mCurMethodState->mCurAppendAlign = sizeMultiple;
  6932. else
  6933. {
  6934. if (sizeMultiple % align == 0)
  6935. mCurMethodState->mCurAppendAlign = align;
  6936. else
  6937. mCurMethodState->mCurAppendAlign = sizeMultiple % align;
  6938. }
  6939. }
  6940. BfIRValue BfModule::AppendAllocFromType(BfType* type, BfIRValue appendSizeValue, int appendAllocAlign, BfIRValue arraySize, int arrayDim, bool isRawArrayAlloc, bool zeroMemory)
  6941. {
  6942. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  6943. BF_ASSERT(localVar->mName == "appendIdx");
  6944. BfTypedValue appendIdxVal(localVar->mValue, localVar->mResolvedType, true);
  6945. BfIRValue retValue;
  6946. BfTypeInstance* retTypeInstance = NULL;
  6947. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  6948. auto voidPtrType = GetPrimitiveType(BfTypeCode_NullPtr);
  6949. if (arraySize)
  6950. {
  6951. if (isRawArrayAlloc)
  6952. {
  6953. EmitAppendAlign(type->mAlign);
  6954. BfPointerType* ptrType = CreatePointerType(type);
  6955. BfIRValue sizeValue = mBfIRBuilder->CreateMul(GetConstValue(type->mSize), arraySize);
  6956. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  6957. if (mSystem->mPtrSize != 4)
  6958. sizeValue = mBfIRBuilder->CreateNumericCast(sizeValue, true, (intPtrType->mSize == 4) ? BfTypeCode_Int32 : BfTypeCode_Int64);
  6959. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  6960. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  6961. if (zeroMemory)
  6962. {
  6963. auto ptr = mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(voidPtrType));
  6964. mBfIRBuilder->CreateMemSet(ptr, GetConstValue8(0), sizeValue, type->mAlign);
  6965. }
  6966. return mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(ptrType));
  6967. }
  6968. else
  6969. {
  6970. BfArrayType* arrayType = CreateArrayType(type, arrayDim);
  6971. EmitAppendAlign(arrayType->mAlign, type->mSize);
  6972. auto firstElementField = &arrayType->mFieldInstances.back();
  6973. int arrayClassSize = arrayType->mInstSize - firstElementField->mDataSize;
  6974. BfIRValue sizeValue = GetConstValue(arrayClassSize);
  6975. BfIRValue elementDataSize = mBfIRBuilder->CreateMul(GetConstValue(type->mSize), arraySize);
  6976. sizeValue = mBfIRBuilder->CreateAdd(sizeValue, elementDataSize);
  6977. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  6978. if (mSystem->mPtrSize != 4)
  6979. sizeValue = mBfIRBuilder->CreateNumericCast(sizeValue, true, (intPtrType->mSize == 4) ? BfTypeCode_Int32 : BfTypeCode_Int64);
  6980. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  6981. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  6982. if (zeroMemory)
  6983. {
  6984. // Only zero out the actual elements
  6985. int dataOffset = arrayType->mFieldInstances.back().mDataOffset;
  6986. auto newOffset = mBfIRBuilder->CreateAdd(curIdxVal, GetConstValue(dataOffset));
  6987. auto newSize = mBfIRBuilder->CreateSub(sizeValue, GetConstValue(dataOffset));
  6988. auto ptr = mBfIRBuilder->CreateIntToPtr(newOffset, mBfIRBuilder->MapType(voidPtrType));
  6989. mBfIRBuilder->CreateMemSet(ptr, GetConstValue8(0), newSize, type->mAlign);
  6990. }
  6991. retTypeInstance = arrayType;
  6992. retValue = mBfIRBuilder->CreateIntToPtr(curIdxVal, mBfIRBuilder->MapType(arrayType));
  6993. }
  6994. }
  6995. else
  6996. {
  6997. auto typeInst = type->ToTypeInstance();
  6998. BfIRValue sizeValue;
  6999. BfIRType toType;
  7000. if (typeInst != NULL)
  7001. {
  7002. EmitAppendAlign(typeInst->mInstAlign, typeInst->mInstSize);
  7003. sizeValue = GetConstValue(typeInst->mInstSize);
  7004. toType = mBfIRBuilder->MapTypeInstPtr(typeInst);
  7005. }
  7006. else
  7007. {
  7008. EmitAppendAlign(type->mAlign, type->mSize);
  7009. sizeValue = GetConstValue(type->mSize);
  7010. auto toPtrType = CreatePointerType(type);
  7011. toType = mBfIRBuilder->MapType(toPtrType);
  7012. }
  7013. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  7014. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, sizeValue);
  7015. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  7016. retTypeInstance = typeInst;
  7017. retValue = mBfIRBuilder->CreateIntToPtr(curIdxVal, toType);
  7018. }
  7019. if ((retTypeInstance != NULL) && (retTypeInstance->IsObject()))
  7020. {
  7021. mBfIRBuilder->PopulateType(retTypeInstance);
  7022. auto int8Type = mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8);
  7023. auto ptrType = mBfIRBuilder->GetPointerTo(int8Type);
  7024. auto ptrPtrType = mBfIRBuilder->GetPointerTo(ptrType);
  7025. auto curThis = GetThis();
  7026. BfIRValue newFlags;
  7027. if (mCompiler->mOptions.mObjectHasDebugFlags)
  7028. {
  7029. auto thisFlagsPtr = mBfIRBuilder->CreateBitCast(curThis.mValue, ptrType);
  7030. auto thisFlags = mBfIRBuilder->CreateLoad(thisFlagsPtr);
  7031. auto maskedThisFlags = mBfIRBuilder->CreateAnd(thisFlags, GetConstValue8(BfObjectFlag_StackAlloc)); // Take 'stack' flag from 'this'
  7032. newFlags = mBfIRBuilder->CreateOr(maskedThisFlags, GetConstValue8(BfObjectFlag_AppendAlloc));
  7033. }
  7034. auto vObjectAddr = mBfIRBuilder->CreateInBoundsGEP(retValue, 0, 0);
  7035. auto vDataRef = CreateClassVDataGlobal(retTypeInstance);
  7036. auto destAddr = mBfIRBuilder->CreateBitCast(vObjectAddr, ptrPtrType);
  7037. auto srcVal = mBfIRBuilder->CreateBitCast(vDataRef, ptrType);
  7038. mBfIRBuilder->CreateStore(srcVal, destAddr);
  7039. if (mCompiler->mOptions.mObjectHasDebugFlags)
  7040. {
  7041. auto flagsPtr = mBfIRBuilder->CreateBitCast(destAddr, ptrType);
  7042. mBfIRBuilder->CreateStore(newFlags, flagsPtr);
  7043. }
  7044. }
  7045. if (appendSizeValue)
  7046. {
  7047. EmitAppendAlign(appendAllocAlign);
  7048. auto curIdxVal = mBfIRBuilder->CreateLoad(appendIdxVal.mValue);
  7049. auto newIdxVal = mBfIRBuilder->CreateAdd(curIdxVal, appendSizeValue);
  7050. mBfIRBuilder->CreateStore(newIdxVal, appendIdxVal.mValue);
  7051. }
  7052. return retValue;
  7053. }
  7054. bool BfModule::IsOptimized()
  7055. {
  7056. if (mProject == NULL)
  7057. return false;
  7058. int optLevel = GetModuleOptions().mOptLevel;
  7059. return (optLevel >= BfOptLevel_O1) && (optLevel <= BfOptLevel_O3);
  7060. }
  7061. bool BfModule::IsTargetingBeefBackend()
  7062. {
  7063. if (mProject == NULL)
  7064. return false;
  7065. return GetModuleOptions().mOptLevel == BfOptLevel_OgPlus;
  7066. }
  7067. bool BfModule::WantsLifetimes()
  7068. {
  7069. if (mProject == NULL)
  7070. return false;
  7071. return GetModuleOptions().mOptLevel == BfOptLevel_OgPlus;
  7072. }
  7073. bool BfModule::HasCompiledOutput()
  7074. {
  7075. return (!mSystem->mIsResolveOnly) && (mIsReified);
  7076. }
  7077. // We will skip the object access check for any occurances of this value
  7078. void BfModule::SkipObjectAccessCheck(BfTypedValue typedVal)
  7079. {
  7080. if ((mBfIRBuilder->mIgnoreWrites) || (!typedVal.mType->IsObjectOrInterface()) || (mCurMethodState == NULL) || (mCurMethodState->mIgnoreObjectAccessCheck))
  7081. return;
  7082. if (!mCompiler->mOptions.mObjectHasDebugFlags)
  7083. return;
  7084. if ((typedVal.mValue.mFlags & BfIRValueFlags_Value) == 0)
  7085. return;
  7086. mCurMethodState->mSkipObjectAccessChecks.Add(typedVal.mValue.mId);
  7087. }
  7088. void BfModule::EmitObjectAccessCheck(BfTypedValue typedVal)
  7089. {
  7090. if ((mBfIRBuilder->mIgnoreWrites) || (!typedVal.mType->IsObjectOrInterface()) || (mCurMethodState == NULL) || (mCurMethodState->mIgnoreObjectAccessCheck))
  7091. return;
  7092. if (!mCompiler->mOptions.mObjectHasDebugFlags)
  7093. return;
  7094. bool emitObjectAccessCheck = mCompiler->mOptions.mEmitObjectAccessCheck;
  7095. auto typeOptions = GetTypeOptions();
  7096. if (typeOptions != NULL)
  7097. emitObjectAccessCheck = BfTypeOptions::Apply(emitObjectAccessCheck, typeOptions->mEmitObjectAccessCheck);
  7098. if (!emitObjectAccessCheck)
  7099. return;
  7100. if ((typedVal.mValue.mFlags & BfIRValueFlags_Value) != 0)
  7101. {
  7102. if (mCurMethodState->mSkipObjectAccessChecks.Contains(typedVal.mValue.mId))
  7103. return;
  7104. }
  7105. if (typedVal.IsAddr())
  7106. typedVal = LoadValue(typedVal);
  7107. mBfIRBuilder->CreateObjectAccessCheck(typedVal.mValue, !IsOptimized());
  7108. }
  7109. void BfModule::EmitEnsureInstructionAt()
  7110. {
  7111. if (mProject == NULL)
  7112. return;
  7113. if ((mBfIRBuilder->mIgnoreWrites) || (!mHasFullDebugInfo) || (IsOptimized()) || (mCompiler->mOptions.mOmitDebugHelpers))
  7114. return;
  7115. mBfIRBuilder->CreateEnsureInstructionAt();
  7116. }
  7117. void BfModule::EmitDynamicCastCheck(const BfTypedValue& targetValue, BfType* targetType, BfIRBlock trueBlock, BfIRBlock falseBlock, bool nullSucceeds)
  7118. {
  7119. if (mBfIRBuilder->mIgnoreWrites)
  7120. return; // Nothing needed here
  7121. auto irb = mBfIRBuilder;
  7122. auto checkBB = irb->CreateBlock("as.check");
  7123. auto isNull = irb->CreateIsNull(targetValue.mValue);
  7124. mBfIRBuilder->CreateCondBr(isNull, nullSucceeds ? trueBlock : falseBlock, checkBB);
  7125. auto intType = GetPrimitiveType(BfTypeCode_IntPtr);
  7126. auto intPtrType = CreatePointerType(intType);
  7127. auto intPtrPtrType = CreatePointerType(intPtrType);
  7128. auto int32Type = GetPrimitiveType(BfTypeCode_Int32);
  7129. auto int32PtrType = CreatePointerType(int32Type);
  7130. auto typeTypeInstance = ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef)->ToTypeInstance();
  7131. if (mCompiler->mOptions.mAllowHotSwapping)
  7132. {
  7133. BfExprEvaluator exprEvaluator(this);
  7134. AddBasicBlock(checkBB);
  7135. auto objectParam = mBfIRBuilder->CreateBitCast(targetValue.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType));
  7136. auto moduleMethodInstance = GetMethodByName(mContext->mBfObjectType, targetType->IsInterface() ? "DynamicCastToInterface" : "DynamicCastToTypeId");
  7137. SizedArray<BfIRValue, 4> irArgs;
  7138. irArgs.push_back(objectParam);
  7139. irArgs.push_back(GetConstValue32(targetType->mTypeId));
  7140. auto callResult = exprEvaluator.CreateCall(moduleMethodInstance.mMethodInstance, moduleMethodInstance.mFunc, false, irArgs);
  7141. auto resultType = ResolveTypeDef(mSystem->mTypeBool);
  7142. auto cmpResult = mBfIRBuilder->CreateCmpNE(callResult.mValue, GetDefaultValue(callResult.mType));
  7143. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  7144. }
  7145. else
  7146. {
  7147. AddBasicBlock(checkBB);
  7148. BfIRValue vDataPtr = irb->CreateBitCast(targetValue.mValue, irb->MapType(intPtrType));
  7149. vDataPtr = irb->CreateLoad(vDataPtr);
  7150. if (mCompiler->mOptions.mObjectHasDebugFlags)
  7151. vDataPtr = irb->CreateAnd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, (uint64)~0xFFULL));
  7152. if (targetType->IsInterface())
  7153. {
  7154. auto targetTypeInst = targetType->ToTypeInstance();
  7155. AddDependency(targetType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  7156. // Skip past mType, but since a 'GetDynCastVDataCount()' data is included in the sSlotOfs, we need to remove that
  7157. //int inheritanceIdOfs = mSystem->mPtrSize - (mCompiler->GetDynCastVDataCount())*4;
  7158. //vDataPtr = irb->CreateAdd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, inheritanceIdOfs));
  7159. vDataPtr = irb->CreateAdd(vDataPtr, irb->GetConfigConst(BfIRConfigConst_DynSlotOfs, BfTypeCode_IntPtr));
  7160. BfIRValue slotOfs = GetInterfaceSlotNum(targetType->ToTypeInstance());
  7161. BfIRValue slotByteOfs = irb->CreateMul(slotOfs, irb->CreateConst(BfTypeCode_Int32, 4));
  7162. slotByteOfs = irb->CreateNumericCast(slotByteOfs, false, BfTypeCode_IntPtr);
  7163. vDataPtr = irb->CreateAdd(vDataPtr, slotByteOfs);
  7164. vDataPtr = irb->CreateIntToPtr(vDataPtr, irb->MapType(int32PtrType));
  7165. BfIRValue typeId = irb->CreateLoad(vDataPtr);
  7166. BfIRValue cmpResult = irb->CreateCmpEQ(typeId, irb->CreateConst(BfTypeCode_Int32, targetType->mTypeId));
  7167. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  7168. }
  7169. else
  7170. {
  7171. if (!targetType->IsTypeInstance())
  7172. targetType = GetWrappedStructType(targetType);
  7173. AddDependency(targetType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  7174. int inheritanceIdOfs = mSystem->mPtrSize;
  7175. vDataPtr = irb->CreateAdd(vDataPtr, irb->CreateConst(BfTypeCode_IntPtr, inheritanceIdOfs));
  7176. vDataPtr = irb->CreateIntToPtr(vDataPtr, irb->MapType(int32PtrType));
  7177. BfIRValue objInheritanceId = irb->CreateLoad(vDataPtr);
  7178. BfIRValue typeDataRef = CreateTypeDataRef(targetType);
  7179. BfIRValue typeInstDataRef = irb->CreateBitCast(typeDataRef, irb->MapType(typeTypeInstance, BfIRPopulateType_Full));
  7180. auto fieldInst = &typeTypeInstance->mFieldInstances[9];
  7181. BF_ASSERT(fieldInst->GetFieldDef()->mName == "mInheritanceId");
  7182. BfIRValue gepValue = irb->CreateInBoundsGEP(typeInstDataRef, 0, fieldInst->mDataIdx);
  7183. BfIRValue wantInheritanceId = irb->CreateLoad(gepValue);
  7184. fieldInst = &typeTypeInstance->mFieldInstances[10];
  7185. BF_ASSERT(fieldInst->GetFieldDef()->mName == "mInheritanceCount");
  7186. gepValue = irb->CreateInBoundsGEP(typeInstDataRef, 0, fieldInst->mDataIdx);
  7187. BfIRValue inheritanceCount = irb->CreateLoad(gepValue);
  7188. BfIRValue idDiff = irb->CreateSub(objInheritanceId, wantInheritanceId);
  7189. BfIRValue cmpResult = irb->CreateCmpLTE(idDiff, inheritanceCount, false);
  7190. irb->CreateCondBr(cmpResult, trueBlock, falseBlock);
  7191. }
  7192. }
  7193. }
  7194. void BfModule::EmitDynamicCastCheck(BfTypedValue typedVal, BfType* type, bool allowNull)
  7195. {
  7196. if (mBfIRBuilder->mIgnoreWrites)
  7197. return;
  7198. bool emitDynamicCastCheck = mCompiler->mOptions.mEmitDynamicCastCheck;
  7199. auto typeOptions = GetTypeOptions();
  7200. if (typeOptions != NULL)
  7201. emitDynamicCastCheck = BfTypeOptions::Apply(emitDynamicCastCheck, typeOptions->mEmitDynamicCastCheck);
  7202. if (emitDynamicCastCheck)
  7203. {
  7204. int wantTypeId = 0;
  7205. if (!type->IsGenericParam())
  7206. wantTypeId = type->mTypeId;
  7207. BfIRBlock failBlock = mBfIRBuilder->CreateBlock("dynFail");
  7208. BfIRBlock endBlock = mBfIRBuilder->CreateBlock("dynEnd");
  7209. EmitDynamicCastCheck(typedVal, type, endBlock, failBlock, allowNull ? true : false);
  7210. AddBasicBlock(failBlock);
  7211. SizedArray<BfIRValue, 8> llvmArgs;
  7212. auto bitAddr = mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType));
  7213. llvmArgs.push_back(bitAddr);
  7214. llvmArgs.push_back(GetConstValue32(wantTypeId));
  7215. auto objDynCheck = GetInternalMethod("ObjectDynCheckFailed");
  7216. BF_ASSERT(objDynCheck);
  7217. if (objDynCheck)
  7218. {
  7219. auto callInst = mBfIRBuilder->CreateCall(objDynCheck.mFunc, llvmArgs);
  7220. }
  7221. mBfIRBuilder->CreateBr(endBlock);
  7222. AddBasicBlock(endBlock);
  7223. }
  7224. }
  7225. BfTypedValue BfModule::BoxValue(BfAstNode* srcNode, BfTypedValue typedVal, BfType* toType, const BfAllocTarget& allocTarget, bool callDtor)
  7226. {
  7227. if (mBfIRBuilder->mIgnoreWrites)
  7228. {
  7229. if (toType == mContext->mBfObjectType)
  7230. return BfTypedValue(mBfIRBuilder->GetFakeVal(), toType);
  7231. }
  7232. BP_ZONE("BoxValue");
  7233. BfTypeInstance* fromStructTypeInstance = typedVal.mType->ToTypeInstance();
  7234. if (typedVal.mType->IsNullable())
  7235. {
  7236. typedVal = MakeAddressable(typedVal);
  7237. auto innerType = typedVal.mType->GetUnderlyingType();
  7238. if (!innerType->IsValueType())
  7239. {
  7240. if (!mIgnoreErrors)
  7241. Fail("Only value types can be boxed", srcNode);
  7242. return BfTypedValue();
  7243. }
  7244. auto boxedType = CreateBoxedType(innerType);
  7245. auto resultType = toType;
  7246. if (resultType == NULL)
  7247. resultType = boxedType;
  7248. if (mBfIRBuilder->mIgnoreWrites)
  7249. return BfTypedValue(mBfIRBuilder->GetFakeVal(), resultType);
  7250. auto prevBB = mBfIRBuilder->GetInsertBlock();
  7251. auto boxBB = mBfIRBuilder->CreateBlock("boxedN.notNull");
  7252. auto endBB = mBfIRBuilder->CreateBlock("boxedN.end");
  7253. mBfIRBuilder->PopulateType(typedVal.mType);
  7254. auto hasValueAddr = mBfIRBuilder->CreateInBoundsGEP(typedVal.mValue, 0, innerType->IsValuelessType() ? 1 : 2); // has_value
  7255. auto hasValue = mBfIRBuilder->CreateLoad(hasValueAddr);
  7256. mBfIRBuilder->CreateCondBr(hasValue, boxBB, endBB);
  7257. AddDependency(boxedType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  7258. mBfIRBuilder->AddBlock(boxBB);
  7259. mBfIRBuilder->SetInsertPoint(boxBB);
  7260. BfScopeData newScope;
  7261. newScope.mOuterIsConditional = true;
  7262. mCurMethodState->AddScope(&newScope);
  7263. NewScopeState();
  7264. BfIRValue nullableValueAddr;
  7265. BfIRValue loadedVal;
  7266. if (innerType->IsValuelessType())
  7267. {
  7268. loadedVal = mBfIRBuilder->GetFakeVal();
  7269. }
  7270. else
  7271. {
  7272. nullableValueAddr = mBfIRBuilder->CreateInBoundsGEP(typedVal.mValue, 0, 1); // value
  7273. loadedVal = mBfIRBuilder->CreateLoad(nullableValueAddr);
  7274. }
  7275. auto boxedVal = BoxValue(srcNode, BfTypedValue(loadedVal, fromStructTypeInstance->GetUnderlyingType()), resultType, allocTarget, callDtor);
  7276. RestoreScopeState();
  7277. if (!boxedVal)
  7278. return BfTypedValue();
  7279. mBfIRBuilder->CreateBr(endBB);
  7280. auto boxBBEnd = mBfIRBuilder->GetInsertBlock();
  7281. mBfIRBuilder->AddBlock(endBB);
  7282. mBfIRBuilder->SetInsertPoint(endBB);
  7283. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapType(resultType), 2);
  7284. mBfIRBuilder->AddPhiIncoming(phi, boxedVal.mValue, boxBBEnd);
  7285. mBfIRBuilder->AddPhiIncoming(phi, GetDefaultValue(resultType), prevBB);
  7286. return BfTypedValue(phi, resultType);
  7287. }
  7288. bool alreadyCheckedCast = false;
  7289. BfTypeInstance* toTypeInstance = NULL;
  7290. if (toType != NULL)
  7291. toTypeInstance = toType->ToTypeInstance();
  7292. bool isStructPtr = typedVal.mType->IsStructPtr();
  7293. if (fromStructTypeInstance == NULL)
  7294. {
  7295. auto primType = (BfPrimitiveType*)typedVal.mType;
  7296. fromStructTypeInstance = GetWrappedStructType(typedVal.mType);
  7297. if (isStructPtr)
  7298. {
  7299. if ((toTypeInstance != NULL) && (TypeIsSubTypeOf(fromStructTypeInstance, toTypeInstance)))
  7300. alreadyCheckedCast = true;
  7301. fromStructTypeInstance = typedVal.mType->GetUnderlyingType()->ToTypeInstance();
  7302. }
  7303. }
  7304. if (fromStructTypeInstance == NULL)
  7305. return BfTypedValue();
  7306. // Need to box it
  7307. bool isBoxedType = (fromStructTypeInstance != NULL) && (toType->IsBoxed());
  7308. if ((toType == NULL) || (toType == mContext->mBfObjectType) || (isBoxedType) || (alreadyCheckedCast) || (TypeIsSubTypeOf(fromStructTypeInstance, toTypeInstance)))
  7309. {
  7310. if (mBfIRBuilder->mIgnoreWrites)
  7311. return BfTypedValue(mBfIRBuilder->GetFakeVal(), (toType != NULL) ? toType : CreateBoxedType(typedVal.mType));
  7312. auto boxedType = CreateBoxedType(typedVal.mType);
  7313. mBfIRBuilder->PopulateType(boxedType);
  7314. AddDependency(boxedType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  7315. auto allocaInst = AllocFromType(boxedType, allocTarget, BfIRValue(), BfIRValue(), 0, callDtor ? BfAllocFlags_None : BfAllocFlags_NoDtorCall);
  7316. BfTypedValue boxedTypedValue(allocaInst, boxedType);
  7317. mBfIRBuilder->SetName(allocaInst, "boxed." + fromStructTypeInstance->mTypeDef->mName->ToString());
  7318. if (boxedType->IsUnspecializedType())
  7319. {
  7320. BF_ASSERT((srcNode == NULL) || (mCurMethodInstance->mIsUnspecialized));
  7321. }
  7322. else
  7323. {
  7324. PopulateType(fromStructTypeInstance);
  7325. if (!fromStructTypeInstance->IsValuelessType())
  7326. {
  7327. typedVal = LoadValue(typedVal);
  7328. auto valPtr = mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 1);
  7329. if ((typedVal.mType != fromStructTypeInstance) && (!isStructPtr))
  7330. {
  7331. auto ptrType = CreatePointerType(typedVal.mType);
  7332. valPtr = mBfIRBuilder->CreateBitCast(valPtr, mBfIRBuilder->MapType(ptrType));
  7333. }
  7334. if (typedVal.IsSplat())
  7335. {
  7336. AggregateSplatIntoAddr(typedVal, valPtr);
  7337. }
  7338. else
  7339. mBfIRBuilder->CreateStore(typedVal.mValue, valPtr);
  7340. }
  7341. }
  7342. if (toType == NULL)
  7343. {
  7344. return BfTypedValue(allocaInst, boxedType);
  7345. }
  7346. else
  7347. {
  7348. auto castedValue = mBfIRBuilder->CreateBitCast(allocaInst, mBfIRBuilder->MapType(toType));
  7349. return BfTypedValue(castedValue, toType);
  7350. }
  7351. }
  7352. return BfTypedValue();
  7353. }
  7354. bool BfModule::GetBasePropertyDef(BfPropertyDef*& propDef, BfTypeInstance*& typeInst)
  7355. {
  7356. BfTypeInstance* checkTypeInst = typeInst;
  7357. while (checkTypeInst != NULL)
  7358. {
  7359. for (auto checkProp : checkTypeInst->mTypeDef->mProperties)
  7360. {
  7361. if (checkProp->mName == propDef->mName)
  7362. {
  7363. auto checkPropDeclaration = BfNodeDynCast<BfPropertyDeclaration>(checkProp->mFieldDeclaration);
  7364. if ((checkPropDeclaration == NULL) || (checkPropDeclaration->mVirtualSpecifier == NULL) || (checkPropDeclaration->mVirtualSpecifier->GetToken() == BfToken_Virtual))
  7365. {
  7366. propDef = checkProp;
  7367. typeInst = checkTypeInst;
  7368. return true;
  7369. }
  7370. }
  7371. }
  7372. checkTypeInst = checkTypeInst->mBaseType;
  7373. }
  7374. return false;
  7375. }
  7376. BfMethodInstance* BfModule::GetRawMethodInstanceAtIdx(BfTypeInstance* typeInstance, int methodIdx, const char* assertName)
  7377. {
  7378. if (!typeInstance->mResolvingVarField)
  7379. {
  7380. if (typeInstance->IsIncomplete())
  7381. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7382. }
  7383. else
  7384. {
  7385. if (methodIdx >= (int)typeInstance->mMethodInstanceGroups.size())
  7386. {
  7387. AssertErrorState();
  7388. return NULL;
  7389. }
  7390. }
  7391. if (assertName != NULL)
  7392. {
  7393. BF_ASSERT(typeInstance->mTypeDef->mMethods[methodIdx]->mName == assertName);
  7394. }
  7395. auto& methodGroup = typeInstance->mMethodInstanceGroups[methodIdx];
  7396. if (methodGroup.mDefault == NULL)
  7397. {
  7398. if (!mCompiler->mIsResolveOnly)
  7399. {
  7400. BF_ASSERT((methodGroup.mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference) || (methodGroup.mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl));
  7401. methodGroup.mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingDecl;
  7402. // Get it from the owning module so we don't create a reference prematurely...
  7403. auto declModule = typeInstance->mModule;
  7404. return declModule->GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector(), (BfGetMethodInstanceFlags)(BfGetMethodInstanceFlag_UnspecializedPass | BfGetMethodInstanceFlag_Unreified)).mMethodInstance;
  7405. }
  7406. else
  7407. {
  7408. auto declModule = typeInstance->mModule;
  7409. return declModule->GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector(), (BfGetMethodInstanceFlags)(BfGetMethodInstanceFlag_UnspecializedPass)).mMethodInstance;
  7410. }
  7411. }
  7412. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  7413. //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
  7414. // be from a call to the NON-raw version
  7415. // if (!methodInstance->mMethodInstanceGroup->IsImplemented())
  7416. // {
  7417. // methodInstance->mIsReified = mIsReified;
  7418. // if (methodInstance->mMethodProcessRequest == NULL)
  7419. // typeInstance->mModule->AddMethodToWorkList(methodInstance);
  7420. // }
  7421. return methodInstance;
  7422. }
  7423. BfMethodInstance* BfModule::GetRawMethodInstance(BfTypeInstance* typeInstance, BfMethodDef* methodDef)
  7424. {
  7425. if (methodDef->mIsLocalMethod)
  7426. {
  7427. return GetMethodInstance(typeInstance, methodDef, BfTypeVector()).mMethodInstance;
  7428. }
  7429. return GetRawMethodInstanceAtIdx(typeInstance, methodDef->mIdx);
  7430. }
  7431. BfMethodInstance* BfModule::GetRawMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase, bool allowMixin)
  7432. {
  7433. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7434. while (typeInstance != NULL)
  7435. {
  7436. typeInstance->mTypeDef->PopulateMemberSets();
  7437. BfMemberSetEntry* entry = NULL;
  7438. BfMethodDef* methodDef = NULL;
  7439. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  7440. methodDef = (BfMethodDef*)entry->mMemberDef;
  7441. while (methodDef != NULL)
  7442. {
  7443. if (((allowMixin) || (methodDef->mMethodType != BfMethodType_Mixin)) &&
  7444. (methodDef->mGenericParams.size() == 0) &&
  7445. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  7446. return GetRawMethodInstance(typeInstance, methodDef);
  7447. methodDef = methodDef->mNextWithSameName;
  7448. }
  7449. if (!checkBase)
  7450. break;
  7451. typeInstance = typeInstance->mBaseType;
  7452. }
  7453. return NULL;
  7454. }
  7455. BfMethodInstance* BfModule::GetUnspecializedMethodInstance(BfMethodInstance* methodInstance)
  7456. {
  7457. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mMethodGenericArguments.size() != 0))
  7458. methodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  7459. auto owner = methodInstance->mMethodInstanceGroup->mOwner;
  7460. if (!owner->IsGenericTypeInstance())
  7461. return methodInstance;
  7462. auto genericType = (BfGenericTypeInstance*)owner;
  7463. if (genericType->IsUnspecializedType())
  7464. return methodInstance;
  7465. auto unspecializedType = ResolveTypeDef(genericType->mTypeDef);
  7466. if (unspecializedType == NULL)
  7467. {
  7468. AssertErrorState();
  7469. return methodInstance;
  7470. }
  7471. if (unspecializedType == NULL)
  7472. return methodInstance;
  7473. auto unspecializedTypeInst = unspecializedType->ToTypeInstance();
  7474. return GetRawMethodInstanceAtIdx(unspecializedTypeInst, methodInstance->mMethodDef->mIdx);
  7475. }
  7476. int BfModule::GetGenericParamAndReturnCount(BfMethodInstance* methodInstance)
  7477. {
  7478. int genericCount = 0;
  7479. auto unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance);
  7480. for (int paramIdx = 0; paramIdx < unspecializedMethodInstance->GetParamCount(); paramIdx++)
  7481. {
  7482. auto param = unspecializedMethodInstance->GetParamType(paramIdx);
  7483. if (param->IsGenericParam())
  7484. genericCount++;
  7485. }
  7486. if (unspecializedMethodInstance->mReturnType->IsGenericParam())
  7487. genericCount++;
  7488. return genericCount;
  7489. }
  7490. BfModule* BfModule::GetSpecializedMethodModule(const SizedArrayImpl<BfProject*>& projectList)
  7491. {
  7492. BF_ASSERT(!mIsScratchModule);
  7493. BF_ASSERT(mIsReified);
  7494. BfModule* mainModule = this;
  7495. if (mParentModule != NULL)
  7496. mainModule = mParentModule;
  7497. BfModule* specModule = NULL;
  7498. BfModule** specModulePtr = NULL;
  7499. if (mainModule->mSpecializedMethodModules.TryGetValueWith(projectList, &specModulePtr))
  7500. {
  7501. return *specModulePtr;
  7502. }
  7503. else
  7504. {
  7505. String specModuleName = mModuleName;
  7506. for (auto bfProject : projectList)
  7507. specModuleName += StrFormat("@%s", bfProject->mName.c_str());
  7508. specModule = new BfModule(mContext, specModuleName);
  7509. specModule->mProject = mainModule->mProject;
  7510. specModule->mParentModule = mainModule;
  7511. specModule->mIsSpecializedMethodModuleRoot = true;
  7512. specModule->Init();
  7513. Array<BfProject*> projList;
  7514. for (auto project : projectList)
  7515. projList.Add(project);
  7516. mainModule->mSpecializedMethodModules[projList] = specModule;
  7517. }
  7518. return specModule;
  7519. }
  7520. BfIRValue BfModule::CreateFunctionFrom(BfMethodInstance* methodInstance, bool tryExisting, bool isInlined)
  7521. {
  7522. if (mCompiler->IsSkippingExtraResolveChecks())
  7523. return BfIRValue();
  7524. if (methodInstance->mMethodInstanceGroup->mOwner->IsInterface())
  7525. {
  7526. //BF_ASSERT(!methodInstance->mIRFunction);
  7527. return BfIRValue();
  7528. }
  7529. auto methodDef = methodInstance->mMethodDef;
  7530. StringT<128> methodName;
  7531. BfMangler::Mangle(methodName, mCompiler->GetMangleKind(), methodInstance);
  7532. if (isInlined != methodInstance->mAlwaysInline)
  7533. {
  7534. if (isInlined)
  7535. methodName += "__INLINE";
  7536. else
  7537. methodName += "__NOINLINE";
  7538. }
  7539. if (tryExisting)
  7540. {
  7541. auto func = mBfIRBuilder->GetFunction(methodName);
  7542. if (func)
  7543. return func;
  7544. }
  7545. if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  7546. {
  7547. if (methodDeclaration->mExternSpecifier != NULL)
  7548. {
  7549. auto intrinsic = GetIntrinsic(methodInstance);
  7550. if (intrinsic)
  7551. return intrinsic;
  7552. // If we have multiple entries with the same name, they could have different arguments and will generate other errors...
  7553. /*auto func = mBfIRBuilder->GetFunction(methodName);
  7554. if (func)
  7555. return func;*/
  7556. }
  7557. }
  7558. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  7559. {
  7560. return CreateDllImportGlobalVar(methodInstance, false);
  7561. }
  7562. BfIRType returnType;
  7563. SizedArray<BfIRType, 8> paramTypes;
  7564. methodInstance->GetIRFunctionInfo(this, returnType, paramTypes);
  7565. auto funcType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes);
  7566. auto func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, methodName);
  7567. auto callingConv = GetCallingConvention(methodInstance->GetOwner(), methodDef);
  7568. if (callingConv != BfIRCallingConv_CDecl)
  7569. mBfIRBuilder->SetFuncCallingConv(func, callingConv);
  7570. SetupIRMethod(methodInstance, func, isInlined);
  7571. // auto srcModule = methodInstance->GetOwner()->GetModule();
  7572. // if ((srcModule != NULL) && (srcModule->mProject != mProject))
  7573. // {
  7574. // if (srcModule->mProject->mTargetType == BfTargetType_BeefDynLib)
  7575. // {
  7576. // mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_DllImport);
  7577. // }
  7578. // }
  7579. return func;
  7580. }
  7581. BfModuleMethodInstance BfModule::GetMethodInstanceAtIdx(BfTypeInstance* typeInstance, int methodIdx, const char* assertName)
  7582. {
  7583. if (assertName != NULL)
  7584. {
  7585. BF_ASSERT(typeInstance->mTypeDef->mMethods[methodIdx]->mName == assertName);
  7586. }
  7587. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7588. auto methodInstance = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  7589. if ((methodInstance != NULL) && (mIsReified) && (!methodInstance->mIsReified))
  7590. {
  7591. // Can't use it, not reified
  7592. methodInstance = NULL;
  7593. }
  7594. if ((methodInstance != NULL) && (mBfIRBuilder != NULL) && (mBfIRBuilder->mIgnoreWrites) &&
  7595. (methodInstance->mMethodInstanceGroup->IsImplemented()))
  7596. {
  7597. BfIRFunction func(mBfIRBuilder->GetFakeVal());
  7598. return BfModuleMethodInstance(methodInstance, func);
  7599. }
  7600. return GetMethodInstance(typeInstance, typeInstance->mTypeDef->mMethods[methodIdx], BfTypeVector());
  7601. }
  7602. BfModuleMethodInstance BfModule::GetMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  7603. {
  7604. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7605. while (typeInstance != NULL)
  7606. {
  7607. typeInstance->mTypeDef->PopulateMemberSets();
  7608. BfMemberSetEntry* entry = NULL;
  7609. BfMethodDef* methodDef = NULL;
  7610. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  7611. methodDef = (BfMethodDef*)entry->mMemberDef;
  7612. while (methodDef != NULL)
  7613. {
  7614. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  7615. (methodDef->mGenericParams.size() == 0) &&
  7616. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  7617. return GetMethodInstanceAtIdx(typeInstance, methodDef->mIdx);
  7618. methodDef = methodDef->mNextWithSameName;
  7619. }
  7620. if (!checkBase)
  7621. break;
  7622. typeInstance = typeInstance->mBaseType;
  7623. }
  7624. return BfModuleMethodInstance();
  7625. }
  7626. BfModuleMethodInstance BfModule::GetMethodByName(BfTypeInstance* typeInstance, const StringImpl& methodName, const Array<BfType*>& paramTypes, bool checkBase)
  7627. {
  7628. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7629. while (typeInstance != NULL)
  7630. {
  7631. typeInstance->mTypeDef->PopulateMemberSets();
  7632. BfMemberSetEntry* entry = NULL;
  7633. BfMethodDef* methodDef = NULL;
  7634. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  7635. methodDef = (BfMethodDef*)entry->mMemberDef;
  7636. while (methodDef != NULL)
  7637. {
  7638. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  7639. (methodDef->mGenericParams.size() == 0) &&
  7640. (paramTypes.size() == methodDef->mParams.size()))
  7641. {
  7642. auto moduleMethodInstance = GetMethodInstanceAtIdx(typeInstance, methodDef->mIdx);
  7643. if (moduleMethodInstance.mMethodInstance != NULL)
  7644. {
  7645. bool matches = true;
  7646. for (int paramIdx = 0; paramIdx < (int)paramTypes.size(); paramIdx++)
  7647. {
  7648. if (moduleMethodInstance.mMethodInstance->GetParamType(paramIdx) != paramTypes[paramIdx])
  7649. matches = false;
  7650. }
  7651. if (matches)
  7652. return moduleMethodInstance;
  7653. }
  7654. }
  7655. methodDef = methodDef->mNextWithSameName;
  7656. }
  7657. if (!checkBase)
  7658. break;
  7659. typeInstance = typeInstance->mBaseType;
  7660. }
  7661. return BfModuleMethodInstance();
  7662. }
  7663. BfModuleMethodInstance BfModule::GetInternalMethod(const StringImpl& methodName, int paramCount)
  7664. {
  7665. auto internalType = ResolveTypeDef(mCompiler->mInternalTypeDef);
  7666. PopulateType(internalType);
  7667. auto moduleMethodInstance = GetMethodByName(internalType->ToTypeInstance(), methodName, paramCount);
  7668. if (!moduleMethodInstance)
  7669. {
  7670. Fail(StrFormat("Failed to find System.Internal method '%s'", methodName.c_str()));
  7671. }
  7672. return moduleMethodInstance;
  7673. }
  7674. bool BfModule::IsMethodImplementedAndReified(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  7675. {
  7676. while (typeInstance != NULL)
  7677. {
  7678. typeInstance->mTypeDef->PopulateMemberSets();
  7679. BfMemberSetEntry* entry = NULL;
  7680. BfMethodDef* methodDef = NULL;
  7681. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  7682. methodDef = (BfMethodDef*)entry->mMemberDef;
  7683. while (methodDef != NULL)
  7684. {
  7685. if ((methodDef->mMethodType != BfMethodType_Mixin) &&
  7686. (methodDef->mGenericParams.size() == 0) &&
  7687. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  7688. {
  7689. auto& methodInstanceGroup = typeInstance->mMethodInstanceGroups[methodDef->mIdx];
  7690. if (!methodInstanceGroup.IsImplemented())
  7691. return false;
  7692. if (methodInstanceGroup.mDefault == NULL)
  7693. return false;
  7694. return methodInstanceGroup.mDefault->mIsReified;
  7695. }
  7696. methodDef = methodDef->mNextWithSameName;
  7697. }
  7698. if (!checkBase)
  7699. break;
  7700. typeInstance = typeInstance->mBaseType;
  7701. }
  7702. return false;
  7703. }
  7704. bool BfModule::HasMixin(BfTypeInstance* typeInstance, const StringImpl& methodName, int paramCount, bool checkBase)
  7705. {
  7706. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7707. while (typeInstance != NULL)
  7708. {
  7709. typeInstance->mTypeDef->PopulateMemberSets();
  7710. BfMemberSetEntry* entry = NULL;
  7711. BfMethodDef* methodDef = NULL;
  7712. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(methodName, &entry))
  7713. methodDef = (BfMethodDef*)entry->mMemberDef;
  7714. while (methodDef != NULL)
  7715. {
  7716. if ((methodDef->mMethodType == BfMethodType_Mixin) &&
  7717. ((paramCount == -1) || (paramCount == (int)methodDef->mParams.size())))
  7718. return true;
  7719. methodDef = methodDef->mNextWithSameName;
  7720. }
  7721. if (!checkBase)
  7722. break;
  7723. typeInstance = typeInstance->mBaseType;
  7724. }
  7725. return BfModuleMethodInstance();
  7726. }
  7727. BfFieldInstance* BfModule::GetFieldByName(BfTypeInstance* typeInstance, const StringImpl& fieldName)
  7728. {
  7729. PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7730. typeInstance->mTypeDef->PopulateMemberSets();
  7731. BfMemberSetEntry* entry = NULL;
  7732. BfFieldDef* fieldDef = NULL;
  7733. if (typeInstance->mTypeDef->mFieldSet.TryGetWith(fieldName, &entry))
  7734. {
  7735. fieldDef = (BfFieldDef*)entry->mMemberDef;
  7736. return &typeInstance->mFieldInstances[fieldDef->mIdx];
  7737. }
  7738. // for (auto& fieldInst : typeInstance->mFieldInstances)
  7739. // {
  7740. // auto fieldDef = fieldInst.GetFieldDef();
  7741. // if ((fieldDef != NULL) && (fieldDef->mName == fieldName))
  7742. // return &fieldInst;
  7743. // }
  7744. return NULL;
  7745. }
  7746. String BfModule::MethodToString(BfMethodInstance* methodInst, BfMethodNameFlags methodNameFlags, BfTypeVector* methodGenericArgs)
  7747. {
  7748. auto methodDef = methodInst->mMethodDef;
  7749. bool allowResolveGenericParamNames = ((methodNameFlags & BfMethodNameFlag_ResolveGenericParamNames) != 0);
  7750. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  7751. if ((mCurTypeInstance == NULL) || (!mCurTypeInstance->IsUnspecializedTypeVariation()))
  7752. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  7753. BfType* type = methodInst->mMethodInstanceGroup->mOwner;
  7754. if ((methodGenericArgs != NULL) && (type->IsUnspecializedType()))
  7755. type = ResolveGenericType(type, *methodGenericArgs);
  7756. String methodName;
  7757. if ((methodNameFlags & BfMethodNameFlag_OmitTypeName) == 0)
  7758. {
  7759. methodName = TypeToString(type, typeNameFlags);
  7760. if (methodName == "$")
  7761. methodName = "";
  7762. else
  7763. methodName += ".";
  7764. }
  7765. String accessorString;
  7766. StringT<64> methodDefName = methodInst->mMethodDef->mName;
  7767. if (methodInst->mMethodDef->mIsLocalMethod)
  7768. {
  7769. int atPos = (int)methodDefName.IndexOf('$');
  7770. methodDefName.RemoveToEnd(atPos);
  7771. methodDefName.Replace("@", ".");
  7772. }
  7773. else
  7774. {
  7775. int atPos = (int)methodDefName.IndexOf('$');
  7776. if (atPos != -1)
  7777. {
  7778. accessorString = methodDefName.Substring(0, atPos);
  7779. if ((accessorString == "get") || (accessorString == "set"))
  7780. {
  7781. methodDefName = methodDefName.Substring(atPos + 1);
  7782. }
  7783. else
  7784. accessorString = "";
  7785. }
  7786. }
  7787. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mForeignType != NULL))
  7788. {
  7789. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  7790. if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  7791. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  7792. methodName += TypeToString(methodInst->mMethodInfoEx->mForeignType, typeNameFlags);
  7793. methodName += ".";
  7794. }
  7795. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mExplicitInterface != NULL))
  7796. {
  7797. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  7798. if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  7799. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  7800. methodName += TypeToString(methodInst->mMethodInfoEx->mExplicitInterface, typeNameFlags);
  7801. methodName += ".";
  7802. }
  7803. if (methodDef->mMethodType == BfMethodType_Operator)
  7804. {
  7805. BfOperatorDef* operatorDef = (BfOperatorDef*)methodDef;
  7806. if (operatorDef->mOperatorDeclaration->mIsConvOperator)
  7807. {
  7808. // Don't add explicit/implicit part, since that's not available in GCC mangling
  7809. /*if (operatorDef->mOperatorDeclaration->mExplicitToken != NULL)
  7810. {
  7811. if (operatorDef->mOperatorDeclaration->mExplicitToken->GetToken() == BfToken_Explicit)
  7812. methodName += "explicit ";
  7813. else if (operatorDef->mOperatorDeclaration->mExplicitToken->GetToken() == BfToken_Explicit)
  7814. methodName += "explicit ";
  7815. }*/
  7816. methodName += "operator ";
  7817. if (methodInst->mReturnType != NULL)
  7818. methodName += TypeToString(methodInst->mReturnType);
  7819. }
  7820. else
  7821. {
  7822. methodName += "operator";
  7823. if (operatorDef->mOperatorDeclaration->mOpTypeToken != NULL)
  7824. methodName += BfTokenToString(operatorDef->mOperatorDeclaration->mOpTypeToken->GetToken());
  7825. }
  7826. }
  7827. else if (methodDef->mMethodType == BfMethodType_Ctor)
  7828. {
  7829. if (methodDef->mIsStatic)
  7830. methodName += "__BfStaticCtor";
  7831. else
  7832. methodName += "this";
  7833. accessorString = "";
  7834. }
  7835. else if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  7836. {
  7837. methodDef->GetRefNode()->ToString(methodName);
  7838. methodName += " get accessor";
  7839. return methodName;
  7840. }
  7841. else if (methodDef->mMethodType == BfMethodType_PropertySetter)
  7842. {
  7843. methodDef->GetRefNode()->ToString(methodName);
  7844. methodName += " set accessor";
  7845. return methodName;
  7846. }
  7847. else
  7848. methodName += methodDefName;
  7849. BfTypeVector newMethodGenericArgs;
  7850. if ((methodInst->mMethodInfoEx != NULL) && (methodInst->mMethodInfoEx->mMethodGenericArguments.size() != 0))
  7851. {
  7852. methodName += "<";
  7853. for (int i = 0; i < (int) methodInst->mMethodInfoEx->mMethodGenericArguments.size(); i++)
  7854. {
  7855. if (i > 0)
  7856. methodName += ", ";
  7857. BfTypeNameFlags typeNameFlags = BfTypeNameFlags_None;
  7858. //Why did we have this methodInst->mIsUnspecializedVariation check? Sometimes we do need to show errors calling methods that refer back to our types
  7859. //if (!methodInst->mIsUnspecializedVariation && allowResolveGenericParamNames)
  7860. if (allowResolveGenericParamNames)
  7861. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  7862. BfType* type = methodInst->mMethodInfoEx->mMethodGenericArguments[i];
  7863. if ((methodGenericArgs != NULL) && (type->IsUnspecializedType()))
  7864. {
  7865. bool hasEmpty = false;
  7866. for (auto arg : *methodGenericArgs)
  7867. {
  7868. if (arg == NULL)
  7869. hasEmpty = true;
  7870. }
  7871. if (hasEmpty)
  7872. {
  7873. for (int genericIdx = 0; genericIdx < (int)methodGenericArgs->size(); genericIdx++)
  7874. {
  7875. auto arg = (*methodGenericArgs)[genericIdx];
  7876. if (arg != NULL)
  7877. newMethodGenericArgs.push_back(arg);
  7878. else
  7879. {
  7880. auto genericParamInst = methodInst->mMethodInfoEx->mGenericParams[genericIdx];
  7881. if (genericParamInst->mTypeConstraint != NULL)
  7882. newMethodGenericArgs.push_back(genericParamInst->mTypeConstraint);
  7883. else
  7884. newMethodGenericArgs.push_back(mContext->mBfObjectType); // Default
  7885. }
  7886. }
  7887. methodGenericArgs = &newMethodGenericArgs;
  7888. }
  7889. if (type->IsUnspecializedType())
  7890. type = ResolveGenericType(type, *methodGenericArgs);
  7891. }
  7892. methodName += TypeToString(type, typeNameFlags);
  7893. }
  7894. methodName += ">";
  7895. }
  7896. if (accessorString.length() == 0)
  7897. {
  7898. int dispParamIdx = 0;
  7899. methodName += "(";
  7900. for (int paramIdx = 0; paramIdx < (int) methodInst->GetParamCount(); paramIdx++)
  7901. {
  7902. int paramKind = methodInst->GetParamKind(paramIdx);
  7903. if (paramKind == BfParamKind_ImplicitCapture)
  7904. continue;
  7905. if (dispParamIdx > 0)
  7906. methodName += ", ";
  7907. if (paramKind == BfParamKind_Params)
  7908. methodName += "params ";
  7909. typeNameFlags = BfTypeNameFlag_ResolveGenericParamNames;
  7910. BfType* type = methodInst->GetParamType(paramIdx);
  7911. if ((methodGenericArgs != NULL) && (type->IsUnspecializedType()))
  7912. type = ResolveGenericType(type, *methodGenericArgs);
  7913. methodName += TypeToString(type, typeNameFlags);
  7914. methodName += " ";
  7915. methodName += methodInst->GetParamName(paramIdx);
  7916. dispParamIdx++;
  7917. }
  7918. methodName += ")";
  7919. }
  7920. if (accessorString.length() != 0)
  7921. {
  7922. methodName += " " + accessorString;
  7923. }
  7924. return methodName;
  7925. }
  7926. static void AddAttributeTargetName(BfAttributeTargets& flagsLeft, BfAttributeTargets checkFlag, String& str, String addString)
  7927. {
  7928. if ((flagsLeft & checkFlag) == 0)
  7929. return;
  7930. if (!str.empty())
  7931. {
  7932. if (flagsLeft == checkFlag)
  7933. {
  7934. if ((int)str.IndexOf(',') != -1)
  7935. str += ", and ";
  7936. else
  7937. str += " and ";
  7938. }
  7939. else
  7940. str += ", ";
  7941. }
  7942. str += addString;
  7943. flagsLeft = (BfAttributeTargets)(flagsLeft & ~checkFlag);
  7944. }
  7945. static String GetAttributesTargetListString(BfAttributeTargets attrTarget)
  7946. {
  7947. String resultStr;
  7948. auto flagsLeft = attrTarget;
  7949. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Assembly, resultStr, "assembly declarations");
  7950. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Module, resultStr, "module declarations");
  7951. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Class, resultStr, "class declarations");
  7952. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Struct, resultStr, "struct declarations");
  7953. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Enum, resultStr, "enum declarations");
  7954. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Constructor, resultStr, "constructor declarations");
  7955. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Method, resultStr, "method declarations");
  7956. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Property, resultStr, "property declarations");
  7957. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Field, resultStr, "field declarations");
  7958. AddAttributeTargetName(flagsLeft, BfAttributeTargets_StaticField, resultStr, "static field declarations");
  7959. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Interface, resultStr, "interface declarations");
  7960. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Parameter, resultStr, "parameter declarations");
  7961. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Delegate, resultStr, "delegate declarations");
  7962. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Function, resultStr, "function declarations");
  7963. AddAttributeTargetName(flagsLeft, BfAttributeTargets_ReturnValue, resultStr, "return value");
  7964. AddAttributeTargetName(flagsLeft, BfAttributeTargets_GenericParameter, resultStr, "generic parameters");
  7965. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Invocation, resultStr, "invocations");
  7966. AddAttributeTargetName(flagsLeft, BfAttributeTargets_MemberAccess, resultStr, "member access");
  7967. AddAttributeTargetName(flagsLeft, BfAttributeTargets_Alloc, resultStr, "allocations");
  7968. if (resultStr.IsEmpty())
  7969. return "<nothing>";
  7970. return resultStr;
  7971. }
  7972. void BfModule::CurrentAddToConstHolder(BfIRValue& irVal)
  7973. {
  7974. auto constant = mBfIRBuilder->GetConstant(irVal);
  7975. int stringPoolIdx = GetStringPoolIdx(irVal, mBfIRBuilder);
  7976. if (stringPoolIdx != -1)
  7977. {
  7978. irVal = mCurTypeInstance->GetOrCreateConstHolder()->CreateConst(BfTypeCode_Int32, stringPoolIdx);
  7979. return;
  7980. }
  7981. if (constant->mConstType == BfConstType_Array)
  7982. {
  7983. auto constArray = (BfConstantArray*)constant;
  7984. SizedArray<BfIRValue, 8> newVals;
  7985. for (auto val : constArray->mValues)
  7986. {
  7987. auto newVal = val;
  7988. CurrentAddToConstHolder(newVal);
  7989. newVals.push_back(newVal);
  7990. }
  7991. irVal = mCurTypeInstance->mConstHolder->CreateConstArray(constArray->mType, newVals);
  7992. return;
  7993. }
  7994. auto origConst = irVal;
  7995. if ((constant->mConstType == BfConstType_BitCast) || (constant->mConstType == BfConstType_BitCastNull))
  7996. {
  7997. auto bitcast = (BfConstantBitCast*)constant;
  7998. constant = mBfIRBuilder->GetConstantById(bitcast->mTarget);
  7999. }
  8000. irVal = mCurTypeInstance->CreateConst(constant, mBfIRBuilder);
  8001. }
  8002. void BfModule::ClearConstData()
  8003. {
  8004. mBfIRBuilder->ClearConstData();
  8005. mStringObjectPool.Clear();
  8006. mStringCharPtrPool.Clear();
  8007. mStringPoolRefs.Clear();
  8008. }
  8009. BfTypedValue BfModule::GetTypedValueFromConstant(BfConstant* constant, BfIRConstHolder* constHolder, BfType* wantType)
  8010. {
  8011. bool isString = false;
  8012. isString = (wantType->IsObject()) && (wantType->ToTypeInstance()->mTypeDef == mCompiler->mStringTypeDef);
  8013. if (wantType->IsPointer())
  8014. isString = true;
  8015. if (!isString)
  8016. {
  8017. switch (constant->mTypeCode)
  8018. {
  8019. case BfTypeCode_Boolean:
  8020. case BfTypeCode_Int8:
  8021. case BfTypeCode_UInt8:
  8022. case BfTypeCode_Int16:
  8023. case BfTypeCode_UInt16:
  8024. case BfTypeCode_Int32:
  8025. case BfTypeCode_UInt32:
  8026. case BfTypeCode_Int64:
  8027. case BfTypeCode_UInt64:
  8028. case BfTypeCode_IntPtr:
  8029. case BfTypeCode_UIntPtr:
  8030. case BfTypeCode_IntUnknown:
  8031. case BfTypeCode_UIntUnknown:
  8032. case BfTypeCode_Char8:
  8033. case BfTypeCode_Char16:
  8034. case BfTypeCode_Char32:
  8035. case BfTypeCode_Single:
  8036. case BfTypeCode_Double:
  8037. {
  8038. auto constVal = mBfIRBuilder->CreateConst(constant, constHolder);
  8039. auto typedValue = BfTypedValue(constVal, GetPrimitiveType(constant->mTypeCode));
  8040. if (typedValue.mType == wantType)
  8041. return typedValue;
  8042. if (wantType->IsTypedPrimitive())
  8043. {
  8044. if (typedValue.mType == wantType->GetUnderlyingType())
  8045. {
  8046. typedValue.mType = wantType;
  8047. return typedValue;
  8048. }
  8049. }
  8050. auto castedTypedValue = Cast(NULL, typedValue, wantType, (BfCastFlags)(BfCastFlags_SilentFail | BfCastFlags_Explicit));
  8051. BF_ASSERT(castedTypedValue);
  8052. return castedTypedValue;
  8053. }
  8054. break;
  8055. default: break;
  8056. }
  8057. }
  8058. BfIRValue irValue = ConstantToCurrent(constant, constHolder, wantType);
  8059. BF_ASSERT(irValue);
  8060. if (!irValue)
  8061. return BfTypedValue();
  8062. return BfTypedValue(irValue, wantType, false);
  8063. }
  8064. BfIRValue BfModule::ConstantToCurrent(BfConstant* constant, BfIRConstHolder* constHolder, BfType* wantType)
  8065. {
  8066. if (constant->mTypeCode == BfTypeCode_NullPtr)
  8067. {
  8068. return GetDefaultValue(wantType);
  8069. }
  8070. bool isString = false;
  8071. isString = (wantType->IsObject()) && (wantType->ToTypeInstance()->mTypeDef == mCompiler->mStringTypeDef);
  8072. if (((wantType->IsPointer()) || (isString)) && (mBfIRBuilder->IsInt(constant->mTypeCode)))
  8073. {
  8074. const StringImpl& str = mContext->mStringObjectIdMap[constant->mInt32].mString;
  8075. BfIRValue stringObjConst = GetStringObjectValue(str);
  8076. if (wantType->IsObject())
  8077. return stringObjConst;
  8078. return GetStringCharPtr(stringObjConst);
  8079. }
  8080. if (constant->mConstType == BfConstType_Array)
  8081. {
  8082. auto elementType = wantType->GetUnderlyingType();
  8083. auto constArray = (BfConstantArray*)constant;
  8084. SizedArray<BfIRValue, 8> newVals;
  8085. for (auto val : constArray->mValues)
  8086. {
  8087. newVals.push_back(ConstantToCurrent(constHolder->GetConstant(val), constHolder, elementType));
  8088. }
  8089. return mBfIRBuilder->CreateConstArray(mBfIRBuilder->MapType(wantType), newVals);
  8090. }
  8091. return mBfIRBuilder->CreateConst(constant, constHolder);
  8092. }
  8093. void BfModule::ValidateCustomAttributes(BfCustomAttributes* customAttributes, BfAttributeTargets attrTarget)
  8094. {
  8095. if (attrTarget == BfAttributeTargets_SkipValidate)
  8096. return;
  8097. for (auto& customAttribute : customAttributes->mAttributes)
  8098. {
  8099. if (!customAttribute.mAwaitingValidation)
  8100. continue;
  8101. if ((customAttribute.mType->mAttributeData->mAttributeTargets & attrTarget) == 0)
  8102. {
  8103. Fail(StrFormat("Attribute '%s' is not valid on this declaration type. It is only valid on %s.",
  8104. customAttribute.mRef->ToString().c_str(), GetAttributesTargetListString(customAttribute.mType->mAttributeData->mAttributeTargets).c_str()), customAttribute.mRef->mAttributeTypeRef); // CS0592
  8105. }
  8106. customAttribute.mAwaitingValidation = false;
  8107. }
  8108. }
  8109. void BfModule::GetCustomAttributes(BfCustomAttributes* customAttributes, BfAttributeDirective* attributesDirective, BfAttributeTargets attrTarget, bool allowNonConstArgs, BfCaptureInfo* captureInfo)
  8110. {
  8111. if ((attributesDirective != NULL) && (mCompiler->mResolvePassData != NULL) &&
  8112. (attributesDirective->IsFromParser(mCompiler->mResolvePassData->mParser)) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  8113. {
  8114. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(attributesDirective);
  8115. }
  8116. SetAndRestoreValue<bool> prevIsCapturingMethodMatchInfo;
  8117. if (mCompiler->IsAutocomplete())
  8118. prevIsCapturingMethodMatchInfo.Init(mCompiler->mResolvePassData->mAutoComplete->mIsCapturingMethodMatchInfo, false);
  8119. BfTypeInstance* baseAttrTypeInst = mContext->mUnreifiedModule->ResolveTypeDef(mCompiler->mAttributeTypeDef)->ToTypeInstance();
  8120. BfAttributeTargets targetOverride = (BfAttributeTargets)0;
  8121. BfAutoComplete* autoComplete = NULL;
  8122. if (mCompiler->mResolvePassData != NULL)
  8123. autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  8124. for (; attributesDirective != NULL; attributesDirective = attributesDirective->mNextAttribute)
  8125. {
  8126. if (auto tokenNode = BfNodeDynCast<BfTokenNode>(attributesDirective->mAttributeTargetSpecifier))
  8127. {
  8128. if (captureInfo == NULL)
  8129. {
  8130. Fail("Capture specifiers can only be used in lambda allocations", attributesDirective);
  8131. continue;
  8132. }
  8133. BfCaptureInfo::Entry captureEntry;
  8134. captureEntry.mCaptureType = (tokenNode->mToken == BfToken_Ampersand) ? BfCaptureType_Reference : BfCaptureType_Copy;
  8135. if (!attributesDirective->mArguments.IsEmpty())
  8136. {
  8137. captureEntry.mNameNode = BfNodeDynCast<BfIdentifierNode>(attributesDirective->mArguments[0]);
  8138. if ((captureEntry.mNameNode != NULL) && (autoComplete != NULL))
  8139. autoComplete->CheckIdentifier(captureEntry.mNameNode);
  8140. }
  8141. captureInfo->mCaptures.Add(captureEntry);
  8142. continue;
  8143. }
  8144. BfAutoParentNodeEntry autoParentNodeEntry(this, attributesDirective);
  8145. BfCustomAttribute customAttribute;
  8146. customAttribute.mAwaitingValidation = true;
  8147. customAttribute.mRef = attributesDirective;
  8148. if (attributesDirective->mAttrOpenToken != NULL)
  8149. targetOverride = (BfAttributeTargets)0;
  8150. if (attributesDirective->mAttributeTypeRef == NULL)
  8151. {
  8152. AssertErrorState();
  8153. continue;
  8154. }
  8155. String attrName = attributesDirective->mAttributeTypeRef->ToString();
  8156. BfType* attrType = NULL;
  8157. BfAtomComposite nameComposite;
  8158. BfTypeDef* attrTypeDef = NULL;
  8159. if (mSystem->ParseAtomComposite(attrName + "Attribute", nameComposite))
  8160. {
  8161. BfTypeLookupError error;
  8162. error.mRefNode = attributesDirective->mAttributeTypeRef;
  8163. attrTypeDef = FindTypeDefRaw(nameComposite, 0, mCurTypeInstance, GetActiveTypeDef(NULL, true), &error);
  8164. }
  8165. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  8166. {
  8167. mCompiler->mResolvePassData->mAutoComplete->CheckAttributeTypeRef(attributesDirective->mAttributeTypeRef);
  8168. if (attrTypeDef != NULL)
  8169. mCompiler->mResolvePassData->HandleTypeReference(attributesDirective->mAttributeTypeRef, attrTypeDef);
  8170. }
  8171. if (attrTypeDef == NULL)
  8172. {
  8173. TypeRefNotFound(attributesDirective->mAttributeTypeRef, "Attribute");
  8174. continue;
  8175. }
  8176. bool isBypassedAttr = false;
  8177. if (attrTypeDef != NULL)
  8178. {
  8179. attrType = mContext->mUnreifiedModule->ResolveTypeDef(attrTypeDef, BfPopulateType_Identity);
  8180. // 'Object' has some dependencies on some attributes, but those attributes are classes so we have a circular dependency issue
  8181. // We solve it by having a 'bypass' for known attributes that Object depends on
  8182. if ((attributesDirective->mArguments.empty()) && (autoComplete == NULL) && (attrType != NULL) && (attrType->IsTypeInstance()))
  8183. {
  8184. if (attrTypeDef == mCompiler->mCReprAttributeTypeDef)
  8185. {
  8186. BfTypeInstance* attrTypeInst = attrType->ToTypeInstance();
  8187. for (auto methodDef : attrTypeDef->mMethods)
  8188. {
  8189. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mProtection == BfProtection_Public))
  8190. {
  8191. customAttribute.mType = attrType->ToTypeInstance();
  8192. customAttribute.mCtor = methodDef;
  8193. isBypassedAttr = true;
  8194. break;
  8195. }
  8196. }
  8197. }
  8198. }
  8199. if (isBypassedAttr)
  8200. {
  8201. customAttribute.mAwaitingValidation = false;
  8202. customAttributes->mAttributes.push_back(customAttribute);
  8203. continue;
  8204. }
  8205. if (mContext->mCurTypeState != NULL)
  8206. {
  8207. SetAndRestoreValue<BfTypeReference*> prevTypeRef(mContext->mCurTypeState->mCurAttributeTypeRef, attributesDirective->mAttributeTypeRef);
  8208. mContext->mUnreifiedModule->ResolveTypeResult(attributesDirective->mAttributeTypeRef, attrType, BfPopulateType_BaseType, (BfResolveTypeRefFlags)0);
  8209. }
  8210. else
  8211. {
  8212. mContext->mUnreifiedModule->ResolveTypeResult(attributesDirective->mAttributeTypeRef, attrType, BfPopulateType_BaseType, (BfResolveTypeRefFlags)0);
  8213. }
  8214. }
  8215. // Don't allow this
  8216. /*else if (mContext->mCurTypeState != NULL)
  8217. {
  8218. SetAndRestoreValue<BfTypeReference*> prevTypeRef(mContext->mCurTypeState->mCurAttributeTypeRef, attributesDirective->mAttributeTypeRef);
  8219. attrType = mContext->mUnreifiedModule->ResolveTypeRef(attributesDirective->mAttributeTypeRef, BfPopulateType_DataAndMethods);
  8220. }
  8221. else
  8222. {
  8223. attrType = mContext->mUnreifiedModule->ResolveTypeRef(attributesDirective->mAttributeTypeRef);
  8224. }*/
  8225. BfTypeInstance* attrTypeInst = NULL;
  8226. if (attrType == NULL)
  8227. continue;
  8228. mContext->mUnreifiedModule->PopulateType(attrType, BfPopulateType_DataAndMethods);
  8229. attrTypeInst = attrType->ToTypeInstance();
  8230. if ((attrTypeInst == NULL) || (!TypeIsSubTypeOf(attrTypeInst, baseAttrTypeInst)) || (attrTypeInst->mAttributeData == NULL))
  8231. {
  8232. Fail(StrFormat("'%s' is not an attribute class", TypeToString(attrType).c_str()), attributesDirective->mAttributeTypeRef); //CS0616
  8233. continue;
  8234. }
  8235. if (mCurTypeInstance != NULL)
  8236. AddDependency(attrTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  8237. customAttribute.mType = attrTypeInst;
  8238. BfConstResolver constResolver(this);
  8239. if (allowNonConstArgs)
  8240. constResolver.mBfEvalExprFlags = (BfEvalExprFlags)(constResolver.mBfEvalExprFlags | BfEvalExprFlags_AllowNonConst);
  8241. bool inPropSet = false;
  8242. SizedArray<BfResolvedArg, 2> argValues;
  8243. for (BfExpression* arg : attributesDirective->mArguments)
  8244. {
  8245. if (arg == NULL)
  8246. {
  8247. continue;
  8248. }
  8249. if (autoComplete != NULL)
  8250. autoComplete->mShowAttributeProperties = attrTypeInst;
  8251. if (auto assignExpr = BfNodeDynCast<BfAssignmentExpression>(arg))
  8252. {
  8253. inPropSet = true;
  8254. if (autoComplete != NULL)
  8255. autoComplete->CheckNode(assignExpr->mLeft);
  8256. String findName = assignExpr->mLeft->ToString();
  8257. BfPropertyDef* bestProp = NULL;
  8258. BfTypeInstance* bestPropTypeInst = NULL;
  8259. BfFieldDef* bestField = NULL;
  8260. BfTypeInstance* bestFieldTypeInst = NULL;
  8261. auto checkTypeInst = attrTypeInst;
  8262. while (checkTypeInst != NULL)
  8263. {
  8264. mContext->mUnreifiedModule->PopulateType(checkTypeInst, BfPopulateType_Data);
  8265. for (auto prop : checkTypeInst->mTypeDef->mProperties)
  8266. {
  8267. if (prop->mName == findName)
  8268. {
  8269. if ((bestProp == NULL) || (bestProp->mProtection != BfProtection_Public))
  8270. {
  8271. bestProp = prop;
  8272. bestPropTypeInst = checkTypeInst;
  8273. }
  8274. }
  8275. }
  8276. for (auto field : checkTypeInst->mTypeDef->mFields)
  8277. {
  8278. if (field->mName == findName)
  8279. {
  8280. if ((bestField == NULL) || (bestField->mProtection != BfProtection_Public))
  8281. {
  8282. bestField = field;
  8283. bestFieldTypeInst = checkTypeInst;
  8284. }
  8285. }
  8286. }
  8287. if ((bestProp != NULL) || (bestField != NULL))
  8288. break;
  8289. checkTypeInst = checkTypeInst->mBaseType;
  8290. }
  8291. bool handledExpr = false;
  8292. if (bestField != NULL)
  8293. {
  8294. handledExpr = true;
  8295. if (mCompiler->mResolvePassData != NULL)
  8296. {
  8297. mCompiler->mResolvePassData->HandleFieldReference(assignExpr->mLeft, attrTypeDef, bestField);
  8298. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(assignExpr->mLeft)))
  8299. {
  8300. autoComplete->mDefField = bestField;
  8301. autoComplete->mDefType = attrTypeDef;
  8302. }
  8303. }
  8304. if (bestField->mProtection != BfProtection_Public)
  8305. Fail(StrFormat("'%s.%s' is inaccessible due to its protection level", TypeToString(bestFieldTypeInst).c_str(), findName.c_str()), assignExpr->mLeft); // CS0122
  8306. AddDependency(bestFieldTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  8307. BfCustomAttributeSetField setField;
  8308. setField.mFieldRef = BfFieldRef(bestFieldTypeInst, bestField);
  8309. auto& fieldTypeInst = checkTypeInst->mFieldInstances[bestField->mIdx];
  8310. if (assignExpr->mRight != NULL)
  8311. {
  8312. BfTypedValue result = constResolver.Resolve(assignExpr->mRight, fieldTypeInst.mResolvedType);
  8313. if (result)
  8314. {
  8315. CurrentAddToConstHolder(result.mValue);
  8316. setField.mParam = result;
  8317. customAttribute.mSetField.push_back(setField);
  8318. }
  8319. }
  8320. }
  8321. else if (bestProp == NULL)
  8322. {
  8323. Fail(StrFormat("'%s' does not contain a field or property named '%s'", TypeToString(attrTypeInst).c_str(), findName.c_str()), assignExpr->mLeft);
  8324. }
  8325. else
  8326. {
  8327. BfMethodDef* setMethod = NULL;
  8328. for (auto methodDef : bestProp->mMethods)
  8329. {
  8330. if (methodDef->mMethodType == BfMethodType_PropertySetter)
  8331. {
  8332. setMethod = methodDef;
  8333. break;
  8334. }
  8335. }
  8336. if (setMethod == NULL)
  8337. {
  8338. Fail("Property has no setter", assignExpr->mLeft);
  8339. }
  8340. else
  8341. {
  8342. if (mCompiler->mResolvePassData != NULL)
  8343. {
  8344. mCompiler->mResolvePassData->HandlePropertyReference(assignExpr->mLeft, attrTypeDef, bestProp);
  8345. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(assignExpr->mLeft)))
  8346. {
  8347. autoComplete->mDefProp = bestProp;
  8348. autoComplete->mDefType = attrTypeDef;
  8349. }
  8350. }
  8351. handledExpr = true;
  8352. if (bestProp->mProtection != BfProtection_Public)
  8353. Fail(StrFormat("'%s.%s' is inaccessible due to its protection level", TypeToString(bestPropTypeInst).c_str(), findName.c_str()), assignExpr->mLeft); // CS0122
  8354. BfResolvedArg resolvedArg;
  8355. AddDependency(bestPropTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  8356. BfCustomAttributeSetProperty setProperty;
  8357. setProperty.mPropertyRef = BfPropertyRef(bestPropTypeInst, bestProp);
  8358. // We don't actually need the mFunc, so get the ModuleMethodInstance from the native module
  8359. auto methodInstance = bestPropTypeInst->mModule->GetMethodInstance(bestPropTypeInst, setMethod, BfTypeVector());
  8360. if (methodInstance.mMethodInstance != NULL)
  8361. {
  8362. auto propType = methodInstance.mMethodInstance->GetParamType(0);
  8363. if (assignExpr->mRight != NULL)
  8364. {
  8365. BfTypedValue result = constResolver.Resolve(assignExpr->mRight, propType);
  8366. if (result)
  8367. {
  8368. BF_ASSERT(result.mType == propType);
  8369. CurrentAddToConstHolder(result.mValue);
  8370. setProperty.mParam = result;
  8371. customAttribute.mSetProperties.push_back(setProperty);
  8372. }
  8373. }
  8374. }
  8375. }
  8376. }
  8377. if ((!handledExpr) && (assignExpr->mRight != NULL))
  8378. constResolver.Resolve(assignExpr->mRight);
  8379. }
  8380. else
  8381. {
  8382. if (inPropSet)
  8383. {
  8384. Fail("Named attribute argument expected", arg); // CS1016
  8385. }
  8386. BfDeferEvalChecker deferEvalChecker;
  8387. arg->Accept(&deferEvalChecker);
  8388. bool deferParamEval = deferEvalChecker.mNeedsDeferEval;
  8389. BfResolvedArg resolvedArg;
  8390. resolvedArg.mExpression = arg;
  8391. if (deferParamEval)
  8392. {
  8393. resolvedArg.mArgFlags = BfArgFlag_DeferredEval;
  8394. }
  8395. else
  8396. resolvedArg.mTypedValue = constResolver.Resolve(arg);
  8397. if (!inPropSet)
  8398. argValues.push_back(resolvedArg);
  8399. }
  8400. if (autoComplete != NULL)
  8401. autoComplete->mShowAttributeProperties = NULL;
  8402. }
  8403. auto wasCapturingMethodInfo = false;
  8404. if (autoComplete != NULL)
  8405. {
  8406. wasCapturingMethodInfo = autoComplete->mIsCapturingMethodMatchInfo;
  8407. if (attributesDirective->mCtorOpenParen != NULL)
  8408. autoComplete->CheckInvocation(attributesDirective, attributesDirective->mCtorOpenParen, attributesDirective->mCtorCloseParen, attributesDirective->mCommas);
  8409. }
  8410. BfMethodMatcher methodMatcher(attributesDirective, this, "", argValues, NULL);
  8411. attrTypeDef = attrTypeInst->mTypeDef;
  8412. bool success = true;
  8413. bool isFailurePass = false;
  8414. for (int pass = 0; pass < 2; pass++)
  8415. {
  8416. bool isFailurePass = pass == 1;
  8417. for (auto checkMethod : attrTypeDef->mMethods)
  8418. {
  8419. if ((isFailurePass) && (checkMethod->mMethodDeclaration == NULL))
  8420. continue; // Don't match private default ctor if there's a user-defined one
  8421. if ((checkMethod->mIsStatic) || (checkMethod->mMethodType != BfMethodType_Ctor))
  8422. continue;
  8423. if ((!isFailurePass) && (!CheckProtection(checkMethod->mProtection, false, false)))
  8424. continue;
  8425. methodMatcher.CheckMethod(attrTypeInst, checkMethod, isFailurePass);
  8426. }
  8427. if ((methodMatcher.mBestMethodDef != NULL) || (methodMatcher.mBackupMethodDef != NULL))
  8428. break;
  8429. }
  8430. if (autoComplete != NULL)
  8431. {
  8432. if ((wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo))
  8433. {
  8434. autoComplete->mIsCapturingMethodMatchInfo = true;
  8435. BF_ASSERT(autoComplete->mMethodMatchInfo != NULL);
  8436. }
  8437. else
  8438. autoComplete->mIsCapturingMethodMatchInfo = false;
  8439. }
  8440. if (methodMatcher.mBestMethodDef == NULL)
  8441. methodMatcher.mBestMethodDef = methodMatcher.mBackupMethodDef;
  8442. BF_ASSERT(methodMatcher.mBestMethodDef != NULL);
  8443. customAttribute.mCtor = methodMatcher.mBestMethodDef;
  8444. if (methodMatcher.mBestMethodTypeInstance == mCurTypeInstance)
  8445. {
  8446. Fail("Custom attribute circular reference", attributesDirective);
  8447. }
  8448. if (mCurTypeInstance != NULL)
  8449. AddDependency(methodMatcher.mBestMethodTypeInstance, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  8450. if (!constResolver.PrepareMethodArguments(attributesDirective->mAttributeTypeRef, &methodMatcher, customAttribute.mCtorArgs))
  8451. success = false;
  8452. for (auto& arg : argValues)
  8453. {
  8454. if ((arg.mArgFlags & BfArgFlag_DeferredEval) != 0)
  8455. {
  8456. if (auto expr = BfNodeDynCast<BfExpression>(arg.mExpression))
  8457. constResolver.Resolve(expr);
  8458. }
  8459. }
  8460. // Move all those to the constHolder
  8461. for (auto& ctorArg : customAttribute.mCtorArgs)
  8462. {
  8463. if (ctorArg.IsConst())
  8464. CurrentAddToConstHolder(ctorArg);
  8465. }
  8466. if (attributesDirective->mAttributeTargetSpecifier != NULL)
  8467. {
  8468. targetOverride = BfAttributeTargets_ReturnValue;
  8469. if (attrTarget != BfAttributeTargets_Method)
  8470. {
  8471. 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.",
  8472. GetAttributesTargetListString(targetOverride).c_str(), GetAttributesTargetListString(attrTarget).c_str()), attributesDirective->mAttributeTargetSpecifier); // CS0657
  8473. }
  8474. success = false;
  8475. }
  8476. if ((success) && (targetOverride != (BfAttributeTargets)0))
  8477. {
  8478. if ((targetOverride == BfAttributeTargets_ReturnValue) && (attrTarget == BfAttributeTargets_Method))
  8479. {
  8480. auto methodInfoEx = mCurMethodInstance->GetMethodInfoEx();
  8481. if (methodInfoEx->mMethodCustomAttributes == NULL)
  8482. methodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  8483. if (success)
  8484. {
  8485. if (methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes == NULL)
  8486. methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes = new BfCustomAttributes();
  8487. methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes->mAttributes.push_back(customAttribute);
  8488. }
  8489. }
  8490. else
  8491. {
  8492. // Failed - ignore
  8493. success = false;
  8494. }
  8495. }
  8496. if (success)
  8497. {
  8498. if (!attrTypeInst->mAttributeData->mAllowMultiple)
  8499. {
  8500. for (auto& prevCustomAttribute : customAttributes->mAttributes)
  8501. {
  8502. if (prevCustomAttribute.mType == attrTypeInst)
  8503. {
  8504. Fail(StrFormat("Duplicate '%s' attribute", attributesDirective->mAttributeTypeRef->ToString().c_str()), attributesDirective->mAttributeTypeRef); // CS0579
  8505. }
  8506. }
  8507. }
  8508. }
  8509. if (success)
  8510. {
  8511. customAttributes->mAttributes.push_back(customAttribute);
  8512. }
  8513. }
  8514. ValidateCustomAttributes(customAttributes, attrTarget);
  8515. }
  8516. BfCustomAttributes* BfModule::GetCustomAttributes(BfAttributeDirective* attributesDirective, BfAttributeTargets attrType, bool allowNonConstArgs, BfCaptureInfo* captureInfo)
  8517. {
  8518. BfCustomAttributes* customAttributes = new BfCustomAttributes();
  8519. GetCustomAttributes(customAttributes, attributesDirective, attrType, allowNonConstArgs, captureInfo);
  8520. return customAttributes;
  8521. }
  8522. void BfModule::ProcessTypeInstCustomAttributes(bool& isPacked, bool& isUnion, bool& isCRepr, bool& isOrdered)
  8523. {
  8524. if (mCurTypeInstance->mCustomAttributes != NULL)
  8525. {
  8526. for (auto& customAttribute : mCurTypeInstance->mCustomAttributes->mAttributes)
  8527. {
  8528. String typeName = TypeToString(customAttribute.mType);
  8529. if (typeName == "System.PackedAttribute")
  8530. {
  8531. isPacked = true;
  8532. }
  8533. else if (typeName == "System.UnionAttribute")
  8534. {
  8535. isUnion = true;
  8536. }
  8537. else if (typeName == "System.CReprAttribute")
  8538. {
  8539. isCRepr = true;
  8540. isOrdered = true;
  8541. }
  8542. else if (typeName == "System.OrderedAttribute")
  8543. {
  8544. isOrdered = true;
  8545. }
  8546. else if (typeName == "System.AlwaysIncludeAttribute")
  8547. {
  8548. for (auto setProp : customAttribute.mSetProperties)
  8549. {
  8550. BfPropertyDef* propertyDef = setProp.mPropertyRef;
  8551. if (propertyDef->mName == "AssumeInstantiated")
  8552. {
  8553. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  8554. if ((constant != NULL) && (constant->mBool))
  8555. mCurTypeInstance->mHasBeenInstantiated = true;
  8556. }
  8557. }
  8558. }
  8559. }
  8560. }
  8561. }
  8562. // Checking to see if we're an attribute or not
  8563. void BfModule::ProcessCustomAttributeData()
  8564. {
  8565. bool isAttribute = false;
  8566. auto checkTypeInst = mCurTypeInstance->mBaseType;
  8567. while (checkTypeInst != NULL)
  8568. {
  8569. if (checkTypeInst->mTypeDef == mCompiler->mAttributeTypeDef)
  8570. isAttribute = true;
  8571. checkTypeInst = checkTypeInst->mBaseType;
  8572. }
  8573. if (!isAttribute)
  8574. return;
  8575. auto attributeData = new BfAttributeData();
  8576. bool hasCustomAttribute = false;
  8577. if (mCurTypeInstance->mCustomAttributes != NULL)
  8578. {
  8579. for (auto& customAttribute : mCurTypeInstance->mCustomAttributes->mAttributes)
  8580. {
  8581. if (customAttribute.mType->mTypeDef == mCompiler->mAttributeUsageAttributeTypeDef)
  8582. {
  8583. if (customAttribute.mCtorArgs.size() > 0)
  8584. {
  8585. auto constant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  8586. if ((constant != NULL) && (mBfIRBuilder->IsInt(constant->mTypeCode)))
  8587. attributeData->mAttributeTargets = (BfAttributeTargets)constant->mInt32;
  8588. }
  8589. for (auto& setProp : customAttribute.mSetProperties)
  8590. {
  8591. BfPropertyDef* propDef = setProp.mPropertyRef;
  8592. if (propDef->mName == "AllowMultiple")
  8593. {
  8594. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  8595. if (constant != NULL)
  8596. attributeData->mAllowMultiple = constant->mBool;
  8597. }
  8598. else if (propDef->mName == "Inherited")
  8599. {
  8600. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  8601. if (constant != NULL)
  8602. attributeData->mInherited = constant->mBool;
  8603. }
  8604. else if (propDef->mName == "ValidOn")
  8605. {
  8606. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  8607. if (constant != NULL)
  8608. attributeData->mAttributeTargets = (BfAttributeTargets)constant->mInt32;
  8609. }
  8610. }
  8611. hasCustomAttribute = true;
  8612. }
  8613. }
  8614. }
  8615. if ((!hasCustomAttribute) && (mCurTypeInstance->mBaseType->mAttributeData != NULL))
  8616. {
  8617. attributeData->mAttributeTargets = mCurTypeInstance->mBaseType->mAttributeData->mAttributeTargets;
  8618. attributeData->mInherited = mCurTypeInstance->mBaseType->mAttributeData->mInherited;
  8619. attributeData->mAllowMultiple = mCurTypeInstance->mBaseType->mAttributeData->mAllowMultiple;
  8620. }
  8621. mCurTypeInstance->mAttributeData = attributeData;
  8622. }
  8623. bool BfModule::TryGetConstString(BfIRConstHolder* constHolder, BfIRValue irValue, StringImpl& str)
  8624. {
  8625. auto constant = constHolder->GetConstant(irValue);
  8626. if (constant == NULL)
  8627. return false;
  8628. if (!BfIRConstHolder::IsInt(constant->mTypeCode))
  8629. return false;
  8630. int stringId = constant->mInt32;
  8631. BfStringPoolEntry* entry = NULL;
  8632. if (mContext->mStringObjectIdMap.TryGetValue(stringId, &entry))
  8633. {
  8634. str = entry->mString;
  8635. }
  8636. else
  8637. {
  8638. BF_DBG_FATAL("Failed to find string by id");
  8639. }
  8640. return true;
  8641. }
  8642. BfVariant BfModule::TypedValueToVariant(BfAstNode* refNode, const BfTypedValue& value, bool allowUndef)
  8643. {
  8644. BfVariant variant;
  8645. variant.mTypeCode = BfTypeCode_None;
  8646. BfType* primType = NULL;
  8647. if (value.mType->IsPrimitiveType())
  8648. primType = (BfPrimitiveType*)value.mType;
  8649. else if (value.mType->IsTypedPrimitive())
  8650. primType = value.mType->GetUnderlyingType();
  8651. if (primType)
  8652. {
  8653. auto constant = mBfIRBuilder->GetConstant(value.mValue);
  8654. if (constant != NULL)
  8655. {
  8656. if ((allowUndef) && (constant->mConstType == BfConstType_Undef))
  8657. {
  8658. variant.mTypeCode = BfTypeCode_Let;
  8659. return variant;
  8660. }
  8661. switch (constant->mTypeCode)
  8662. {
  8663. case BfTypeCode_Int8:
  8664. case BfTypeCode_UInt8:
  8665. case BfTypeCode_Int16:
  8666. case BfTypeCode_UInt16:
  8667. case BfTypeCode_Int32:
  8668. case BfTypeCode_UInt32:
  8669. case BfTypeCode_Int64:
  8670. case BfTypeCode_UInt64:
  8671. case BfTypeCode_IntPtr:
  8672. case BfTypeCode_UIntPtr:
  8673. case BfTypeCode_IntUnknown:
  8674. case BfTypeCode_UIntUnknown:
  8675. case BfTypeCode_Single:
  8676. case BfTypeCode_Double:
  8677. case BfTypeCode_Char8:
  8678. case BfTypeCode_Char16:
  8679. case BfTypeCode_Char32:
  8680. variant.mTypeCode = constant->mTypeCode;
  8681. variant.mInt64 = constant->mInt64;
  8682. break;
  8683. default:
  8684. if (refNode != NULL)
  8685. Fail("Invalid const expression type", refNode);
  8686. break;
  8687. }
  8688. }
  8689. }
  8690. return variant;
  8691. }
  8692. BfTypedValue BfModule::RemoveRef(BfTypedValue typedValue)
  8693. {
  8694. if ((typedValue.mType != NULL) && (typedValue.mType->IsRef()))
  8695. {
  8696. auto elementType = typedValue.mType->GetUnderlyingType();
  8697. if (typedValue.IsAddr())
  8698. {
  8699. if (elementType->IsValuelessType())
  8700. {
  8701. BF_ASSERT(!typedValue.mValue);
  8702. typedValue = BfTypedValue(typedValue.mValue, elementType, true);
  8703. }
  8704. else
  8705. typedValue = BfTypedValue(mBfIRBuilder->CreateLoad(typedValue.mValue), elementType, true);
  8706. }
  8707. else
  8708. typedValue = BfTypedValue(typedValue.mValue, elementType, true);
  8709. if (typedValue.mType->IsValuelessType())
  8710. {
  8711. BF_ASSERT(typedValue.mValue.IsFake());
  8712. }
  8713. }
  8714. return typedValue;
  8715. }
  8716. BfTypedValue BfModule::LoadValue(BfTypedValue typedValue, BfAstNode* refNode, bool isVolatile)
  8717. {
  8718. if (!typedValue.IsAddr())
  8719. return typedValue;
  8720. if (typedValue.mType->IsValuelessType())
  8721. return BfTypedValue(mBfIRBuilder->GetFakeVal(), typedValue.mType, false);
  8722. BfIRValue loadedVal = typedValue.mValue;
  8723. if (loadedVal)
  8724. {
  8725. if (typedValue.mType->IsVar())
  8726. {
  8727. return BfTypedValue(loadedVal, typedValue.mType, false);
  8728. }
  8729. /*if (isVolatile)
  8730. mBfIRBuilder->CreateFence(BfIRFenceType_AcquireRelease);*/
  8731. PopulateType(typedValue.mType, BfPopulateType_Data);
  8732. loadedVal = mBfIRBuilder->CreateAlignedLoad(loadedVal, std::max(1, (int)typedValue.mType->mAlign), isVolatile);
  8733. }
  8734. return BfTypedValue(loadedVal, typedValue.mType, false);
  8735. }
  8736. BfTypedValue BfModule::LoadOrAggregateValue(BfTypedValue typedValue)
  8737. {
  8738. if (typedValue.IsSplat())
  8739. return AggregateSplat(typedValue);
  8740. if (typedValue.IsAddr())
  8741. return LoadValue(typedValue);
  8742. return typedValue;
  8743. }
  8744. BfTypedValue BfModule::AggregateSplat(BfTypedValue typedValue, BfIRValue* valueArrPtr)
  8745. {
  8746. if (!typedValue.IsSplat())
  8747. return typedValue;
  8748. if (typedValue.mType->IsValuelessType())
  8749. return typedValue;
  8750. int elementIdx = 0;
  8751. auto _ExtractValue = [&](BfType* checkType)
  8752. {
  8753. if (valueArrPtr != NULL)
  8754. return valueArrPtr[elementIdx++];
  8755. return ExtractSplatValue(typedValue, elementIdx++, checkType);
  8756. };
  8757. std::function<BfIRValue(BfType*)> checkTypeLambda = [&](BfType* checkType)
  8758. {
  8759. if (checkType->IsStruct())
  8760. {
  8761. BfIRValue curValue = mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(checkType, BfIRPopulateType_Full));
  8762. auto checkTypeInstance = checkType->ToTypeInstance();
  8763. if (checkTypeInstance->mBaseType != NULL)
  8764. {
  8765. mBfIRBuilder->PopulateType(checkTypeInstance->mBaseType, BfIRPopulateType_Full);
  8766. BfIRValue baseValue = checkTypeLambda(checkTypeInstance->mBaseType);
  8767. curValue = mBfIRBuilder->CreateInsertValue(curValue, baseValue, 0);
  8768. }
  8769. if (checkTypeInstance->mIsUnion)
  8770. {
  8771. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  8772. if (!unionInnerType->IsValuelessType())
  8773. {
  8774. BfIRValue fieldValue = checkTypeLambda(unionInnerType);
  8775. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, 1);
  8776. }
  8777. if (checkTypeInstance->IsEnum())
  8778. {
  8779. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  8780. BfIRValue fieldValue = checkTypeLambda(dscrType);
  8781. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, 2);
  8782. }
  8783. }
  8784. else
  8785. {
  8786. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  8787. {
  8788. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  8789. if (fieldInstance->mDataIdx >= 0)
  8790. {
  8791. BfIRValue fieldValue = checkTypeLambda(fieldInstance->GetResolvedType());
  8792. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, fieldInstance->mDataIdx);
  8793. }
  8794. }
  8795. }
  8796. return curValue;
  8797. }
  8798. else if (checkType->IsMethodRef())
  8799. {
  8800. BfMethodRefType* methodRefType = (BfMethodRefType*)checkType;
  8801. BfIRValue curValue = mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(checkType, BfIRPopulateType_Full));
  8802. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  8803. {
  8804. BfIRValue fieldValue;
  8805. auto checkType = methodRefType->GetCaptureType(dataIdx);
  8806. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  8807. {
  8808. fieldValue = checkTypeLambda(checkType);
  8809. }
  8810. else
  8811. {
  8812. fieldValue = _ExtractValue(checkType);
  8813. }
  8814. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, dataIdx);
  8815. }
  8816. return curValue;
  8817. }
  8818. else if (!checkType->IsValuelessType())
  8819. {
  8820. return _ExtractValue(checkType);
  8821. }
  8822. return BfIRValue();
  8823. };
  8824. BfIRValue value = checkTypeLambda(typedValue.mType);
  8825. return BfTypedValue(value, typedValue.mType, typedValue.IsThis() ? BfTypedValueKind_ThisValue : BfTypedValueKind_Value);
  8826. }
  8827. void BfModule::AggregateSplatIntoAddr(BfTypedValue typedValue, BfIRValue addrVal)
  8828. {
  8829. if (!typedValue.IsSplat())
  8830. return;
  8831. if (typedValue.mType->IsValuelessType())
  8832. return;
  8833. /*static int sCallIdx = 0;
  8834. if (!mCompiler->mIsResolveOnly)
  8835. sCallIdx++;
  8836. int callIdx = sCallIdx;*/
  8837. int elementIdx = 0;
  8838. std::function<void(BfType*, BfIRValue)> checkTypeLambda = [&](BfType* checkType, BfIRValue curAddrVal)
  8839. {
  8840. if (checkType->IsStruct())
  8841. {
  8842. auto checkTypeInstance = checkType->ToTypeInstance();
  8843. if (checkTypeInstance->mBaseType != NULL)
  8844. {
  8845. mBfIRBuilder->PopulateType(checkTypeInstance->mBaseType);
  8846. auto baseAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 0);
  8847. checkTypeLambda(checkTypeInstance->mBaseType, baseAddrVal);
  8848. }
  8849. if (checkTypeInstance->mIsUnion)
  8850. {
  8851. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  8852. if (!unionInnerType->IsValuelessType())
  8853. {
  8854. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 1);
  8855. checkTypeLambda(unionInnerType, fieldAddrVal);
  8856. }
  8857. if (checkTypeInstance->IsEnum())
  8858. {
  8859. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  8860. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 2);
  8861. checkTypeLambda(dscrType, fieldAddrVal);
  8862. }
  8863. }
  8864. else
  8865. {
  8866. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  8867. {
  8868. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  8869. if (fieldInstance->mDataIdx >= 0)
  8870. {
  8871. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, fieldInstance->mDataIdx);
  8872. checkTypeLambda(fieldInstance->mResolvedType, fieldAddrVal);
  8873. }
  8874. }
  8875. }
  8876. }
  8877. else if (checkType->IsMethodRef())
  8878. {
  8879. BfMethodRefType* methodRefType = (BfMethodRefType*)checkType;
  8880. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  8881. {
  8882. auto dataType = methodRefType->GetCaptureType(dataIdx);
  8883. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, dataIdx);
  8884. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  8885. {
  8886. checkTypeLambda(methodRefType->GetCaptureType(dataIdx), fieldAddrVal);
  8887. }
  8888. else
  8889. {
  8890. // static int sItrCount = 0;
  8891. // sItrCount++;
  8892. // int curItr = sItrCount;
  8893. // if (curItr == 1)
  8894. // {
  8895. // NOP;
  8896. // }
  8897. auto val = ExtractSplatValue(typedValue, elementIdx++, dataType);
  8898. mBfIRBuilder->CreateStore(val, fieldAddrVal);
  8899. }
  8900. }
  8901. }
  8902. else if (!checkType->IsValuelessType())
  8903. {
  8904. auto val = ExtractSplatValue(typedValue, elementIdx++, checkType);
  8905. mBfIRBuilder->CreateStore(val, curAddrVal);
  8906. }
  8907. };
  8908. checkTypeLambda(typedValue.mType, addrVal);
  8909. }
  8910. BfTypedValue BfModule::MakeAddressable(BfTypedValue typedVal)
  8911. {
  8912. bool wasReadOnly = typedVal.IsReadOnly();
  8913. if ((typedVal.mType->IsValueType()) &&
  8914. (!typedVal.mType->IsValuelessType()))
  8915. {
  8916. wasReadOnly = true; // Any non-addr is implicitly read-only
  8917. //static int gCallIdx = 0;
  8918. if (typedVal.IsAddr())
  8919. return typedVal;
  8920. BfType* type = typedVal.mType;
  8921. PopulateType(type);
  8922. auto tempVar = CreateAlloca(type);
  8923. if (typedVal.IsSplat())
  8924. AggregateSplatIntoAddr(typedVal, tempVar);
  8925. else
  8926. mBfIRBuilder->CreateAlignedStore(typedVal.mValue, tempVar, type->mAlign);
  8927. return BfTypedValue(tempVar, type,
  8928. typedVal.IsThis() ?
  8929. (wasReadOnly ? BfTypedValueKind_ReadOnlyThisAddr : BfTypedValueKind_ThisAddr) :
  8930. (wasReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr));
  8931. }
  8932. return LoadValue(typedVal);
  8933. }
  8934. BfTypedValue BfModule::RemoveReadOnly(BfTypedValue typedValue)
  8935. {
  8936. if (typedValue.mKind == BfTypedValueKind_ReadOnlyAddr)
  8937. typedValue.mKind = BfTypedValueKind_Addr;
  8938. return typedValue;
  8939. }
  8940. BfIRValue BfModule::ExtractSplatValue(BfTypedValue typedValue, int componentIdx, BfType* wantType, bool* isAddr)
  8941. {
  8942. BfIRValue val;
  8943. if (typedValue.mValue.IsArg())
  8944. {
  8945. val = mBfIRBuilder->GetArgument(typedValue.mValue.mId + componentIdx);
  8946. if (isAddr != NULL)
  8947. {
  8948. if (wantType != NULL)
  8949. *isAddr = wantType->IsComposite();
  8950. else
  8951. *isAddr = false;
  8952. }
  8953. else if (wantType->IsComposite())
  8954. val = mBfIRBuilder->CreateLoad(val);
  8955. }
  8956. if (!val)
  8957. {
  8958. auto checkMethodState = mCurMethodState;
  8959. while (checkMethodState != NULL)
  8960. {
  8961. for (int idx = 0; idx < (int)checkMethodState->mSplatDecompAddrs.size(); idx++)
  8962. {
  8963. auto decompAddr = checkMethodState->mSplatDecompAddrs[idx];
  8964. if (decompAddr == typedValue.mValue)
  8965. {
  8966. val = checkMethodState->mSplatDecompAddrs[idx + componentIdx];
  8967. if ((wantType->IsComposite()) && (typedValue.mType->IsMethodRef()))
  8968. {
  8969. // This is really backing for a POINTER to a composite inside a methodRef
  8970. val = mBfIRBuilder->CreateLoad(val);
  8971. }
  8972. if ((isAddr != NULL) && (typedValue.mKind != BfTypedValueKind_SplatHead_NeedsCasting))
  8973. {
  8974. *isAddr = true;
  8975. return val;
  8976. }
  8977. else
  8978. {
  8979. val = mBfIRBuilder->CreateLoad(val);
  8980. break;
  8981. }
  8982. }
  8983. }
  8984. if (val)
  8985. break;
  8986. checkMethodState = checkMethodState->mPrevMethodState;
  8987. }
  8988. }
  8989. if (val)
  8990. {
  8991. if (typedValue.mKind == BfTypedValueKind_SplatHead_NeedsCasting)
  8992. {
  8993. BF_ASSERT(wantType != NULL);
  8994. if (wantType != NULL)
  8995. return mBfIRBuilder->CreateBitCast(val, mBfIRBuilder->MapType(wantType));
  8996. }
  8997. return val;
  8998. }
  8999. BF_FATAL("Splat not found");
  9000. return BfIRValue();
  9001. }
  9002. BfTypedValue BfModule::ExtractValue(BfTypedValue typedValue, BfFieldInstance* fieldInstance, int fieldIdx)
  9003. {
  9004. int useFieldIdx = fieldIdx;
  9005. BfType* fieldType = NULL;
  9006. if (fieldInstance != NULL)
  9007. {
  9008. fieldType = fieldInstance->mResolvedType;
  9009. if (typedValue.mType->IsUnion())
  9010. {
  9011. if (fieldIdx == 1)
  9012. {
  9013. if (typedValue.IsSplat())
  9014. {
  9015. BfTypedValue innerVal = typedValue;
  9016. innerVal.mType = fieldType;
  9017. return innerVal;
  9018. }
  9019. }
  9020. }
  9021. }
  9022. else
  9023. {
  9024. if (typedValue.mType->IsPayloadEnum())
  9025. {
  9026. auto typeInst = typedValue.mType->ToTypeInstance();
  9027. if (fieldIdx == 1)
  9028. fieldType = typeInst->GetUnionInnerType();
  9029. else if (fieldIdx == 2)
  9030. {
  9031. fieldType = typeInst->GetDiscriminatorType(&useFieldIdx);
  9032. }
  9033. }
  9034. else if (typedValue.mType->IsUnion())
  9035. {
  9036. if (fieldIdx == 1)
  9037. {
  9038. fieldType = typedValue.mType->ToTypeInstance()->GetUnionInnerType();
  9039. if (typedValue.IsSplat())
  9040. {
  9041. BfTypedValue innerVal = typedValue;
  9042. innerVal.mType = fieldType;
  9043. return innerVal;
  9044. }
  9045. }
  9046. }
  9047. }
  9048. BF_ASSERT(typedValue.mType->IsStruct());
  9049. if (typedValue.IsSplat())
  9050. {
  9051. if (typedValue.mType->IsPayloadEnum())
  9052. {
  9053. if (fieldIdx == 1)
  9054. {
  9055. // Payload
  9056. auto typeInst = typedValue.mType->ToTypeInstance();
  9057. auto unionInnerType = typeInst->GetUnionInnerType();
  9058. bool isAddr = false;
  9059. BfIRValue irVal = ExtractSplatValue(typedValue, 0, unionInnerType, &isAddr);
  9060. return BfTypedValue(irVal, unionInnerType, BfTypedValueKind_SplatHead);
  9061. }
  9062. if (fieldIdx == 2)
  9063. {
  9064. // Discriminator
  9065. auto typeInst = typedValue.mType->ToTypeInstance();
  9066. auto unionInnerType = typeInst->GetUnionInnerType();
  9067. auto dscrType = typeInst->GetDiscriminatorType();
  9068. int argIdx = typedValue.mValue.mId;
  9069. int componentIdx = 0;
  9070. BfTypeUtils::SplatIterate([&](BfType* checkType) { componentIdx++; }, unionInnerType);
  9071. bool isAddr;
  9072. BfIRValue irVal = ExtractSplatValue(typedValue, componentIdx, dscrType, &isAddr);
  9073. return BfTypedValue(irVal, dscrType, isAddr);
  9074. }
  9075. }
  9076. int componentIdx = 0;
  9077. BfTypedValue retVal;
  9078. BfFieldInstance* wantFieldInstance = fieldInstance;
  9079. std::function<void(BfType*)> checkTypeLambda = [&](BfType* checkType)
  9080. {
  9081. if (checkType->IsStruct())
  9082. {
  9083. auto checkTypeInstance = checkType->ToTypeInstance();
  9084. if ((checkType->IsUnion()) || (checkType->IsEnum()))
  9085. {
  9086. //TODO: Why did we have this removed? It messed up an extraction from a nullable splattable
  9087. fieldType = checkTypeInstance->GetUnionInnerType();
  9088. checkTypeLambda(fieldType);
  9089. if (checkType->IsEnum())
  9090. {
  9091. // Past discriminator...
  9092. componentIdx++;
  9093. }
  9094. return;
  9095. }
  9096. if (checkTypeInstance->mBaseType != NULL)
  9097. checkTypeLambda(checkTypeInstance->mBaseType);
  9098. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  9099. {
  9100. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  9101. if (fieldInstance == wantFieldInstance)
  9102. {
  9103. bool isAddr = false;
  9104. BfIRValue val = ExtractSplatValue(typedValue, componentIdx, fieldInstance->mResolvedType, &isAddr);
  9105. retVal = BfTypedValue(val, fieldInstance->mResolvedType,
  9106. fieldInstance->mResolvedType->IsComposite() ? BfTypedValueKind_SplatHead :
  9107. isAddr ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Value);
  9108. if ((retVal.IsAddr()) && (!fieldInstance->mResolvedType->IsValueType()))
  9109. {
  9110. retVal = LoadValue(retVal);
  9111. }
  9112. break;
  9113. }
  9114. if (fieldInstance->mDataIdx >= 0)
  9115. checkTypeLambda(fieldInstance->GetResolvedType());
  9116. }
  9117. }
  9118. else if (!checkType->IsValuelessType())
  9119. {
  9120. componentIdx++;
  9121. //argIdx++;
  9122. }
  9123. };
  9124. checkTypeLambda(typedValue.mType);
  9125. BF_ASSERT(retVal);
  9126. return retVal;
  9127. }
  9128. if (typedValue.IsAddr())
  9129. {
  9130. BF_ASSERT(fieldType != NULL);
  9131. auto valRef = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, useFieldIdx);
  9132. return BfTypedValue(valRef, fieldType, BfTypedValueKind_ReadOnlyAddr);
  9133. }
  9134. else
  9135. {
  9136. BF_ASSERT(fieldType != NULL);
  9137. return BfTypedValue(mBfIRBuilder->CreateExtractValue(typedValue.mValue, useFieldIdx), fieldType, BfTypedValueKind_Value);
  9138. }
  9139. }
  9140. BfIRValue BfModule::ExtractValue(BfTypedValue typedValue, int dataIdx)
  9141. {
  9142. if (typedValue.IsAddr())
  9143. {
  9144. auto addrVal = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, dataIdx);
  9145. return mBfIRBuilder->CreateLoad(addrVal);
  9146. }
  9147. return mBfIRBuilder->CreateExtractValue(typedValue.mValue, dataIdx);
  9148. }
  9149. BfIRValue BfModule::CreateIndexedValue(BfType* elementType, BfIRValue value, BfIRValue indexValue, bool isElementIndex)
  9150. {
  9151. if (elementType->IsSizeAligned())
  9152. {
  9153. if (isElementIndex)
  9154. return mBfIRBuilder->CreateInBoundsGEP(value, GetConstValue(0), indexValue);
  9155. else
  9156. return mBfIRBuilder->CreateInBoundsGEP(value, indexValue);
  9157. }
  9158. auto ptrType = CreatePointerType(elementType);
  9159. auto ofsVal = mBfIRBuilder->CreateNumericCast(indexValue, true, BfTypeCode_IntPtr);
  9160. auto ofsScaledVal = mBfIRBuilder->CreateMul(ofsVal, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, elementType->GetStride()));
  9161. auto intVal = mBfIRBuilder->CreatePtrToInt(value, BfTypeCode_IntPtr);
  9162. auto newIntVal = mBfIRBuilder->CreateAdd(intVal, ofsScaledVal);
  9163. return mBfIRBuilder->CreateIntToPtr(newIntVal, mBfIRBuilder->MapType(ptrType));
  9164. }
  9165. BfIRValue BfModule::CreateIndexedValue(BfType* elementType, BfIRValue value, int indexValue, bool isElementIndex)
  9166. {
  9167. if (elementType->IsSizeAligned())
  9168. {
  9169. if (isElementIndex)
  9170. return mBfIRBuilder->CreateInBoundsGEP(value, 0, indexValue);
  9171. else
  9172. return mBfIRBuilder->CreateInBoundsGEP(value, indexValue);
  9173. }
  9174. return CreateIndexedValue(elementType, value, GetConstValue(indexValue), isElementIndex);
  9175. }
  9176. bool BfModule::CheckModifyValue(BfTypedValue& typedValue, BfAstNode* refNode, const char* modifyType)
  9177. {
  9178. if (modifyType == NULL)
  9179. modifyType = "modify";
  9180. if (typedValue.mType->IsVar())
  9181. return true;
  9182. if (typedValue.IsReadOnly())
  9183. {
  9184. Fail(StrFormat("Cannot %s read-only variable", modifyType), refNode);
  9185. return false;
  9186. }
  9187. if ((!typedValue.IsAddr()) && (!typedValue.mType->IsValuelessType()))
  9188. {
  9189. Fail(StrFormat("Cannot %s value", modifyType), refNode);
  9190. return false;
  9191. }
  9192. if (typedValue.mKind == BfTypedValueKind_TempAddr)
  9193. {
  9194. Fail(StrFormat("Cannot %s temporary value", modifyType), refNode);
  9195. return false;
  9196. }
  9197. return true;
  9198. }
  9199. bool BfModule::CompareMethodSignatures(BfMethodInstance* methodA, BfMethodInstance* methodB)
  9200. {
  9201. // If one is an interface and the other is an impl, B is the impl
  9202. auto implOwner = methodB->GetOwner();
  9203. if (methodA->mMethodDef->mIsLocalMethod)
  9204. {
  9205. int sepPosA = (int)BF_MIN(methodA->mMethodDef->mName.IndexOf('@'), methodA->mMethodDef->mName.length());
  9206. int sepPosB = (int)BF_MIN(methodB->mMethodDef->mName.IndexOf('@'), methodB->mMethodDef->mName.length());
  9207. if (sepPosA != sepPosB)
  9208. return false;
  9209. if (strncmp(methodA->mMethodDef->mName.c_str(), methodB->mMethodDef->mName.c_str(), sepPosA) != 0)
  9210. return false;
  9211. }
  9212. else if (methodA->mMethodDef->mName != methodB->mMethodDef->mName)
  9213. return false;
  9214. if (methodA->mMethodDef->mCheckedKind != methodB->mMethodDef->mCheckedKind)
  9215. return false;
  9216. if (methodA->mMethodDef->mMethodType == BfMethodType_Ctor)
  9217. {
  9218. if (methodA->mMethodDef->mIsStatic != methodB->mMethodDef->mIsStatic)
  9219. return false;
  9220. }
  9221. if (methodA->mMethodDef->mMethodType == BfMethodType_Operator)
  9222. {
  9223. if (methodB->mMethodDef->mMethodType != BfMethodType_Operator)
  9224. return false;
  9225. auto operatorA = (BfOperatorDef*)methodA->mMethodDef;
  9226. auto operatorB = (BfOperatorDef*)methodB->mMethodDef;
  9227. if (operatorA->mOperatorDeclaration->mBinOp != operatorB->mOperatorDeclaration->mBinOp)
  9228. return false;
  9229. if (operatorA->mOperatorDeclaration->mUnaryOp != operatorB->mOperatorDeclaration->mUnaryOp)
  9230. return false;
  9231. if (operatorA->mOperatorDeclaration->mIsConvOperator)
  9232. {
  9233. if (!BfTypeUtils::TypeEquals(methodA->mReturnType, methodB->mReturnType, implOwner))
  9234. return false;
  9235. }
  9236. }
  9237. int implicitParamCountA = methodA->GetImplicitParamCount();
  9238. int implicitParamCountB = methodB->GetImplicitParamCount();
  9239. if (methodA->GetParamCount() - implicitParamCountA != methodB->GetParamCount() - implicitParamCountB)
  9240. return false;
  9241. if (methodA->mHadGenericDelegateParams != methodB->mHadGenericDelegateParams)
  9242. return false;
  9243. for (int paramIdx = 0; paramIdx < (int)methodA->GetParamCount() - implicitParamCountA; paramIdx++)
  9244. {
  9245. if ((!BfTypeUtils::TypeEquals(methodA->GetParamType(paramIdx + implicitParamCountA), methodB->GetParamType(paramIdx + implicitParamCountB), implOwner)) ||
  9246. (methodA->GetParamKind(paramIdx + implicitParamCountA) != methodB->GetParamKind(paramIdx + implicitParamCountB)))
  9247. return false;
  9248. }
  9249. // Compare generic params. Generic params are part of the method signature here
  9250. if (methodA->GetNumGenericParams() != methodB->GetNumGenericParams())
  9251. return false;
  9252. for (int genericParamIdx = 0; genericParamIdx < (int)methodA->GetNumGenericParams(); genericParamIdx++)
  9253. {
  9254. auto genericParamA = methodA->mMethodInfoEx->mGenericParams[genericParamIdx];
  9255. auto genericParamB = methodB->mMethodInfoEx->mGenericParams[genericParamIdx];
  9256. if (genericParamA->mGenericParamFlags != genericParamB->mGenericParamFlags)
  9257. return false;
  9258. if (genericParamA->mTypeConstraint != genericParamB->mTypeConstraint)
  9259. return false;
  9260. if (genericParamA->mInterfaceConstraints.size() != genericParamB->mInterfaceConstraints.size())
  9261. return false;
  9262. for (int interfaceIdx = 0; interfaceIdx < (int)genericParamA->mInterfaceConstraints.size(); interfaceIdx++)
  9263. if (genericParamA->mInterfaceConstraints[interfaceIdx] != genericParamB->mInterfaceConstraints[interfaceIdx])
  9264. return false;
  9265. }
  9266. return true;
  9267. }
  9268. bool BfModule::IsCompatibleInterfaceMethod(BfMethodInstance* iMethodInst, BfMethodInstance* methodInstance)
  9269. {
  9270. if (iMethodInst->mMethodDef->mName != methodInstance->mMethodDef->mName)
  9271. return false;
  9272. if (iMethodInst->mMethodDef->mIsOperator != methodInstance->mMethodDef->mIsOperator)
  9273. return false;
  9274. if (iMethodInst->mMethodDef->mIsOperator)
  9275. {
  9276. auto iOperatorDef = (BfOperatorDef*)iMethodInst->mMethodDef;
  9277. auto operatorDef = (BfOperatorDef*)methodInstance->mMethodDef;
  9278. if (iOperatorDef->mOperatorDeclaration->mUnaryOp != operatorDef->mOperatorDeclaration->mUnaryOp)
  9279. return false;
  9280. if (iOperatorDef->mOperatorDeclaration->mBinOp != operatorDef->mOperatorDeclaration->mBinOp)
  9281. return false;
  9282. }
  9283. if (iMethodInst->GetParamCount() != methodInstance->GetParamCount())
  9284. return false;
  9285. for (int paramIdx = 0; paramIdx < (int)iMethodInst->GetParamCount(); paramIdx++)
  9286. {
  9287. if (iMethodInst->GetParamKind(paramIdx) != methodInstance->GetParamKind(paramIdx))
  9288. return false;
  9289. BfType* iParamType = iMethodInst->GetParamType(paramIdx);
  9290. BfType* methodParamType = methodInstance->GetParamType(paramIdx);
  9291. if (iParamType->IsSelf())
  9292. {
  9293. if (methodParamType != methodInstance->GetOwner())
  9294. return false;
  9295. }
  9296. else if (!iParamType->IsGenericParam())
  9297. {
  9298. if (methodParamType != iParamType)
  9299. return false;
  9300. }
  9301. else
  9302. {
  9303. if (!methodParamType->IsGenericParam())
  9304. return false;
  9305. auto genericParamType = (BfGenericParamType*)methodParamType;
  9306. if (genericParamType->mGenericParamKind == BfGenericParamKind_Type)
  9307. return false;
  9308. auto genericParam = methodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  9309. bool hadInterface = false;
  9310. for (auto interfaceConstraint : genericParam->mInterfaceConstraints)
  9311. if (interfaceConstraint == iParamType)
  9312. hadInterface = true;
  9313. if (!hadInterface)
  9314. return false;
  9315. }
  9316. }
  9317. return true;
  9318. }
  9319. void BfModule::AddMethodReference(const BfMethodRef& methodRef, BfGetMethodInstanceFlags flags)
  9320. {
  9321. BfMethodInstance* methodInstance = methodRef;
  9322. if ((mCurTypeInstance != NULL) && (!mCompiler->IsAutocomplete()))
  9323. {
  9324. auto methodInstanceGroup = methodInstance->mMethodInstanceGroup;
  9325. if ((methodInstance->IsSpecializedGenericMethod()) || (methodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_AlwaysInclude))
  9326. {
  9327. BF_ASSERT(!methodRef.mTypeInstance->IsFunction());
  9328. BfMethodRef methodRef = methodInstance;
  9329. BfSpecializedMethodRefInfo* specializedMethodRefInfo = NULL;
  9330. bool isNew = mCurTypeInstance->mSpecializedMethodReferences.TryAdd(methodRef, NULL, &specializedMethodRefInfo);
  9331. if (((flags & BfGetMethodInstanceFlag_Unreified) == 0) &&
  9332. ((flags & BfGetMethodInstanceFlag_NoForceReification) == 0) &&
  9333. (mIsReified))
  9334. {
  9335. specializedMethodRefInfo->mHasReifiedRef = true;
  9336. }
  9337. }
  9338. }
  9339. }
  9340. BfModuleMethodInstance BfModule::ReferenceExternalMethodInstance(BfMethodInstance* methodInstance, BfGetMethodInstanceFlags flags)
  9341. {
  9342. if ((flags & BfGetMethodInstanceFlag_ResultNotUsed) != 0)
  9343. return BfModuleMethodInstance(methodInstance, BfIRValue());
  9344. if (mBfIRBuilder == NULL)
  9345. return BfModuleMethodInstance(methodInstance, BfIRValue());
  9346. if (methodInstance->GetOwner()->IsFunction())
  9347. {
  9348. // No actual ref needed- not an actual generated function
  9349. return BfModuleMethodInstance(methodInstance, BfIRValue());
  9350. }
  9351. bool isGenFunction = methodInstance->mMethodInstanceGroup->mMethodIdx < 0;
  9352. if (!isGenFunction)
  9353. AddMethodReference(methodInstance, flags);
  9354. if (mBfIRBuilder->mIgnoreWrites)
  9355. return BfModuleMethodInstance(methodInstance, mBfIRBuilder->GetFakeVal());
  9356. if (mCompiler->IsSkippingExtraResolveChecks())
  9357. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  9358. if (methodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)
  9359. {
  9360. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  9361. }
  9362. bool isInlined = (methodInstance->mAlwaysInline) || ((flags & BfGetMethodInstanceFlag_ForceInline) != 0);
  9363. BfMethodRef methodRef = methodInstance;
  9364. if (isInlined)
  9365. methodRef.mMethodRefFlags = (BfMethodRefFlags)(methodRef.mMethodRefFlags | BfMethodRefFlag_AlwaysInclude);
  9366. else
  9367. methodRef.mMethodRefFlags = BfMethodRefFlag_None;
  9368. if (!isGenFunction)
  9369. {
  9370. BfIRValue* irFuncPtr = NULL;
  9371. if (mFuncReferences.TryGetValue(methodRef, &irFuncPtr))
  9372. return BfModuleMethodInstance(methodInstance, *irFuncPtr);
  9373. }
  9374. if (mAwaitingInitFinish)
  9375. FinishInit();
  9376. BfIRValue func = CreateFunctionFrom(methodInstance, isGenFunction, isInlined);
  9377. if (!isGenFunction)
  9378. mFuncReferences[methodRef] = func;
  9379. BfLogSysM("Adding func reference. Module:%p MethodInst:%p NewLLVMFunc:%d OldLLVMFunc:%d\n", this, methodInstance, func.mId, methodInstance->mIRFunction.mId);
  9380. if ((isInlined) && (!mIsScratchModule))
  9381. {
  9382. // We can't just add a dependency to mCurTypeInstance because we may have nested inlined functions, and
  9383. // mCurTypeInstance will just reflect the owner of the method currently being inlined, not the top-level
  9384. // type instance
  9385. // Be smarter about this if we ever insert a lot of type instances into a single module - track in a field
  9386. BF_ASSERT(mOwnedTypeInstances.size() <= 1);
  9387. for (auto ownedTypeInst : mOwnedTypeInstances)
  9388. AddDependency(methodInstance->GetOwner(), ownedTypeInst, BfDependencyMap::DependencyFlag_InlinedCall);
  9389. if ((!mCompiler->mIsResolveOnly) && (mIsReified) && (!methodInstance->mIsUnspecialized))
  9390. {
  9391. mIncompleteMethodCount++;
  9392. BfInlineMethodRequest* inlineMethodRequest = mContext->mInlineMethodWorkList.Alloc();
  9393. inlineMethodRequest->mType = methodInstance->GetOwner();
  9394. inlineMethodRequest->mFromModule = this;
  9395. inlineMethodRequest->mFunc = func;
  9396. inlineMethodRequest->mFromModuleRevision = mRevision;
  9397. inlineMethodRequest->mMethodInstance = methodInstance;
  9398. BF_ASSERT(mIsModuleMutable);
  9399. BfLogSysM("mInlineMethodWorkList %p for method %p in module %p in ReferenceExternalMethodInstance\n", inlineMethodRequest, methodInstance, this);
  9400. }
  9401. }
  9402. return BfModuleMethodInstance(methodInstance, func);
  9403. }
  9404. BfModule* BfModule::GetOrCreateMethodModule(BfMethodInstance* methodInstance)
  9405. {
  9406. BfTypeInstance* typeInst = methodInstance->mMethodInstanceGroup->mOwner;
  9407. if (mBfIRBuilder == NULL)
  9408. {
  9409. // To allow for custom attribute data
  9410. PrepareForIRWriting(typeInst);
  9411. }
  9412. BfModule* declareModule = this;
  9413. // Get to the optionless branch head -- but this could still be a specialized method module, not the true root
  9414. while ((declareModule->mParentModule != NULL) && (!declareModule->mIsSpecializedMethodModuleRoot))
  9415. declareModule = declareModule->mParentModule;
  9416. // Check for attributes
  9417. if (typeInst == mContext->mBfObjectType)
  9418. {
  9419. auto methodDecl = methodInstance->mMethodDef->GetMethodDeclaration();
  9420. if (methodDecl != NULL)
  9421. {
  9422. auto attributesDirective = methodDecl->mAttributes;
  9423. if ((attributesDirective != NULL) && (mCompiler->mResolvePassData != NULL) &&
  9424. (attributesDirective->IsFromParser(mCompiler->mResolvePassData->mParser)) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  9425. {
  9426. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(attributesDirective);
  9427. }
  9428. }
  9429. }
  9430. else
  9431. {
  9432. // Only allow attributes on System.Object methods that can be handled inside the DefBuilder
  9433. GetMethodCustomAttributes(methodInstance);
  9434. }
  9435. BF_ASSERT(mModuleOptions == NULL);
  9436. if (methodInstance->GetCustomAttributes() != NULL)
  9437. {
  9438. auto project = typeInst->mTypeDef->mProject;
  9439. BfModuleOptions moduleOptions = declareModule->GetModuleOptions();
  9440. BfModuleOptions wantOptions = moduleOptions;
  9441. auto typeOptions = mSystem->GetTypeOptions(typeInst->mTypeOptionsIdx);
  9442. if (typeOptions != NULL)
  9443. {
  9444. wantOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)wantOptions.mOptLevel, (int)typeOptions->mOptimizationLevel);
  9445. wantOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mSIMDSetting, typeOptions->mSIMDSetting);
  9446. wantOptions.mEmitDebugInfo = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mEmitDebugInfo, typeOptions->mEmitDebugInfo);
  9447. }
  9448. if (!mCompiler->mAttributeTypeOptionMap.IsEmpty())
  9449. {
  9450. StringT<128> attrName;
  9451. for (auto& customAttrs : methodInstance->GetCustomAttributes()->mAttributes)
  9452. {
  9453. attrName.Clear();
  9454. customAttrs.mType->mTypeDef->mFullName.ToString(attrName);
  9455. Array<int>* arrPtr;
  9456. if (mCompiler->mAttributeTypeOptionMap.TryGetValue(attrName, &arrPtr))
  9457. {
  9458. for (auto optionsIdx : *arrPtr)
  9459. {
  9460. auto& typeOptions = mCompiler->mSystem->mTypeOptions[optionsIdx];
  9461. wantOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)wantOptions.mOptLevel, (int)typeOptions.mOptimizationLevel);
  9462. wantOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mSIMDSetting, typeOptions.mSIMDSetting);
  9463. wantOptions.mEmitDebugInfo = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mEmitDebugInfo, typeOptions.mEmitDebugInfo);
  9464. }
  9465. }
  9466. }
  9467. }
  9468. if ((HasCompiledOutput()) && (wantOptions != moduleOptions) && (!mIsScratchModule))
  9469. {
  9470. auto lastCheckModule = this;
  9471. auto checkModule = this->mNextAltModule;
  9472. while (checkModule != NULL)
  9473. {
  9474. if (*checkModule->mModuleOptions == wantOptions)
  9475. {
  9476. declareModule = checkModule;
  9477. break;
  9478. }
  9479. lastCheckModule = checkModule;
  9480. checkModule = checkModule->mNextAltModule;
  9481. }
  9482. // Not found?
  9483. if (declareModule == this)
  9484. {
  9485. String specModuleName = mModuleName + "@@";
  9486. if (wantOptions.mOptLevel != moduleOptions.mOptLevel)
  9487. specModuleName += StrFormat("O%d", wantOptions.mOptLevel);
  9488. if (wantOptions.mSIMDSetting != moduleOptions.mSIMDSetting)
  9489. specModuleName += StrFormat("SIMD%d", wantOptions.mSIMDSetting);
  9490. declareModule = new BfModule(mContext, specModuleName);
  9491. declareModule->mProject = project;
  9492. declareModule->mModuleOptions = new BfModuleOptions();
  9493. *declareModule->mModuleOptions = wantOptions;
  9494. declareModule->mParentModule = lastCheckModule;
  9495. declareModule->Init();
  9496. lastCheckModule->mNextAltModule = declareModule;
  9497. }
  9498. }
  9499. }
  9500. declareModule->PrepareForIRWriting(typeInst);
  9501. return declareModule;
  9502. }
  9503. BfModuleMethodInstance BfModule::GetMethodInstance(BfTypeInstance* typeInst, BfMethodDef* methodDef, const BfTypeVector& methodGenericArguments, BfGetMethodInstanceFlags flags, BfTypeInstance* foreignType)
  9504. {
  9505. if (((flags & BfGetMethodInstanceFlag_ForceInline) != 0) && (mCompiler->mIsResolveOnly))
  9506. {
  9507. // Don't bother inlining for resolve-only
  9508. flags = (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline);
  9509. }
  9510. bool processNow = false;
  9511. bool keepInCurrentModule = false;
  9512. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsUnspecialized))
  9513. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_NoForceReification);
  9514. if (!typeInst->IsTypeMemberIncluded(methodDef->mDeclaringType))
  9515. {
  9516. return BfModuleMethodInstance();
  9517. }
  9518. if (methodDef->mIsLocalMethod)
  9519. {
  9520. auto rootMethodState = mCurMethodState->GetRootMethodState();
  9521. BfLocalMethod* localMethod;
  9522. if (rootMethodState->mLocalMethodCache.TryGetValue(methodDef->mName, &localMethod))
  9523. {
  9524. // Handle the def in the correct method state
  9525. return GetLocalMethodInstance(localMethod, methodGenericArguments);
  9526. }
  9527. BF_FATAL("Cannot find local method");
  9528. return BfModuleMethodInstance();
  9529. }
  9530. #ifdef _DEBUG
  9531. for (auto arg : methodGenericArguments)
  9532. BF_ASSERT(!arg->IsVar());
  9533. #endif
  9534. BF_ASSERT(methodDef->mMethodType != BfMethodType_Ignore);
  9535. // We need to do the 'mNeedsMethodProcessing' check because we want to do a proper initial "awaiting reference" population
  9536. // on the methods before we handle an on-demand situation. This also ensures that our type options are set before doing
  9537. // a FinishInit
  9538. if ((typeInst->IsIncomplete()) &&
  9539. (!typeInst->mResolvingVarField) && (!typeInst->mTypeFailed))
  9540. {
  9541. // For autocomplete, we still may not actually generate methods. This shouldn't matter, and on-demand works differently
  9542. // for resolve-only because we don't differentiate between reified/unreified there
  9543. PopulateType(typeInst, BfPopulateType_Full);
  9544. }
  9545. bool tryModuleMethodLookup = false;
  9546. BfModuleMethodInstance moduleMethodInst;
  9547. BfModule* instModule = typeInst->mModule;
  9548. if (keepInCurrentModule)
  9549. {
  9550. // Stay here
  9551. instModule = this;
  9552. }
  9553. if (this == mContext->mUnreifiedModule)
  9554. {
  9555. // Stay in this 'resolve only' module here
  9556. }
  9557. else if (flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass)
  9558. {
  9559. BF_ASSERT(this == mContext->mUnreifiedModule);
  9560. }
  9561. else if (flags & BfGetMethodInstanceFlag_ExplicitSpecializedModule)
  9562. {
  9563. BF_ASSERT(instModule == mParentModule);
  9564. }
  9565. else if (instModule != this)
  9566. {
  9567. if ((!mIsReified) && (instModule->mIsReified))
  9568. {
  9569. BF_ASSERT(!mCompiler->mIsResolveOnly);
  9570. // A resolve-only module is specializing a method from a type in a reified module,
  9571. // we need to take care that this doesn't cause anything new to become reified
  9572. return mContext->mUnreifiedModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ExplicitResolveOnlyPass), foreignType);
  9573. }
  9574. else
  9575. {
  9576. if ((mIsReified) && (!instModule->mIsReified))
  9577. {
  9578. if (!instModule->mReifyQueued)
  9579. {
  9580. BF_ASSERT((mCompiler->mCompileState != BfCompiler::CompileState_Unreified) && (mCompiler->mCompileState != BfCompiler::CompileState_VData));
  9581. BfLogSysM("Queueing ReifyModule: %p\n", instModule);
  9582. mContext->mReifyModuleWorkList.Add(instModule);
  9583. instModule->mReifyQueued = true;
  9584. }
  9585. // This ensures that the method will actually be created when it gets reified
  9586. BfMethodSpecializationRequest* specializationRequest = mContext->mMethodSpecializationWorkList.Alloc();
  9587. specializationRequest->mFromModule = typeInst->mModule;
  9588. specializationRequest->mFromModuleRevision = typeInst->mModule->mRevision;
  9589. specializationRequest->mMethodDef = methodDef;
  9590. specializationRequest->mMethodGenericArguments = methodGenericArguments;
  9591. specializationRequest->mType = typeInst;
  9592. specializationRequest->mFlags = flags;
  9593. }
  9594. auto defFlags = (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline);
  9595. // Not extern
  9596. // Create the instance in the proper module and then create a reference in this one
  9597. moduleMethodInst = instModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, defFlags, foreignType);
  9598. tryModuleMethodLookup = true;
  9599. if ((mIsReified) && (!moduleMethodInst.mMethodInstance->mIsReified))
  9600. {
  9601. CheckHotMethod(moduleMethodInst.mMethodInstance, "");
  9602. }
  9603. }
  9604. }
  9605. if (tryModuleMethodLookup)
  9606. return ReferenceExternalMethodInstance(moduleMethodInst.mMethodInstance, flags);
  9607. if (((flags & BfGetMethodInstanceFlag_ForceInline) != 0) && (!methodDef->mAlwaysInline))
  9608. {
  9609. auto moduleMethodInstance = GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline), foreignType);
  9610. if (moduleMethodInstance)
  9611. return ReferenceExternalMethodInstance(moduleMethodInstance.mMethodInstance, flags);
  9612. return moduleMethodInst;
  9613. }
  9614. bool isReified = mIsReified /* || ((flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass) != 0)*/;
  9615. bool hadConcreteInterfaceGenericArgument = false;
  9616. if ((flags & BfGetMethodInstanceFlag_Unreified) != 0)
  9617. isReified = false;
  9618. if ((flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass) != 0)
  9619. {
  9620. isReified = false;
  9621. }
  9622. BfTypeVector sanitizedMethodGenericArguments;
  9623. SizedArray<BfProject*, 4> projectList;
  9624. bool isUnspecializedPass = (flags & BfGetMethodInstanceFlag_UnspecializedPass) != 0;
  9625. if ((isUnspecializedPass) && (methodDef->mGenericParams.size() == 0))
  9626. isUnspecializedPass = false;
  9627. // 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
  9628. bool isExternalExtensionMethod = false;
  9629. if ((!typeInst->IsUnspecializedType()) && (!isUnspecializedPass))
  9630. {
  9631. if (((flags & BfGetMethodInstanceFlag_ForeignMethodDef) == 0) && (methodDef->mDeclaringType->mProject != typeInst->mTypeDef->mProject))
  9632. {
  9633. auto specProject = methodDef->mDeclaringType->mProject;
  9634. isExternalExtensionMethod = true;
  9635. if (typeInst->IsGenericTypeInstance())
  9636. {
  9637. auto genericTypeInst = (BfGenericTypeInstance*)typeInst;
  9638. if (genericTypeInst->mProjectsReferenced.empty())
  9639. genericTypeInst->GenerateProjectsReferenced();
  9640. if (genericTypeInst->mProjectsReferenced.Contains(specProject))
  9641. {
  9642. // This is a generic type where a generic param is already confined to the project in question
  9643. isExternalExtensionMethod = false;
  9644. }
  9645. }
  9646. if (isExternalExtensionMethod)
  9647. {
  9648. BF_ASSERT(typeInst->mTypeDef->mIsCombinedPartial);
  9649. projectList.push_back(methodDef->mDeclaringType->mProject);
  9650. }
  9651. }
  9652. }
  9653. if ((!isUnspecializedPass) && (methodGenericArguments.size() != 0))
  9654. {
  9655. int typeProjectsCounts = 0;
  9656. if (typeInst->IsGenericTypeInstance())
  9657. {
  9658. auto genericTypeInst = (BfGenericTypeInstance*)typeInst;
  9659. if (genericTypeInst->mProjectsReferenced.empty())
  9660. genericTypeInst->GenerateProjectsReferenced();
  9661. typeProjectsCounts = (int)genericTypeInst->mProjectsReferenced.size();
  9662. projectList.Insert(0, &genericTypeInst->mProjectsReferenced[0], genericTypeInst->mProjectsReferenced.size());
  9663. }
  9664. else
  9665. {
  9666. typeProjectsCounts = 1;
  9667. projectList.Insert(0, typeInst->mTypeDef->mProject);
  9668. }
  9669. isUnspecializedPass = true;
  9670. for (int genericArgIdx = 0; genericArgIdx < (int) methodGenericArguments.size(); genericArgIdx++)
  9671. {
  9672. auto genericArgType = methodGenericArguments[genericArgIdx];
  9673. //BF_ASSERT(!genericArgType->IsRef());
  9674. if (genericArgType->IsConcreteInterfaceType())
  9675. {
  9676. hadConcreteInterfaceGenericArgument = true;
  9677. auto concreteInterfaceType = (BfConcreteInterfaceType*)genericArgType;
  9678. genericArgType = concreteInterfaceType->mInterface;
  9679. }
  9680. if (genericArgType->IsGenericParam())
  9681. {
  9682. auto genericParam = (BfGenericParamType*) genericArgType;
  9683. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  9684. isUnspecializedPass = false;
  9685. }
  9686. else
  9687. {
  9688. BfTypeUtils::GetProjectList(genericArgType, &projectList, typeProjectsCounts);
  9689. isUnspecializedPass = false;
  9690. }
  9691. sanitizedMethodGenericArguments.push_back(genericArgType);
  9692. }
  9693. if ((int)projectList.size() > typeProjectsCounts)
  9694. {
  9695. // Just leave the new items
  9696. projectList.RemoveRange(0, typeProjectsCounts);
  9697. std::sort(projectList.begin(), projectList.end(), [](BfProject* lhs, BfProject*rhs)
  9698. {
  9699. return lhs->mName < rhs->mName;
  9700. });
  9701. }
  9702. else
  9703. {
  9704. projectList.Clear();
  9705. }
  9706. }
  9707. const BfTypeVector& lookupMethodGenericArguments = isUnspecializedPass ? BfTypeVector() : sanitizedMethodGenericArguments;
  9708. BfMethodInstanceGroup* methodInstGroup = NULL;
  9709. if ((flags & BfGetMethodInstanceFlag_ForeignMethodDef) != 0)
  9710. {
  9711. BF_ASSERT(!typeInst->IsInterface());
  9712. //for (auto& checkGroup : typeInst->mMethodInstanceGroups)
  9713. for (int methodIdx = (int)typeInst->mTypeDef->mMethods.size(); methodIdx < (int)typeInst->mMethodInstanceGroups.size(); methodIdx++)
  9714. {
  9715. auto& checkGroup = typeInst->mMethodInstanceGroups[methodIdx];
  9716. // if (checkGroup.mDefault == NULL)
  9717. // {
  9718. // // This should only be for when we explicitly add a spot so we can set mOnDemandKind
  9719. // BF_ASSERT(methodIdx == typeInst->mMethodInstanceGroups.size() - 1);
  9720. // methodInstGroup = &checkGroup;
  9721. // break;
  9722. // }
  9723. if ((checkGroup.mDefault != NULL) && (checkGroup.mDefault->mMethodDef == methodDef))
  9724. {
  9725. methodInstGroup = &checkGroup;
  9726. break;
  9727. }
  9728. }
  9729. if (methodInstGroup == NULL)
  9730. {
  9731. // Allocate a new entry
  9732. typeInst->mMethodInstanceGroups.Resize(typeInst->mMethodInstanceGroups.size() + 1);
  9733. methodInstGroup = &typeInst->mMethodInstanceGroups.back();
  9734. methodInstGroup->mMethodIdx = (int)typeInst->mMethodInstanceGroups.size() - 1;
  9735. methodInstGroup->mOwner = typeInst;
  9736. // if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet)
  9737. // methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  9738. if (mCompiler->mOptions.mCompileOnDemandKind == BfCompileOnDemandKind_AlwaysInclude)
  9739. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  9740. else
  9741. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingDecl;
  9742. }
  9743. }
  9744. else
  9745. {
  9746. methodInstGroup = &typeInst->mMethodInstanceGroups[methodDef->mIdx];
  9747. }
  9748. if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet)
  9749. {
  9750. BfLogSysM("Forcing BfMethodOnDemandKind_NotSet to BfMethodOnDemandKind_AlwaysInclude for Method:%s in Type:%p\n", methodDef->mName.c_str(), typeInst);
  9751. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  9752. }
  9753. BfIRFunction prevIRFunc;
  9754. bool doingRedeclare = false;
  9755. BfMethodInstance* methodInstance = NULL;
  9756. auto _SetReified = [&]()
  9757. {
  9758. methodInstance->mIsReified = true;
  9759. };
  9760. if (lookupMethodGenericArguments.size() == 0)
  9761. {
  9762. methodInstance = methodInstGroup->mDefault;
  9763. if ((methodInstance != NULL) && (isReified) && (!methodInstance->mIsReified))
  9764. {
  9765. MarkDerivedDirty(typeInst);
  9766. if (mIsScratchModule)
  9767. {
  9768. BfLogSysM("Marking scratch module method instance as reified: %p\n", methodInstance);
  9769. _SetReified();
  9770. CheckHotMethod(methodInstance, "");
  9771. }
  9772. else if ((flags & BfGetMethodInstanceFlag_NoForceReification) != 0)
  9773. {
  9774. // We don't need to force reification if we're in an unspecialized generic- we can wait for
  9775. // the specializations to handle that for us
  9776. return BfModuleMethodInstance(methodInstance);
  9777. }
  9778. else if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_Referenced)
  9779. {
  9780. if (methodDef->mIsAbstract)
  9781. {
  9782. BfLogSysM("Reifying abstract unreified method instance: %p IRFunction:%d\n", methodInstance, methodInstance->mIRFunction.mId);
  9783. _SetReified();
  9784. }
  9785. else
  9786. {
  9787. BfLogSysM("Re-declaring processed but unreified method instance: %p IRFunction:%d\n", methodInstance, methodInstance->mIRFunction.mId);
  9788. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_NoDecl_AwaitingReference;
  9789. methodInstance->UndoDeclaration(!methodInstance->mIRFunction.IsFake());
  9790. doingRedeclare = true;
  9791. mOnDemandMethodCount++;
  9792. }
  9793. }
  9794. else
  9795. {
  9796. BfLogSysM("Marking unprocessed method instance as reified: %p\n", methodInstance);
  9797. // We haven't processed it yet
  9798. _SetReified();
  9799. CheckHotMethod(methodInstance, "");
  9800. if (methodInstance->mDeclModule == this)
  9801. {
  9802. if (methodInstance->mMethodProcessRequest != NULL)
  9803. {
  9804. // Disconnect method process request
  9805. BF_ASSERT(methodInstance->mMethodProcessRequest->mFromModule == this);
  9806. }
  9807. }
  9808. else
  9809. {
  9810. if (methodInstance->mMethodProcessRequest != NULL)
  9811. {
  9812. // Disconnect method process request
  9813. BF_ASSERT(methodInstance->mMethodProcessRequest->mFromModule == mContext->mUnreifiedModule);
  9814. methodInstance->mMethodProcessRequest->mMethodInstance = NULL;
  9815. methodInstance->mMethodProcessRequest = NULL;
  9816. }
  9817. if (methodInstance->mDeclModule == mContext->mUnreifiedModule)
  9818. {
  9819. // Add new request in proper module
  9820. methodInstance->mDeclModule = this;
  9821. }
  9822. else
  9823. {
  9824. if (methodInstance->mDeclModule == NULL)
  9825. {
  9826. //
  9827. }
  9828. else if (methodInstance->mDeclModule != this)
  9829. {
  9830. // Is from specialized module?
  9831. BF_ASSERT(methodInstance->mDeclModule->mParentModule == this);
  9832. }
  9833. }
  9834. if ((!methodInstance->mIRFunction) || (methodInstance->mIRFunction.IsFake()))
  9835. {
  9836. methodInstance->mIRFunction = BfIRFunction();
  9837. if (!mIsModuleMutable)
  9838. StartExtension();
  9839. if ((!mBfIRBuilder->mIgnoreWrites) && (methodInstance->mDeclModule != NULL))
  9840. {
  9841. StringT<128> mangledName;
  9842. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  9843. bool isIntrinsic = false;
  9844. SetupIRFunction(methodInstance, mangledName, false, &isIntrinsic);
  9845. BfLogSysM("Creating new IRFunction %d\n", methodInstance->mIRFunction.mId);
  9846. }
  9847. }
  9848. AddMethodToWorkList(methodInstance);
  9849. }
  9850. }
  9851. }
  9852. }
  9853. else
  9854. {
  9855. BF_ASSERT(lookupMethodGenericArguments.size() != 0);
  9856. if (methodInstGroup->mMethodSpecializationMap == NULL)
  9857. methodInstGroup->mMethodSpecializationMap = new BfMethodInstanceGroup::MapType();
  9858. BfMethodInstance** methodInstancePtr = NULL;
  9859. if (methodInstGroup->mMethodSpecializationMap->TryGetValue(lookupMethodGenericArguments, &methodInstancePtr))
  9860. {
  9861. methodInstance = *methodInstancePtr;
  9862. if ((isReified) && (!methodInstance->mIsReified))
  9863. {
  9864. MarkDerivedDirty(typeInst);
  9865. if (methodInstance->mHasBeenProcessed)
  9866. {
  9867. BfLogSysM("Deleting processed but unreified specialized method instance %p\n", methodInstance);
  9868. delete methodInstance;
  9869. methodInstGroup->mMethodSpecializationMap->Remove(lookupMethodGenericArguments);
  9870. methodInstance = NULL;
  9871. }
  9872. else if ((!methodInstance->mIRFunction) || (methodInstance->mIRFunction.IsFake()))
  9873. {
  9874. BfLogSysM("Deleting declared but uncreated specialized method instance %p\n", methodInstance);
  9875. delete methodInstance;
  9876. methodInstGroup->mMethodSpecializationMap->Remove(lookupMethodGenericArguments);
  9877. methodInstance = NULL;
  9878. }
  9879. else
  9880. {
  9881. BfLogSysM("Reifying declared but unreified method instance %p\n", methodInstance);
  9882. // We haven't processed it yet
  9883. _SetReified();
  9884. CheckHotMethod(methodInstance, "");
  9885. }
  9886. }
  9887. }
  9888. }
  9889. if ((methodInstance != NULL) && (!doingRedeclare))
  9890. {
  9891. if (methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference)
  9892. {
  9893. /*if ((!mCompiler->mIsResolveOnly) && (!isReified))
  9894. BF_ASSERT(!methodInstance->mIsReified);*/
  9895. if (methodInstance->mIsReified != isReified)
  9896. BfLogSysM("GetMethodInstance %p Decl_AwaitingReference setting reified to %d\n", methodInstance, isReified);
  9897. if ((!isReified) &&
  9898. ((methodInstance->mDeclModule == NULL) || (!methodInstance->mDeclModule->mIsModuleMutable)))
  9899. {
  9900. methodInstance->mDeclModule = mContext->mUnreifiedModule;
  9901. methodInstance->mIRFunction = BfIRFunction();
  9902. }
  9903. methodInstance->mIsReified = isReified;
  9904. if ((methodInstance->mHotMethod != NULL) && (!mCompiler->IsHotCompile()) && (isReified))
  9905. {
  9906. methodInstance->mHotMethod->mFlags = (BfHotDepDataFlags)(methodInstance->mHotMethod->mFlags | BfHotDepDataFlag_IsOriginalBuild);
  9907. }
  9908. if (!methodInstance->mMethodDef->mIsAbstract)
  9909. {
  9910. AddMethodToWorkList(methodInstance);
  9911. }
  9912. else
  9913. {
  9914. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Referenced;
  9915. }
  9916. }
  9917. if (mExtensionCount > 0)
  9918. {
  9919. if ((mIsModuleMutable) && (!methodInstance->mIRFunction) &&
  9920. ((projectList.IsEmpty() || ((flags & BfGetMethodInstanceFlag_ExplicitSpecializedModule) != 0))))
  9921. {
  9922. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, false);
  9923. if (mAwaitingInitFinish)
  9924. FinishInit();
  9925. // We need to refer to a function that was defined in a prior module
  9926. bool isInlined = (methodInstance->mAlwaysInline) || ((flags & BfGetMethodInstanceFlag_ForceInline) != 0);
  9927. methodInstance->mIRFunction = CreateFunctionFrom(methodInstance, false, isInlined);
  9928. BF_ASSERT((methodInstance->mDeclModule == this) || (methodInstance->mDeclModule == mContext->mUnreifiedModule) || (methodInstance->mDeclModule == NULL));
  9929. methodInstance->mDeclModule = this;
  9930. // Add this inlined def to ourselves
  9931. if ((methodInstance->mAlwaysInline) && (HasCompiledOutput()) && (!methodInstance->mIsUnspecialized))
  9932. {
  9933. mIncompleteMethodCount++;
  9934. BfInlineMethodRequest* inlineMethodRequest = mContext->mInlineMethodWorkList.Alloc();
  9935. inlineMethodRequest->mType = typeInst;
  9936. inlineMethodRequest->mFromModule = this;
  9937. inlineMethodRequest->mFunc = methodInstance->mIRFunction;
  9938. inlineMethodRequest->mFromModuleRevision = mRevision;
  9939. inlineMethodRequest->mMethodInstance = methodInstance;
  9940. BfLogSysM("mInlineMethodWorkList %p for method %p in module %p in GetMethodInstance\n", inlineMethodRequest, methodInstance, this);
  9941. BF_ASSERT(mIsModuleMutable);
  9942. }
  9943. }
  9944. }
  9945. if (mCompiler->IsSkippingExtraResolveChecks())
  9946. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  9947. else
  9948. {
  9949. if (methodInstance->mDeclModule != this)
  9950. return ReferenceExternalMethodInstance(methodInstance, flags);
  9951. if ((!methodInstance->mIRFunction) && (mIsModuleMutable) && (!mBfIRBuilder->mIgnoreWrites))
  9952. {
  9953. auto importKind = methodInstance->GetImportCallKind();
  9954. if (importKind != BfImportCallKind_None)
  9955. {
  9956. BfLogSysM("DllImportGlobalVar creating %p\n", methodInstance);
  9957. methodInstance->mIRFunction = mBfIRBuilder->GetFakeVal();
  9958. mFuncReferences[methodInstance] = CreateDllImportGlobalVar(methodInstance, true);;
  9959. }
  9960. }
  9961. return BfModuleMethodInstance(methodInstance);
  9962. }
  9963. }
  9964. if (!doingRedeclare)
  9965. {
  9966. BfModule* specModule = NULL;
  9967. if ((!keepInCurrentModule) && (projectList.size() > 0) && (!isUnspecializedPass) && (HasCompiledOutput()) && (!mIsScratchModule))
  9968. {
  9969. specModule = GetSpecializedMethodModule(projectList);
  9970. }
  9971. if ((specModule != NULL) && (specModule != this))
  9972. {
  9973. auto specMethodInstance = specModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ExplicitSpecializedModule));
  9974. if (mAwaitingInitFinish)
  9975. return BfModuleMethodInstance(specMethodInstance.mMethodInstance, BfIRFunction());
  9976. return ReferenceExternalMethodInstance(specMethodInstance.mMethodInstance, flags);
  9977. }
  9978. if ((!isUnspecializedPass) && (methodGenericArguments.size() != 0) && (methodInstGroup->mDefault == NULL))
  9979. {
  9980. // We are attempting to specialize but we don't have the unspecialized method yet. Generate that first.
  9981. GetMethodInstance(typeInst, methodDef, BfTypeVector(), BfGetMethodInstanceFlag_UnspecializedPass);
  9982. }
  9983. }
  9984. if (methodInstance == NULL)
  9985. {
  9986. if (lookupMethodGenericArguments.size() == 0)
  9987. {
  9988. BF_ASSERT(methodInstGroup->mDefault == NULL);
  9989. methodInstance = new BfMethodInstance();
  9990. methodInstGroup->mDefault = methodInstance;
  9991. BfLogSysM("Created Default MethodInst: %p TypeInst: %p Group: %p\n", methodInstance, typeInst, methodInstGroup);
  9992. }
  9993. else
  9994. {
  9995. BfMethodInstance** methodInstancePtr = NULL;
  9996. bool added = methodInstGroup->mMethodSpecializationMap->TryAdd(lookupMethodGenericArguments, NULL, &methodInstancePtr);
  9997. BF_ASSERT(added);
  9998. methodInstance = new BfMethodInstance();
  9999. *methodInstancePtr = methodInstance;
  10000. BfLogSysM("Created Specialized MethodInst: %p TypeInst: %p\n", methodInstance, typeInst);
  10001. }
  10002. if ((prevIRFunc) && (!prevIRFunc.IsFake()))
  10003. methodInstance->mIRFunction = prevIRFunc; // Take it over
  10004. }
  10005. /*// 24 bits for typeid, 20 for method id, 20 for specialization index
  10006. methodInstance->mMethodId = ((int64)typeInst->mTypeId) + ((int64)methodInstGroup->mMethodIdx << 24);
  10007. if (methodInstGroup->mMethodSpecializationMap != NULL)
  10008. methodInstance->mMethodId += ((int64)methodInstGroup->mMethodSpecializationMap->size() << 44);*/
  10009. methodInstance->mMethodDef = methodDef;
  10010. methodInstance->mAlwaysInline = methodDef->mAlwaysInline;
  10011. methodInstance->mMethodInstanceGroup = methodInstGroup;
  10012. methodInstance->mIsReified = isReified;
  10013. SetupMethodIdHash(methodInstance);
  10014. if (hadConcreteInterfaceGenericArgument)
  10015. methodInstance->mIgnoreBody = true;
  10016. if ((flags & BfGetMethodInstanceFlag_ForeignMethodDef) != 0)
  10017. {
  10018. methodInstance->mIsForeignMethodDef = true;
  10019. BF_ASSERT(foreignType != NULL);
  10020. methodInstance->GetMethodInfoEx()->mForeignType = foreignType;
  10021. }
  10022. if ((typeInst->mTypeDef == mCompiler->mValueTypeTypeDef) && (methodDef->mName == BF_METHODNAME_EQUALS))
  10023. {
  10024. if (!lookupMethodGenericArguments.empty())
  10025. {
  10026. auto compareType = lookupMethodGenericArguments[0];
  10027. PopulateType(compareType, BfPopulateType_Data);
  10028. if (compareType->IsSplattable())
  10029. methodInstance->mAlwaysInline = true;
  10030. }
  10031. }
  10032. if (methodDef->mDeclaringType->mTypeDeclaration != typeInst->mTypeDef->mTypeDeclaration)
  10033. {
  10034. // With extensions we can have multiple definitions of the same method
  10035. //methodInstance->mMangleWithIdx = true;
  10036. }
  10037. BfModule* declareModule = GetOrCreateMethodModule(methodInstance);
  10038. BF_ASSERT(typeInst == methodInstance->GetOwner());
  10039. auto methodDeclaration = methodDef->GetMethodDeclaration();
  10040. if (isUnspecializedPass)
  10041. {
  10042. for (int genericParamIdx = 0; genericParamIdx < (int) methodDef->mGenericParams.size(); genericParamIdx++)
  10043. {
  10044. auto genericParamType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  10045. methodInstance->GetMethodInfoEx()->mMethodGenericArguments.Add(genericParamType);
  10046. }
  10047. }
  10048. else if ((methodDeclaration != NULL) && (methodDeclaration->mGenericParams != NULL))
  10049. {
  10050. if (!sanitizedMethodGenericArguments.IsEmpty())
  10051. methodInstance->GetMethodInfoEx()->mMethodGenericArguments = sanitizedMethodGenericArguments;
  10052. if (methodDef->mGenericParams.size() != sanitizedMethodGenericArguments.size())
  10053. {
  10054. Fail("Internal error");
  10055. BF_FATAL("Generic method argument counts mismatch");
  10056. return NULL;
  10057. }
  10058. for (auto genericArg : sanitizedMethodGenericArguments)
  10059. {
  10060. if (genericArg->IsPrimitiveType())
  10061. genericArg = GetWrappedStructType(genericArg);
  10062. AddDependency(genericArg, typeInst, BfDependencyMap::DependencyFlag_MethodGenericArg);
  10063. if (genericArg->IsMethodRef())
  10064. {
  10065. auto methodRefType = (BfMethodRefType*)genericArg;
  10066. //AddDependency(genericArg, typeInst, BfDependencyMap::DependencyFlag_);
  10067. }
  10068. }
  10069. }
  10070. // Generic constraints
  10071. for (int genericParamIdx = 0; genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  10072. {
  10073. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, genericParamIdx);
  10074. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  10075. }
  10076. for (int externConstraintIdx = 0; externConstraintIdx < (int)methodDef->mExternalConstraints.size(); externConstraintIdx++)
  10077. {
  10078. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, externConstraintIdx + (int)methodDef->mGenericParams.size());
  10079. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  10080. }
  10081. bool addToWorkList = !processNow;
  10082. if (mCompiler->GetAutoComplete() != NULL)
  10083. {
  10084. if (typeInst->IsSpecializedByAutoCompleteMethod())
  10085. addToWorkList = false;
  10086. }
  10087. BF_ASSERT(declareModule != NULL);
  10088. methodInstance->mDeclModule = declareModule;
  10089. if ((!methodInstance->mIsReified) && (mCompiler->mCompileState != BfCompiler::CompileState_Normal))
  10090. {
  10091. // We can be sure this method won't become reified later. Normally we can "go either way" with an unreified method
  10092. // of a reified module -
  10093. // If we declare it in the reified module then we can switch it to "reified" before actual processing without any extra work,
  10094. // BUT if we don't reify it then we have to remove the body after processing.
  10095. // 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
  10096. // the proper reified module.
  10097. declareModule = mContext->mUnreifiedModule;
  10098. }
  10099. else if ((!declareModule->mIsModuleMutable) && (!mCompiler->mIsResolveOnly))
  10100. {
  10101. BF_ASSERT(!methodInstance->mIsReified);
  10102. declareModule = mContext->mUnreifiedModule;
  10103. }
  10104. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  10105. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(declareModule->mCurTypeInstance, typeInst);
  10106. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  10107. declareModule->DoMethodDeclaration(methodDef->GetMethodDeclaration(), false, addToWorkList);
  10108. if (processNow)
  10109. {
  10110. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, NULL);
  10111. ProcessMethod(methodInstance);
  10112. }
  10113. if (mCompiler->IsSkippingExtraResolveChecks())
  10114. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  10115. return BfModuleMethodInstance(methodInstance);
  10116. }
  10117. BfModuleMethodInstance BfModule::GetMethodInstance(BfMethodInstance* methodInstance, BfGetMethodInstanceFlags flags)
  10118. {
  10119. BF_ASSERT((methodInstance->mMethodInfoEx == NULL) || (methodInstance->mMethodInfoEx->mGenericParams.IsEmpty()));
  10120. if (methodInstance->mIsForeignMethodDef)
  10121. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ForeignMethodDef);
  10122. return GetMethodInstance(methodInstance->GetOwner(), methodInstance->mMethodDef, BfTypeVector(), flags);
  10123. }
  10124. BfMethodInstance* BfModule::GetOuterMethodInstance(BfMethodInstance* methodInstance)
  10125. {
  10126. if (!methodInstance->mMethodDef->mIsLocalMethod)
  10127. return NULL;
  10128. auto outerLocal = methodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod->mOuterLocalMethod;
  10129. if (outerLocal == NULL)
  10130. return NULL;
  10131. BfTypeVector genericArgs;
  10132. for (int i = 0; i < (int)outerLocal->mMethodDef->mGenericParams.size(); i++)
  10133. genericArgs.Add(methodInstance->mMethodInfoEx->mMethodGenericArguments[i]);
  10134. return GetLocalMethodInstance(outerLocal, genericArgs).mMethodInstance;
  10135. }
  10136. void BfModule::SetupMethodIdHash(BfMethodInstance* methodInstance)
  10137. {
  10138. HashContext hashCtx;
  10139. std::function<void(BfMethodInstance*)> _MixinMethodInstance = [&](BfMethodInstance* methodInstance)
  10140. {
  10141. hashCtx.Mixin(methodInstance->GetOwner()->mTypeId);
  10142. hashCtx.Mixin(methodInstance->mMethodDef->mIdx);
  10143. if (methodInstance->GetNumGenericArguments() != 0)
  10144. {
  10145. hashCtx.Mixin((int32)methodInstance->mMethodInfoEx->mMethodGenericArguments.size());
  10146. for (auto methodGenericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  10147. hashCtx.Mixin(methodGenericArg->mTypeId);
  10148. }
  10149. };
  10150. _MixinMethodInstance(methodInstance);
  10151. if (methodInstance->mMethodDef->mIsLocalMethod)
  10152. {
  10153. auto outmostMethodInstance = mCurMethodState->GetRootMethodState()->mMethodInstance;
  10154. BF_ASSERT((outmostMethodInstance->mIdHash != 0) || (outmostMethodInstance->mIsAutocompleteMethod));
  10155. hashCtx.Mixin(outmostMethodInstance->mIdHash);
  10156. }
  10157. methodInstance->mIdHash = (int64)hashCtx.Finish64();
  10158. }
  10159. BfIRValue BfModule::GetInterfaceSlotNum(BfTypeInstance* ifaceType)
  10160. {
  10161. BfIRValue globalValue;
  10162. BfIRValue* globalValuePtr = NULL;
  10163. if (mInterfaceSlotRefs.TryGetValue(ifaceType, &globalValuePtr))
  10164. {
  10165. globalValue = *globalValuePtr;
  10166. }
  10167. if (!globalValue)
  10168. {
  10169. // This is necessary to reify the interface type
  10170. PopulateType(ifaceType);
  10171. StringT<128> slotVarName;
  10172. BfMangler::MangleStaticFieldName(slotVarName, mCompiler->GetMangleKind(), ifaceType, "sBfSlotOfs");
  10173. BfType* intType = GetPrimitiveType(BfTypeCode_Int32);
  10174. BfIRValue value;
  10175. if ((mCompiler->mHotState != NULL) && (ifaceType->mSlotNum >= 0))
  10176. {
  10177. /*// If this interface already existed before this hot compile but we never indirectly called any of its methods
  10178. // then the sBfSlotOfs could have gotten its symbol stripped, so actually define it here.
  10179. int virtSlotIdx = ifaceType->mSlotNum + 1;
  10180. value = GetConstValue32(virtSlotIdx);*/
  10181. mCompiler->mHotState->mSlotDefineTypeIds.Add(ifaceType->mTypeId);
  10182. ifaceType->mDirty = true; // Makes sure we create interface in vdata
  10183. }
  10184. globalValue = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(intType), true, BfIRLinkageType_External, value, slotVarName);
  10185. mInterfaceSlotRefs[ifaceType] = globalValue;
  10186. }
  10187. return mBfIRBuilder->CreateLoad(globalValue/*, "slotOfs"*/);
  10188. }
  10189. void BfModule::HadSlotCountDependency()
  10190. {
  10191. if (mCompiler->mIsResolveOnly)
  10192. return;
  10193. BF_ASSERT(!mBfIRBuilder->mIgnoreWrites);
  10194. BF_ASSERT((mUsedSlotCount == BF_MAX(mCompiler->mMaxInterfaceSlots, 0)) || (mUsedSlotCount == -1));
  10195. mUsedSlotCount = BF_MAX(mCompiler->mMaxInterfaceSlots, 0);
  10196. }
  10197. BfTypedValue BfModule::ReferenceStaticField(BfFieldInstance* fieldInstance)
  10198. {
  10199. if (mIsScratchModule)
  10200. {
  10201. // Just fake it for the extern and unspecialized modules
  10202. auto ptrType = CreatePointerType(fieldInstance->GetResolvedType());
  10203. return BfTypedValue(GetDefaultValue(ptrType), fieldInstance->GetResolvedType(), true);
  10204. }
  10205. BfIRValue globalValue;
  10206. auto fieldDef = fieldInstance->GetFieldDef();
  10207. if ((fieldDef->mIsConst) && (!fieldDef->mIsExtern))
  10208. {
  10209. if (fieldInstance->mConstIdx != -1)
  10210. {
  10211. auto constant = fieldInstance->mOwner->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  10212. return BfTypedValue(ConstantToCurrent(constant, fieldInstance->mOwner->mConstHolder, fieldInstance->GetResolvedType()), fieldInstance->GetResolvedType());
  10213. }
  10214. else
  10215. {
  10216. return GetDefaultTypedValue(fieldInstance->GetResolvedType());
  10217. }
  10218. }
  10219. BfIRValue* globalValuePtr = NULL;
  10220. if (mStaticFieldRefs.TryGetValue(fieldInstance, &globalValuePtr))
  10221. {
  10222. globalValue = *globalValuePtr;
  10223. BF_ASSERT(globalValue);
  10224. }
  10225. else
  10226. {
  10227. StringT<128> staticVarName;
  10228. BfMangler::Mangle(staticVarName, mCompiler->GetMangleKind(), fieldInstance);
  10229. auto typeType = fieldInstance->GetResolvedType();
  10230. if ((fieldDef->mIsExtern) && (fieldDef->mIsConst) && (typeType->IsPointer()))
  10231. {
  10232. typeType = typeType->GetUnderlyingType();
  10233. }
  10234. PopulateType(typeType);
  10235. if ((typeType != NULL) && (!typeType->IsValuelessType()))
  10236. {
  10237. globalValue = mBfIRBuilder->CreateGlobalVariable(
  10238. mBfIRBuilder->MapType(typeType),
  10239. false,
  10240. BfIRLinkageType_External,
  10241. BfIRValue(),
  10242. staticVarName,
  10243. IsThreadLocal(fieldInstance));
  10244. if (!mBfIRBuilder->mIgnoreWrites)
  10245. {
  10246. // Only store this if we actually did the creation
  10247. BF_ASSERT(globalValue);
  10248. mStaticFieldRefs[fieldInstance] = globalValue;
  10249. }
  10250. BfLogSysM("Mod:%p Type:%p ReferenceStaticField %p -> %p\n", this, fieldInstance->mOwner, fieldInstance, globalValue);
  10251. }
  10252. }
  10253. auto type = fieldInstance->GetResolvedType();
  10254. if (type->IsValuelessType())
  10255. return BfTypedValue(globalValue, type);
  10256. return BfTypedValue(globalValue, type, !fieldDef->mIsConst);
  10257. }
  10258. BfTypedValue BfModule::GetThis()
  10259. {
  10260. auto useMethodState = mCurMethodState;
  10261. while ((useMethodState != NULL) && (useMethodState->mClosureState != NULL) && (useMethodState->mClosureState->mCapturing))
  10262. {
  10263. useMethodState = useMethodState->mPrevMethodState;
  10264. }
  10265. if (useMethodState != NULL)
  10266. {
  10267. // Fake a 'this' for var field resolution
  10268. if (useMethodState->mTempKind == BfMethodState::TempKind_NonStatic)
  10269. {
  10270. auto thisType = mCurTypeInstance;
  10271. if (thisType->IsValueType())
  10272. return BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(thisType)), thisType, BfTypedValueKind_ThisAddr);
  10273. else
  10274. return BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInst(thisType)), thisType, BfTypedValueKind_ThisValue);
  10275. }
  10276. else if (useMethodState->mTempKind == BfMethodState::TempKind_Static)
  10277. {
  10278. return BfTypedValue();
  10279. }
  10280. }
  10281. else
  10282. {
  10283. //TODO: Do we allow useMethodState to be NULL anymore?
  10284. return BfTypedValue();
  10285. }
  10286. // if (useMethodState->HasNonStaticMixin())
  10287. // {
  10288. // auto checkMethodState = useMethodState;
  10289. // while (checkMethodState != NULL)
  10290. // {
  10291. // for (int localIdx = (int)checkMethodState->mLocals.size() - 1; localIdx >= 0; localIdx--)
  10292. // {
  10293. // auto varDecl = checkMethodState->mLocals[localIdx];
  10294. // if (varDecl->mName == "this")
  10295. // {
  10296. // varDecl->mReadFromId = useMethodState->GetRootMethodState()->mCurAccessId++;
  10297. // if (varDecl->mIsSplat)
  10298. // {
  10299. // return BfTypedValue(varDecl->mValue, varDecl->mResolvedType, BfTypedValueKind_ThisSplatHead);
  10300. // }
  10301. // else if ((varDecl->mResolvedType->IsValueType()) && (varDecl->mAddr))
  10302. // {
  10303. // return BfTypedValue(varDecl->mAddr, varDecl->mResolvedType, BfTypedValueKind_ThisAddr);
  10304. // }
  10305. // return BfTypedValue(varDecl->mValue, varDecl->mResolvedType, varDecl->mResolvedType->IsValueType() ? BfTypedValueKind_ThisAddr : BfTypedValueKind_ThisValue);
  10306. // }
  10307. // }
  10308. //
  10309. // checkMethodState = checkMethodState->mPrevMethodState;
  10310. // }
  10311. // }
  10312. // Check mixin state for 'this'
  10313. {
  10314. auto checkMethodState = useMethodState;
  10315. while (checkMethodState != NULL)
  10316. {
  10317. if (checkMethodState->mMixinState != NULL)
  10318. {
  10319. BfTypedValue thisValue = checkMethodState->mMixinState->mTarget;
  10320. if (thisValue)
  10321. {
  10322. checkMethodState->mMixinState->mLastTargetAccessId = useMethodState->GetRootMethodState()->mCurAccessId++;
  10323. if (!thisValue.mType->IsValueType())
  10324. thisValue = LoadValue(thisValue);
  10325. return thisValue;
  10326. }
  10327. }
  10328. checkMethodState = checkMethodState->mPrevMethodState;
  10329. }
  10330. }
  10331. auto curMethodInstance = mCurMethodInstance;
  10332. if (useMethodState->mMethodInstance != NULL)
  10333. curMethodInstance = useMethodState->mMethodInstance;
  10334. if ((curMethodInstance == NULL) /*|| (!mCurMethodInstance->mIRFunction)*/ || (curMethodInstance->mMethodDef->mIsStatic))
  10335. {
  10336. if ((useMethodState->mClosureState != NULL) && (!useMethodState->mClosureState->mConstLocals.empty()))
  10337. {
  10338. auto& constLocal = useMethodState->mClosureState->mConstLocals[0];
  10339. if (constLocal.mIsThis)
  10340. {
  10341. BF_ASSERT(constLocal.mResolvedType->IsValuelessType());
  10342. return BfTypedValue(mBfIRBuilder->GetFakeVal(), constLocal.mResolvedType);
  10343. }
  10344. }
  10345. return BfTypedValue();
  10346. }
  10347. bool preferValue = !IsTargetingBeefBackend();
  10348. if (useMethodState->mLocals.IsEmpty())
  10349. {
  10350. // 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
  10351. BF_ASSERT(useMethodState->mPrevMethodState != NULL);
  10352. return BfTypedValue();
  10353. }
  10354. auto thisLocal = useMethodState->mLocals[0];
  10355. BF_ASSERT(thisLocal->mIsThis);
  10356. BfIRValue thisValue;
  10357. if ((preferValue) || (!thisLocal->mAddr) /*|| (thisLocal->mIsSplat)*/)
  10358. thisValue = thisLocal->mValue;
  10359. else if ((thisLocal->mIsSplat) || (thisLocal->mIsLowered))
  10360. thisValue = thisLocal->mAddr;
  10361. else
  10362. thisValue = mBfIRBuilder->CreateLoad(thisLocal->mAddr);
  10363. useMethodState->mLocals[0]->mReadFromId = useMethodState->GetRootMethodState()->mCurAccessId++;
  10364. if (useMethodState->mClosureState != NULL)
  10365. {
  10366. auto closureTypeInst = useMethodState->mClosureState->mClosureType;
  10367. if (closureTypeInst != NULL)
  10368. {
  10369. if (closureTypeInst->mFieldInstances.size() > 0)
  10370. {
  10371. auto& field = closureTypeInst->mFieldInstances[0];
  10372. auto fieldDef = field.GetFieldDef();
  10373. if (fieldDef->mName == "__this")
  10374. {
  10375. if (mCurMethodState->mClosureState->mCapturing)
  10376. mCurMethodState->mClosureState->mReferencedOuterClosureMembers.Add(&field);
  10377. // This is a captured 'this'
  10378. BfTypedValue result = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(thisValue, 0, field.mDataIdx), field.mResolvedType, true);
  10379. if (field.mResolvedType->IsRef())
  10380. {
  10381. auto refType = (BfRefType*)field.mResolvedType;
  10382. auto underlyingType = refType->GetUnderlyingType();
  10383. result = BfTypedValue(mBfIRBuilder->CreateLoad(result.mValue), underlyingType, true);
  10384. }
  10385. if (field.mResolvedType->IsObject())
  10386. {
  10387. result = LoadValue(result);
  10388. result.mKind = BfTypedValueKind_ThisValue;
  10389. }
  10390. else
  10391. {
  10392. if (fieldDef->mIsReadOnly)
  10393. result.mKind = BfTypedValueKind_ReadOnlyThisAddr;
  10394. else
  10395. result.mKind = BfTypedValueKind_ThisAddr;
  10396. }
  10397. return result;
  10398. }
  10399. }
  10400. return BfTypedValue();
  10401. }
  10402. if (useMethodState->mClosureState->mCapturing)
  10403. {
  10404. auto thisType = useMethodState->mLocals[0]->mResolvedType;
  10405. if (thisType->IsValueType())
  10406. return BfTypedValue(CreateAlloca(thisType), thisType, BfTypedValueKind_ThisAddr);
  10407. else
  10408. return BfTypedValue(GetDefaultValue(thisType), thisType, BfTypedValueKind_ThisValue);
  10409. }
  10410. }
  10411. auto localDef = useMethodState->mLocals[0];
  10412. auto curMethodOwner = mCurMethodInstance->mMethodInstanceGroup->mOwner;
  10413. if ((curMethodOwner->IsStruct()) || (curMethodOwner->IsTypedPrimitive()))
  10414. {
  10415. if ((localDef->mResolvedType->IsTypedPrimitive()) && (!mCurMethodInstance->mMethodDef->mIsMutating))
  10416. {
  10417. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, BfTypedValueKind_ReadOnlyThisValue);
  10418. }
  10419. if (localDef->mIsSplat)
  10420. {
  10421. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, BfTypedValueKind_ThisSplatHead);
  10422. }
  10423. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, localDef->mIsReadOnly ? BfTypedValueKind_ReadOnlyThisAddr : BfTypedValueKind_ThisAddr);
  10424. }
  10425. return BfTypedValue(thisValue, mCurMethodInstance->mMethodInstanceGroup->mOwner, BfTypedValueKind_ThisValue);
  10426. }
  10427. BfLocalVariable* BfModule::GetThisVariable()
  10428. {
  10429. if (mCurMethodState == NULL)
  10430. return NULL;
  10431. auto methodState = mCurMethodState->GetNonCaptureState();
  10432. if ((methodState->mLocals.size() > 0) && (methodState->mLocals[0]->mIsThis))
  10433. return methodState->mLocals[0];
  10434. return NULL;
  10435. }
  10436. bool BfModule::IsInGeneric()
  10437. {
  10438. return (mCurMethodInstance->GetNumGenericArguments() != 0) || (mCurTypeInstance->IsGenericTypeInstance());
  10439. }
  10440. bool BfModule::IsInSpecializedGeneric()
  10441. {
  10442. if ((mCurMethodInstance == NULL) || (mCurMethodInstance->mIsUnspecialized))
  10443. return false;
  10444. return (mCurMethodInstance->GetNumGenericArguments() != 0) || (mCurTypeInstance->IsGenericTypeInstance());
  10445. }
  10446. bool BfModule::IsInSpecializedSection()
  10447. {
  10448. return IsInSpecializedGeneric() ||
  10449. ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL));
  10450. }
  10451. bool BfModule::IsInUnspecializedGeneric()
  10452. {
  10453. if (mCurMethodInstance != NULL)
  10454. return mCurMethodInstance->mIsUnspecialized;
  10455. return false;
  10456. }
  10457. //////////////////////////////////////////////////////////////////////////
  10458. BfIRValue BfModule::AllocLocalVariable(BfType* type, const StringImpl& name, bool doLifetimeEnd)
  10459. {
  10460. //if ((type->IsValuelessType()) || (type->IsMethodRef()))
  10461. if (type->IsValuelessType())
  10462. return mBfIRBuilder->GetFakeVal();
  10463. auto allocaInst = CreateAlloca(type, doLifetimeEnd, name.c_str());
  10464. if ((!doLifetimeEnd) && (WantsLifetimes()))
  10465. {
  10466. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  10467. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  10468. }
  10469. bool initLocalVariables = mCompiler->mOptions.mInitLocalVariables;
  10470. auto typeOptions = GetTypeOptions();
  10471. if (typeOptions != NULL)
  10472. initLocalVariables = BfTypeOptions::Apply(initLocalVariables, typeOptions->mInitLocalVariables);
  10473. // Local variable inits are implicitly handled in the Beef Backend
  10474. if ((initLocalVariables) && (!IsTargetingBeefBackend()))
  10475. {
  10476. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  10477. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  10478. auto storeInst = mBfIRBuilder->CreateAlignedStore(GetDefaultValue(type), allocaInst, type->mAlign);
  10479. mBfIRBuilder->ClearDebugLocation(storeInst);
  10480. mBfIRBuilder->SetInsertPoint(prevBlock);
  10481. }
  10482. return allocaInst;
  10483. }
  10484. void BfModule::DoAddLocalVariable(BfLocalVariable* localVar)
  10485. {
  10486. localVar->mLocalVarIdx = (int)mCurMethodState->mLocals.size();
  10487. mCurMethodState->mLocals.push_back(localVar);
  10488. BfLocalVarEntry* localVarEntryPtr;
  10489. if (!mCurMethodState->mLocalVarSet.TryAdd(BfLocalVarEntry(localVar), &localVarEntryPtr))
  10490. {
  10491. localVar->mShadowedLocal = localVarEntryPtr->mLocalVar;
  10492. localVarEntryPtr->mLocalVar = localVar;
  10493. }
  10494. }
  10495. BfLocalVariable* BfModule::AddLocalVariableDef(BfLocalVariable* localVarDef, bool addDebugInfo, bool doAliasValue, BfIRValue declareBefore, BfIRInitType initType)
  10496. {
  10497. if ((localVarDef->mValue) && (!localVarDef->mAddr) && (IsTargetingBeefBackend()))
  10498. {
  10499. if ((!localVarDef->mValue.IsConst()) && (!localVarDef->mValue.IsArg()) && (!localVarDef->mValue.IsFake()))
  10500. {
  10501. mBfIRBuilder->CreateValueScopeRetain(localVarDef->mValue);
  10502. mCurMethodState->mCurScope->mHadScopeValueRetain = true;
  10503. }
  10504. }
  10505. if ((addDebugInfo) && (mBfIRBuilder->DbgHasInfo()) &&
  10506. ((mCurMethodInstance == NULL) || (!mCurMethodInstance->mIsUnspecialized)) &&
  10507. (mHasFullDebugInfo) &&
  10508. ((mCurMethodState->mClosureState == NULL) || (!mCurMethodState->mClosureState->mCapturing)))
  10509. {
  10510. auto varType = localVarDef->mResolvedType;
  10511. if (localVarDef->mResolvedType->IsValuelessType())
  10512. {
  10513. }
  10514. else
  10515. {
  10516. bool isByAddr = false;
  10517. auto diValue = localVarDef->mValue;
  10518. if (localVarDef->mConstValue)
  10519. diValue = localVarDef->mConstValue;
  10520. else if (localVarDef->mAddr)
  10521. {
  10522. diValue = localVarDef->mAddr;
  10523. isByAddr = true;
  10524. }
  10525. auto diType = mBfIRBuilder->DbgGetType(localVarDef->mResolvedType);
  10526. bool didConstToMem = false;
  10527. bool isConstant = false;
  10528. if ((localVarDef->mIsReadOnly) && (localVarDef->mAddr))
  10529. diType = mBfIRBuilder->DbgCreateConstType(diType);
  10530. else if (localVarDef->mConstValue)
  10531. {
  10532. auto constant = mBfIRBuilder->GetConstant(localVarDef->mConstValue);
  10533. isConstant =
  10534. (constant->mConstType < BfConstType_GlobalVar) ||
  10535. (constant->mConstType == BfConstType_AggZero) ||
  10536. (constant->mConstType == BfConstType_Array);
  10537. if (isConstant)
  10538. {
  10539. if (localVarDef->mResolvedType->IsComposite())
  10540. {
  10541. mBfIRBuilder->PopulateType(localVarDef->mResolvedType);
  10542. auto constMem = mBfIRBuilder->ConstToMemory(localVarDef->mConstValue);
  10543. if (IsTargetingBeefBackend())
  10544. {
  10545. diValue = mBfIRBuilder->CreateAliasValue(constMem);
  10546. didConstToMem = true;
  10547. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  10548. }
  10549. else
  10550. {
  10551. isByAddr = true;
  10552. mBfIRBuilder->SaveDebugLocation();
  10553. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  10554. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  10555. mBfIRBuilder->ClearDebugLocation();
  10556. auto ptrType = CreatePointerType(localVarDef->mResolvedType);
  10557. auto addrVal = CreateAlloca(ptrType);
  10558. mBfIRBuilder->CreateStore(constMem, addrVal);
  10559. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  10560. diValue = addrVal;
  10561. didConstToMem = true;
  10562. mBfIRBuilder->SetInsertPoint(prevBlock);
  10563. mBfIRBuilder->RestoreDebugLocation();
  10564. }
  10565. }
  10566. if (mCompiler->mOptions.IsCodeView())
  10567. diType = mBfIRBuilder->DbgCreateConstType(diType);
  10568. }
  10569. }
  10570. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  10571. localVarDef->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, initType);
  10572. localVarDef->mDbgVarInst = diVariable;
  10573. if (mBfIRBuilder->HasDebugLocation())
  10574. {
  10575. if ((isConstant) && (!didConstToMem))
  10576. {
  10577. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(localVarDef->mConstValue, diVariable);
  10578. }
  10579. else
  10580. {
  10581. if ((IsTargetingBeefBackend()) && (doAliasValue))
  10582. {
  10583. diValue = mBfIRBuilder->CreateAliasValue(diValue);
  10584. mCurMethodState->mCurScope->mDeferredLifetimeEnds.Add(diValue);
  10585. }
  10586. if (isByAddr)
  10587. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertDeclare(diValue, diVariable, declareBefore);
  10588. else if (diValue)
  10589. {
  10590. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(diValue, diVariable);
  10591. }
  10592. else if (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU) // DWARF chokes on this:
  10593. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  10594. }
  10595. }
  10596. }
  10597. }
  10598. localVarDef->mDeclBlock = mBfIRBuilder->GetInsertBlock();
  10599. DoAddLocalVariable(localVarDef);
  10600. auto rootMethodState = mCurMethodState->GetRootMethodState();
  10601. if (localVarDef->mLocalVarId == -1)
  10602. {
  10603. BF_ASSERT(rootMethodState->mCurLocalVarId >= 0);
  10604. localVarDef->mLocalVarId = rootMethodState->mCurLocalVarId++;
  10605. }
  10606. if ((localVarDef->mNameNode != NULL) && (mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  10607. mCompiler->mResolvePassData->mAutoComplete->CheckLocalDef(localVarDef->mNameNode, localVarDef);
  10608. if ((localVarDef->mNameNode != NULL) && (mCurMethodInstance != NULL))
  10609. {
  10610. bool isClosureProcessing = (mCurMethodState->mClosureState != NULL) && (!mCurMethodState->mClosureState->mCapturing);
  10611. if ((!isClosureProcessing) && (mCompiler->mResolvePassData != NULL) && (localVarDef->mNameNode != NULL))
  10612. mCompiler->mResolvePassData->HandleLocalReference(localVarDef->mNameNode, rootMethodState->mMethodInstance->GetOwner()->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, localVarDef->mLocalVarId);
  10613. }
  10614. return localVarDef;
  10615. }
  10616. void BfModule::CreateDIRetVal()
  10617. {
  10618. if (!WantsDebugInfo())
  10619. return;
  10620. /*if (!mCurMethodState->mRetVal)
  10621. {
  10622. if (mCurMethodInstance->mMethodDef->mName != "Ziggle")
  10623. return;
  10624. }*/
  10625. if ((mCurMethodState->mRetVal) || (mCurMethodState->mRetValAddr))
  10626. {
  10627. BfType* dbgType = mCurMethodInstance->mReturnType;
  10628. BfIRValue dbgValue = mCurMethodState->mRetVal.mValue;
  10629. if (mCurMethodInstance->HasStructRet())
  10630. {
  10631. BF_ASSERT(mCurMethodState->mRetValAddr);
  10632. dbgType = CreatePointerType(dbgType);
  10633. dbgValue = mCurMethodState->mRetValAddr;
  10634. }
  10635. else
  10636. {
  10637. BF_ASSERT(!mCurMethodState->mRetValAddr);
  10638. }
  10639. mCurMethodState->mDIRetVal = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  10640. "__return", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(dbgType));
  10641. auto declareCall = mBfIRBuilder->DbgInsertDeclare(dbgValue, mCurMethodState->mDIRetVal);
  10642. }
  10643. }
  10644. void BfModule::CheckVariableDef(BfLocalVariable* variableDef)
  10645. {
  10646. BfLocalVarEntry* localVarEntryPtr = NULL;
  10647. if ((mCurMethodState != NULL) && (mCurMethodState->mLocalVarSet.TryGet(BfLocalVarEntry(variableDef), &localVarEntryPtr)))
  10648. {
  10649. auto checkLocal = localVarEntryPtr->mLocalVar;
  10650. if ((checkLocal->mLocalVarIdx >= mCurMethodState->GetLocalStartIdx()) && (!checkLocal->mIsShadow))
  10651. {
  10652. BfError* error;
  10653. if (checkLocal->mIsImplicitParam)
  10654. return; // Ignore 'redefinition'
  10655. if (checkLocal->IsParam())
  10656. error = Fail(StrFormat("A parameter named '%s' has already been declared.", variableDef->mName.c_str()), variableDef->mNameNode);
  10657. else if (checkLocal->mLocalVarIdx < mCurMethodState->mCurScope->mLocalVarStart)
  10658. error = Fail(StrFormat("A variable named '%s' has already been declared in this parent's scope.", variableDef->mName.c_str()), variableDef->mNameNode);
  10659. else
  10660. error = Fail(StrFormat("A variable named '%s' has already been declared in this scope.", variableDef->mName.c_str()), variableDef->mNameNode);
  10661. if ((checkLocal->mNameNode != NULL) && (error != NULL))
  10662. mCompiler->mPassInstance->MoreInfo("Previous declaration", checkLocal->mNameNode);
  10663. return;
  10664. }
  10665. }
  10666. }
  10667. BfScopeData* BfModule::FindScope(BfAstNode* scopeName, BfMixinState* fromMixinState, bool allowAcrossDeferredBlock)
  10668. {
  10669. bool inMixinDecl = (mCurMethodInstance != NULL) && (mCurMethodInstance->IsMixin());
  10670. if (auto tokenNode = BfNodeDynCast<BfTokenNode>(scopeName))
  10671. {
  10672. if (tokenNode->GetToken() == BfToken_Colon)
  10673. {
  10674. if ((!allowAcrossDeferredBlock) && (mCurMethodState->mInDeferredBlock))
  10675. {
  10676. Fail("Cannot access method scope across deferred block boundary", scopeName);
  10677. return NULL;
  10678. }
  10679. return &mCurMethodState->mHeadScope;
  10680. }
  10681. else if (tokenNode->GetToken() == BfToken_Mixin)
  10682. {
  10683. if (fromMixinState == NULL)
  10684. {
  10685. if (mCurMethodInstance->mMethodDef->mMethodType != BfMethodType_Mixin)
  10686. Fail("'mixin' scope specifier can only be used within a mixin declaration", scopeName);
  10687. return mCurMethodState->mCurScope;
  10688. }
  10689. fromMixinState->mUsedInvocationScope = true;
  10690. return fromMixinState->mTargetScope;
  10691. }
  10692. else if (tokenNode->GetToken() == BfToken_New)
  10693. return NULL;
  10694. }
  10695. if (auto identifier = BfNodeDynCast<BfIdentifierNode>(scopeName))
  10696. {
  10697. auto findLabel = scopeName->ToString();
  10698. bool crossedDeferredBlock = false;
  10699. auto checkScope = mCurMethodState->mCurScope;
  10700. while (checkScope != NULL)
  10701. {
  10702. if (checkScope->mIsDeferredBlock)
  10703. crossedDeferredBlock = true;
  10704. if (checkScope->mLabel == findLabel)
  10705. {
  10706. if ((crossedDeferredBlock) && (!allowAcrossDeferredBlock))
  10707. {
  10708. Fail(StrFormat("Cannot access scope '%s' across deferred block boundary", findLabel.c_str()), scopeName);
  10709. return NULL;
  10710. }
  10711. return checkScope;
  10712. }
  10713. checkScope = checkScope->mPrevScope;
  10714. }
  10715. if (!inMixinDecl)
  10716. Fail(StrFormat("Unable to locate label '%s'", findLabel.c_str()), scopeName);
  10717. }
  10718. if (auto scopeNode = BfNodeDynCast<BfScopeNode>(scopeName))
  10719. {
  10720. return FindScope(scopeNode->mTargetNode, allowAcrossDeferredBlock);
  10721. }
  10722. return mCurMethodState->mCurScope;
  10723. }
  10724. BfScopeData* BfModule::FindScope(BfAstNode* scopeName, bool allowAcrossDeferredBlock)
  10725. {
  10726. return FindScope(scopeName, mCurMethodState->mMixinState, allowAcrossDeferredBlock);
  10727. }
  10728. BfBreakData* BfModule::FindBreakData(BfAstNode* scopeName)
  10729. {
  10730. auto scopeData = FindScope(scopeName, false);
  10731. if (scopeData == NULL)
  10732. return NULL;
  10733. int scopeDepth = scopeData->GetDepth();
  10734. // Find the first break data that is at or below the depth of our requested scope
  10735. auto breakData = mCurMethodState->mBreakData;
  10736. while ((breakData != NULL) && (scopeDepth < breakData->mScope->GetDepth()))
  10737. {
  10738. if (breakData->mScope->mIsConditional)
  10739. return NULL;
  10740. breakData = breakData->mPrevBreakData;
  10741. }
  10742. return breakData;
  10743. }
  10744. void BfModule::EmitLifetimeEnds(BfScopeData* scopeData)
  10745. {
  10746. // LLVM is stricter about the placement of these (ie: they can't occur after a 'ret')
  10747. if (!IsTargetingBeefBackend())
  10748. return;
  10749. for (auto lifetimeEnd : scopeData->mDeferredLifetimeEnds)
  10750. {
  10751. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  10752. }
  10753. }
  10754. void BfModule::ClearLifetimeEnds()
  10755. {
  10756. auto scopeData = mCurMethodState->mCurScope;
  10757. while (scopeData != NULL)
  10758. {
  10759. scopeData->mDeferredLifetimeEnds.Clear();
  10760. scopeData = scopeData->mPrevScope;
  10761. }
  10762. }
  10763. bool BfModule::WantsDebugInfo()
  10764. {
  10765. if ((mCurMethodInstance != NULL) &&
  10766. ((mCurMethodInstance->mIsUnspecialized) || (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)))
  10767. return false;
  10768. return (mBfIRBuilder->DbgHasInfo()) && (mHasFullDebugInfo) &&
  10769. ((mCurMethodState == NULL) || (mCurMethodState->mClosureState == NULL) || (!mCurMethodState->mClosureState->mCapturing));
  10770. }
  10771. BfTypeOptions* BfModule::GetTypeOptions()
  10772. {
  10773. if ((mCurMethodState != NULL) && (mCurMethodState->mMethodTypeOptions != NULL))
  10774. return mCurMethodState->mMethodTypeOptions;
  10775. return mSystem->GetTypeOptions(mCurTypeInstance->mTypeOptionsIdx);
  10776. }
  10777. bool BfModule::HasDeferredScopeCalls(BfScopeData* scope)
  10778. {
  10779. BfScopeData* checkScope = mCurMethodState->mCurScope;
  10780. while (checkScope != NULL)
  10781. {
  10782. if ((!checkScope->mDeferredCallEntries.IsEmpty()) || (!checkScope->mDeferredLifetimeEnds.empty()))
  10783. return true;
  10784. if (checkScope == scope)
  10785. break;
  10786. checkScope = checkScope->mPrevScope;
  10787. }
  10788. return false;
  10789. }
  10790. void BfModule::EmitDeferredScopeCalls(bool useSrcPositions, BfScopeData* scopeData, BfIRBlock doneBlock)
  10791. {
  10792. // Is there anything we need to do here?
  10793. if (mBfIRBuilder->mIgnoreWrites)
  10794. {
  10795. // Just visit deferred blocks
  10796. BfScopeData* checkScope = mCurMethodState->mCurScope;
  10797. while (checkScope != NULL)
  10798. {
  10799. BfDeferredCallEntry* deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  10800. while (deferredCallEntry != NULL)
  10801. {
  10802. if (deferredCallEntry->mDeferredBlock != NULL)
  10803. {
  10804. VisitEmbeddedStatement(deferredCallEntry->mDeferredBlock, NULL, BfEmbeddedStatementFlags_IsDeferredBlock);
  10805. }
  10806. deferredCallEntry = deferredCallEntry->mNext;
  10807. }
  10808. if (checkScope == scopeData)
  10809. break;
  10810. checkScope = checkScope->mPrevScope;
  10811. }
  10812. return;
  10813. }
  10814. // Why did we want to do SetIllegalSrcPos here?
  10815. // Don't we always want to step onto these instances?
  10816. // Find a case where we don't and perhaps only do it there.
  10817. // The downside was that 'EmitEnsureInstructionAt' on the end of block statements causes
  10818. // a (seemingly) unneeded NOP when we do SetIllegalSrcPos
  10819. //SetIllegalSrcPos();
  10820. bool setSrcPos = false;
  10821. bool wantsNop = true;
  10822. BfAstNode* deferCloseNode = NULL;
  10823. if (mCurMethodState->mInPostReturn)
  10824. {
  10825. // These won't get used, they are post-return
  10826. return;
  10827. }
  10828. SizedArray<BfIRValue, 8> deferredLifetimeEnds;
  10829. BfScopeData* scopeJumpBlock = NULL;
  10830. bool hadExtraDeferredLifetimeEnds = false;
  10831. auto _FlushLifetimeEnds = [&]()
  10832. {
  10833. for (auto lifetimeEnd : deferredLifetimeEnds)
  10834. {
  10835. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  10836. mBfIRBuilder->ClearDebugLocation_Last();
  10837. }
  10838. deferredLifetimeEnds.clear();
  10839. };
  10840. BfScopeData* checkScope = mCurMethodState->mCurScope;
  10841. while (checkScope != NULL)
  10842. {
  10843. if (checkScope->mCloseNode != NULL)
  10844. deferCloseNode = checkScope->mCloseNode;
  10845. if (doneBlock)
  10846. {
  10847. // Try to find a match where we've already emitted these calls and then jumped to the correct block
  10848. for (auto& checkHandler : checkScope->mDeferredHandlers)
  10849. {
  10850. if (checkHandler.mDoneBlock == doneBlock)
  10851. {
  10852. scopeJumpBlock = checkScope;
  10853. mBfIRBuilder->CreateBr(checkHandler.mHandlerBlock);
  10854. mBfIRBuilder->ClearDebugLocation_Last();
  10855. _FlushLifetimeEnds();
  10856. break;
  10857. }
  10858. }
  10859. if (scopeJumpBlock != NULL)
  10860. break;
  10861. }
  10862. bool hasWork = (checkScope->mSavedStack) || (checkScope->mDeferredCallEntries.mHead != NULL);
  10863. if (checkScope != scopeData) // Only emit a block for deferred lifetimes if we're going back beyond this entry
  10864. hasWork |= (!deferredLifetimeEnds.IsEmpty());
  10865. if (hasWork)
  10866. {
  10867. SetAndRestoreValue<BfScopeData*> prevScope(mCurMethodState->mCurScope, checkScope);
  10868. if (deferCloseNode != NULL)
  10869. {
  10870. UpdateSrcPos(deferCloseNode);
  10871. }
  10872. if (doneBlock)
  10873. {
  10874. bool crossingMixin = mCurMethodState->mCurScope->mMixinDepth != checkScope->mMixinDepth;
  10875. String blockName = "deferredCalls";
  10876. //blockName += StrFormat("_%d", mBfIRBuilder->mBlockCount);
  10877. BfDeferredHandler deferredHandler;
  10878. if ((!crossingMixin) && (deferredLifetimeEnds.IsEmpty()))
  10879. {
  10880. mBfIRBuilder->SaveDebugLocation();
  10881. mBfIRBuilder->ClearDebugLocation();
  10882. deferredHandler.mHandlerBlock = mBfIRBuilder->MaybeChainNewBlock(blockName);
  10883. mBfIRBuilder->RestoreDebugLocation();
  10884. }
  10885. else
  10886. {
  10887. // Definitely chain
  10888. deferredHandler.mHandlerBlock = mBfIRBuilder->CreateBlock(blockName);
  10889. mBfIRBuilder->CreateBr(deferredHandler.mHandlerBlock);
  10890. mBfIRBuilder->ClearDebugLocation_Last();
  10891. _FlushLifetimeEnds();
  10892. mBfIRBuilder->AddBlock(deferredHandler.mHandlerBlock);
  10893. mBfIRBuilder->SetInsertPoint(deferredHandler.mHandlerBlock);
  10894. }
  10895. deferredHandler.mDoneBlock = doneBlock;
  10896. if (!mBfIRBuilder->mIgnoreWrites)
  10897. checkScope->mDeferredHandlers.push_back(deferredHandler);
  10898. if (checkScope == &mCurMethodState->mHeadScope)
  10899. {
  10900. if (!mCurMethodState->mDIRetVal)
  10901. {
  10902. // 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
  10903. // be scoped to the physical method
  10904. /*if (deferCloseNode != NULL)
  10905. {
  10906. UpdateSrcPos(deferCloseNode);
  10907. }*/
  10908. CreateDIRetVal();
  10909. }
  10910. }
  10911. if (checkScope != mCurMethodState->mTailScope)
  10912. {
  10913. if (deferredHandler.mHandlerBlock.IsFake())
  10914. {
  10915. BF_ASSERT(mBfIRBuilder->mIgnoreWrites);
  10916. }
  10917. if (!mBfIRBuilder->mIgnoreWrites)
  10918. checkScope->mAtEndBlocks.push_back(deferredHandler.mHandlerBlock);
  10919. }
  10920. }
  10921. std::unordered_set<BfDeferredCallEntry*> handledSet;
  10922. BfDeferredCallEntry* deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  10923. while (deferredCallEntry != NULL)
  10924. {
  10925. BfDeferredCallEmitState deferredCallEmitState;
  10926. deferredCallEmitState.mCloseNode = deferCloseNode;
  10927. SetAndRestoreValue<BfDeferredCallEmitState*> prevDeferredCallEmitState(mCurMethodState->mDeferredCallEmitState, &deferredCallEmitState);
  10928. SetAndRestoreValue<bool> prevIgnoredWrites(mBfIRBuilder->mIgnoreWrites, deferredCallEntry->mIgnored);
  10929. if (deferCloseNode != NULL)
  10930. {
  10931. UpdateSrcPos(deferCloseNode);
  10932. }
  10933. if (wantsNop)
  10934. EmitEnsureInstructionAt();
  10935. wantsNop = false;
  10936. if (deferredCallEntry->mDeferredBlock != NULL)
  10937. {
  10938. auto itr = handledSet.insert(deferredCallEntry);
  10939. if (!itr.second)
  10940. {
  10941. // Already handled, can happen if we defer again within the block
  10942. deferredCallEntry = deferredCallEntry->mNext;
  10943. continue;
  10944. }
  10945. auto prevHead = checkScope->mDeferredCallEntries.mHead;
  10946. EmitDeferredCall(*deferredCallEntry);
  10947. if (prevHead != checkScope->mDeferredCallEntries.mHead)
  10948. {
  10949. // The list changed, start over and ignore anything we've already handled
  10950. deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  10951. }
  10952. else
  10953. deferredCallEntry = deferredCallEntry->mNext;
  10954. }
  10955. else
  10956. {
  10957. EmitDeferredCall(*deferredCallEntry);
  10958. deferredCallEntry = deferredCallEntry->mNext;
  10959. }
  10960. }
  10961. if (checkScope->mSavedStack)
  10962. {
  10963. checkScope->mSavedStackUses.Add(mBfIRBuilder->CreateStackRestore(checkScope->mSavedStack));
  10964. if (mCurMethodState->mDynStackRevIdx)
  10965. {
  10966. auto curValue = mBfIRBuilder->CreateLoad(mCurMethodState->mDynStackRevIdx);
  10967. auto newValue = mBfIRBuilder->CreateAdd(curValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  10968. mBfIRBuilder->CreateStore(newValue, mCurMethodState->mDynStackRevIdx);
  10969. }
  10970. }
  10971. }
  10972. if (!checkScope->mIsScopeHead)
  10973. {
  10974. // We manually emit function-level lifetime ends after the 'ret' in ProcessMethod
  10975. if (!IsTargetingBeefBackend())
  10976. {
  10977. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  10978. {
  10979. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  10980. }
  10981. }
  10982. else
  10983. {
  10984. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  10985. {
  10986. deferredLifetimeEnds.Add(lifetimeEnd);
  10987. }
  10988. }
  10989. }
  10990. if (checkScope == scopeData)
  10991. break;
  10992. checkScope = checkScope->mPrevScope;
  10993. }
  10994. if ((doneBlock) && (scopeJumpBlock == NULL))
  10995. {
  10996. mBfIRBuilder->CreateBr(doneBlock);
  10997. mBfIRBuilder->ClearDebugLocation_Last();
  10998. }
  10999. // Keeping CreateLifetimeEnds until the end messes up when we chain to old mDeferredHandlers that
  11000. // may have been created when other scope lifetimes were available
  11001. _FlushLifetimeEnds();
  11002. // Emit lifetimeEnds after the branch for Beef
  11003. /*if (IsTargetingBeefBackend())
  11004. {
  11005. bool needsEnsureInst = (!doneBlock) && (scopeJumpBlock == NULL);
  11006. BfScopeData* checkScope = mCurMethodState->mCurScope;
  11007. while (checkScope != NULL)
  11008. {
  11009. if (checkScope == scopeJumpBlock)
  11010. break;
  11011. if (!checkScope->mIsScopeHead)
  11012. {
  11013. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  11014. {
  11015. if (needsEnsureInst)
  11016. {
  11017. needsEnsureInst = false;
  11018. }
  11019. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  11020. }
  11021. }
  11022. if (checkScope == scopeData)
  11023. break;
  11024. checkScope = checkScope->mPrevScope;
  11025. }
  11026. }*/
  11027. }
  11028. void BfModule::MarkScopeLeft(BfScopeData* scopeData)
  11029. {
  11030. if (mCurMethodState->mDeferredLocalAssignData != NULL)
  11031. {
  11032. auto deferredLocalAssignData = mCurMethodState->mDeferredLocalAssignData;
  11033. while (deferredLocalAssignData != NULL)
  11034. {
  11035. if ((deferredLocalAssignData->mScopeData == NULL) || (deferredLocalAssignData->mScopeData->mScopeDepth < scopeData->mScopeDepth))
  11036. break;
  11037. if ((deferredLocalAssignData->mScopeData != NULL) && (deferredLocalAssignData->mScopeData->mScopeDepth == scopeData->mScopeDepth))
  11038. deferredLocalAssignData->mIsUnconditional = false;
  11039. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  11040. }
  11041. }
  11042. //for (int localIdx = scopeData->mLocalVarStart; localIdx < (int)mCurMethodState->mLocals.size(); localIdx++)
  11043. // We mark all unassigned variables as assigned now, for avoiding "may be unassigned" usage cases like:
  11044. // int b;
  11045. // if (cond) return;
  11046. // else b = 1;
  11047. // Use(b);
  11048. for (int localIdx = 0; localIdx < (int)mCurMethodState->mLocals.size(); localIdx++)
  11049. {
  11050. auto localDef = mCurMethodState->mLocals[localIdx];
  11051. if ((!localDef->mIsAssigned) && (!localDef->IsParam()))
  11052. mCurMethodState->LocalDefined(localDef);
  11053. }
  11054. }
  11055. void BfModule::CreateReturn(BfIRValue val)
  11056. {
  11057. if (mCurMethodInstance->mReturnType->IsComposite())
  11058. {
  11059. // Store to sret
  11060. BF_ASSERT(val);
  11061. mBfIRBuilder->CreateStore(val, mBfIRBuilder->GetArgument(0));
  11062. mBfIRBuilder->CreateRetVoid();
  11063. }
  11064. else
  11065. {
  11066. if (mCurMethodInstance->mReturnType->IsValuelessType())
  11067. {
  11068. mBfIRBuilder->CreateRetVoid();
  11069. }
  11070. else
  11071. {
  11072. BF_ASSERT(val);
  11073. mBfIRBuilder->CreateRet(val);
  11074. }
  11075. }
  11076. }
  11077. void BfModule::EmitReturn(BfIRValue val)
  11078. {
  11079. if (mCurMethodState->mIRExitBlock)
  11080. {
  11081. if (!mCurMethodInstance->mReturnType->IsValuelessType())
  11082. {
  11083. if (val) // We allow for val to be empty if we know we've already written the value to mRetVal
  11084. {
  11085. BfIRValue retVal = mCurMethodState->mRetVal.mValue;
  11086. if (!mCurMethodState->mRetVal)
  11087. retVal = mBfIRBuilder->CreateLoad(mCurMethodState->mRetValAddr);
  11088. mBfIRBuilder->CreateStore(val, retVal);
  11089. }
  11090. }
  11091. EmitDeferredScopeCalls(true, NULL, mCurMethodState->mIRExitBlock);
  11092. }
  11093. else
  11094. {
  11095. EmitDeferredScopeCalls(false, NULL);
  11096. if (mCurMethodInstance->mReturnType->IsValuelessType())
  11097. mBfIRBuilder->CreateRetVoid();
  11098. else
  11099. mBfIRBuilder->CreateRet(val);
  11100. }
  11101. mCurMethodState->SetHadReturn(true);
  11102. mCurMethodState->mLeftBlockUncond = true;
  11103. }
  11104. void BfModule::EmitDefaultReturn()
  11105. {
  11106. if (mCurMethodState->mInDeferredBlock)
  11107. return;
  11108. if (mCurMethodState->mIRExitBlock)
  11109. {
  11110. EmitDeferredScopeCalls(true, NULL, mCurMethodState->mIRExitBlock);
  11111. }
  11112. else
  11113. {
  11114. if (mCurMethodInstance->mReturnType->IsVoid())
  11115. mBfIRBuilder->CreateRetVoid();
  11116. else
  11117. mBfIRBuilder->CreateRet(GetDefaultValue(mCurMethodInstance->mReturnType));
  11118. }
  11119. mCurMethodState->SetHadReturn(true);
  11120. mCurMethodState->mLeftBlockUncond = true;
  11121. }
  11122. void BfModule::AssertErrorState()
  11123. {
  11124. if (mIgnoreErrors)
  11125. return;
  11126. if (mHadBuildError)
  11127. return;
  11128. if (mCurTypeInstance != NULL)
  11129. {
  11130. if (mCurTypeInstance->IsUnspecializedTypeVariation())
  11131. return;
  11132. }
  11133. if (mCurMethodInstance != NULL)
  11134. {
  11135. if (mCurMethodInstance->mIsUnspecializedVariation)
  11136. return;
  11137. }
  11138. // We want the module to be marked as failed even if it's just an error in the parser
  11139. if (mCurMethodInstance != NULL)
  11140. mCurMethodInstance->mHasFailed = true;
  11141. mHadBuildError = true;
  11142. // We check for either the parsing to have failed (possibly on a previous run), or for the current instance to have failed
  11143. if (mCurTypeInstance != NULL)
  11144. {
  11145. if (mCurTypeInstance->mTypeFailed)
  11146. return;
  11147. if (mCurTypeInstance->mTypeDef->mSource->mParsingFailed)
  11148. return;
  11149. }
  11150. if (mCurMethodInstance != NULL)
  11151. {
  11152. if ((mCurMethodInstance->mMethodDef->mDeclaringType != NULL) && (mCurMethodInstance->mMethodDef->mDeclaringType->mSource->mParsingFailed))
  11153. return;
  11154. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL) && (mCurMethodState->mMixinState->mMixinMethodInstance->mMethodDef->mDeclaringType->mSource->mParsingFailed))
  11155. return;
  11156. }
  11157. BF_ASSERT(mCompiler->mPassInstance->HasFailed());
  11158. }
  11159. void BfModule::AssertParseErrorState()
  11160. {
  11161. if (mCompiler->mRevision == 1)
  11162. AssertErrorState();
  11163. }
  11164. BfType* BfModule::GetDelegateReturnType(BfType* delegateType)
  11165. {
  11166. BF_ASSERT(delegateType->IsDelegate());
  11167. auto typeInst = delegateType->ToTypeInstance();
  11168. PopulateType(typeInst, BfPopulateType_DataAndMethods);
  11169. BfMethodInstance* invokeMethodInstance = GetRawMethodInstanceAtIdx(typeInst->ToTypeInstance(), 0, "Invoke");
  11170. return invokeMethodInstance->mReturnType;
  11171. }
  11172. BfMethodInstance* BfModule::GetDelegateInvokeMethod(BfTypeInstance* typeInstance)
  11173. {
  11174. return GetRawMethodInstanceAtIdx(typeInstance, 0, "Invoke");
  11175. }
  11176. void BfModule::CreateDelegateInvokeMethod()
  11177. {
  11178. // Clear out debug loc - otherwise we'll single step onto the delegate type declaration
  11179. //mBfIRBuilder->ClearDebugLocation();
  11180. SetIllegalSrcPos();
  11181. auto typeInstance = mCurTypeInstance;
  11182. auto memberFuncType = mBfIRBuilder->MapMethod(mCurMethodInstance);
  11183. SizedArray<BfIRType, 4> staticParamTypes;
  11184. SizedArray<BfIRValue, 4> staticFuncArgs;
  11185. SizedArray<BfIRValue, 4> memberFuncArgs;
  11186. auto multicastDelegateType = typeInstance->mBaseType;
  11187. if (multicastDelegateType->mFieldInstances.size() != 2)
  11188. {
  11189. AssertErrorState();
  11190. return;
  11191. }
  11192. auto multicastDelegate = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapType(multicastDelegateType));
  11193. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 2); // Load 'delegate.mTarget'
  11194. auto fieldVal = mBfIRBuilder->CreateLoad(fieldPtr);
  11195. BfExprEvaluator exprEvaluator(this);
  11196. SizedArray<BfIRType, 8> origParamTypes;
  11197. BfIRType origReturnType;
  11198. mCurMethodInstance->GetIRFunctionInfo(this, origReturnType, origParamTypes);
  11199. if (mCurMethodInstance->mReturnType->IsValueType())
  11200. mBfIRBuilder->PopulateType(mCurMethodInstance->mReturnType, BfIRPopulateType_Full);
  11201. int thisIdx = 0;
  11202. if (mCurMethodInstance->HasStructRet())
  11203. {
  11204. thisIdx = 1;
  11205. staticFuncArgs.push_back(mBfIRBuilder->GetArgument(0));
  11206. memberFuncArgs.push_back(mBfIRBuilder->GetArgument(0));
  11207. }
  11208. memberFuncArgs.push_back(BfIRValue()); // Push 'target'
  11209. mCurMethodInstance->GetIRFunctionInfo(this, origReturnType, staticParamTypes, true);
  11210. for (int i = 1; i < (int)mCurMethodState->mLocals.size(); i++)
  11211. {
  11212. BfTypedValue localVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[i], true);
  11213. exprEvaluator.PushArg(localVal, staticFuncArgs);
  11214. exprEvaluator.PushArg(localVal, memberFuncArgs);
  11215. }
  11216. auto staticFunc = mBfIRBuilder->CreateFunctionType(origReturnType, staticParamTypes, false);
  11217. auto staticFuncPtr = mBfIRBuilder->GetPointerTo(staticFunc);
  11218. auto staticFuncPtrPtr = mBfIRBuilder->GetPointerTo(staticFuncPtr);
  11219. auto trueBB = mBfIRBuilder->CreateBlock("if.then", true);
  11220. auto falseBB = mBfIRBuilder->CreateBlock("if.else");
  11221. auto doneBB = mBfIRBuilder->CreateBlock("done");
  11222. auto checkTargetNull = mBfIRBuilder->CreateIsNotNull(fieldVal);
  11223. mBfIRBuilder->CreateCondBr(checkTargetNull, trueBB, falseBB);
  11224. BfIRValue nonStaticResult;
  11225. BfIRValue staticResult;
  11226. auto callingConv = GetCallingConvention(mCurTypeInstance, mCurMethodInstance->mMethodDef);
  11227. /// Non-static invocation
  11228. {
  11229. auto memberFuncPtr = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapMethod(mCurMethodInstance));
  11230. auto memberFuncPtrPtr = mBfIRBuilder->GetPointerTo(memberFuncPtr);
  11231. mBfIRBuilder->SetInsertPoint(trueBB);
  11232. memberFuncArgs[thisIdx] = mBfIRBuilder->CreateBitCast(fieldVal, mBfIRBuilder->MapType(mCurTypeInstance));
  11233. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 1); // Load 'delegate.mFuncPtr'
  11234. auto funcPtrPtr = mBfIRBuilder->CreateBitCast(fieldPtr, memberFuncPtrPtr);
  11235. auto funcPtr = mBfIRBuilder->CreateLoad(funcPtrPtr);
  11236. nonStaticResult = mBfIRBuilder->CreateCall(funcPtr, memberFuncArgs);
  11237. if (callingConv != BfIRCallingConv_CDecl)
  11238. mBfIRBuilder->SetCallCallingConv(nonStaticResult, callingConv);
  11239. mCurMethodState->SetHadReturn(false);
  11240. mCurMethodState->mLeftBlockUncond = false;
  11241. mCurMethodState->mLeftBlockCond = false;
  11242. mBfIRBuilder->CreateBr(doneBB);
  11243. }
  11244. // Static invocation
  11245. {
  11246. mBfIRBuilder->AddBlock(falseBB);
  11247. mBfIRBuilder->SetInsertPoint(falseBB);
  11248. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 1); // Load 'delegate.mFuncPtr'
  11249. auto funcPtrPtr = mBfIRBuilder->CreateBitCast(fieldPtr, staticFuncPtrPtr);
  11250. auto funcPtr = mBfIRBuilder->CreateLoad(funcPtrPtr);
  11251. staticResult = mBfIRBuilder->CreateCall(funcPtr, staticFuncArgs);
  11252. if (callingConv == BfIRCallingConv_ThisCall)
  11253. callingConv = BfIRCallingConv_CDecl;
  11254. if (callingConv != BfIRCallingConv_CDecl)
  11255. mBfIRBuilder->SetCallCallingConv(staticResult, callingConv);
  11256. // if (!mSystem->IsCompatibleCallingConvention(BfCallingConvention_Unspecified, mCurMethodInstance->mMethodDef->mCallingConvention))
  11257. // {
  11258. // if (mCurMethodInstance->mMethodDef->mCallingConvention == BfCallingConvention_Stdcall)
  11259. //
  11260. // }
  11261. mCurMethodState->SetHadReturn(false);
  11262. mCurMethodState->mLeftBlockUncond = false;
  11263. mCurMethodState->mLeftBlockCond = false;
  11264. mBfIRBuilder->CreateBr(doneBB);
  11265. }
  11266. mBfIRBuilder->AddBlock(doneBB);
  11267. mBfIRBuilder->SetInsertPoint(doneBB);
  11268. if ((mCurMethodInstance->mReturnType->IsValuelessType()) || (mCurMethodInstance->HasStructRet()))
  11269. {
  11270. mBfIRBuilder->CreateRetVoid();
  11271. }
  11272. else
  11273. {
  11274. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapType(mCurMethodInstance->mReturnType), 2);
  11275. mBfIRBuilder->AddPhiIncoming(phi, nonStaticResult, trueBB);
  11276. mBfIRBuilder->AddPhiIncoming(phi, staticResult, falseBB);
  11277. mBfIRBuilder->CreateRet(phi);
  11278. }
  11279. }
  11280. // "Interested" here means every method for a normal compile, and just the method the cursor is on for autocompletion
  11281. bool BfModule::IsInterestedInMethod(BfTypeInstance* typeInstance, BfMethodDef* methodDef)
  11282. {
  11283. auto typeDef = typeInstance->mTypeDef;
  11284. auto methodDeclaration = methodDef->mMethodDeclaration;
  11285. if (!mCompiler->mIsResolveOnly)
  11286. return true;
  11287. if (typeInstance->IsGenericTypeInstance())
  11288. {
  11289. // We only really want to process the unspecialized type for autocompletion
  11290. if ((!typeInstance->IsUnspecializedType()) || (typeInstance->IsUnspecializedTypeVariation()))
  11291. return false;
  11292. }
  11293. BfAstNode* checkNode = methodDeclaration;
  11294. if (methodDeclaration == NULL)
  11295. checkNode = methodDef->mBody;
  11296. if ((mCompiler->mResolvePassData->mParser != NULL) && (typeDef->mTypeDeclaration->IsFromParser(mCompiler->mResolvePassData->mParser)))
  11297. {
  11298. if (mCompiler->mResolvePassData->mAutoComplete == NULL)
  11299. return true;
  11300. }
  11301. return false;
  11302. }
  11303. void BfModule::CalcAppendAlign(BfMethodInstance* methodInst)
  11304. {
  11305. methodInst->mAppendAllocAlign = 1;
  11306. }
  11307. BfTypedValue BfModule::TryConstCalcAppend(BfMethodInstance* methodInst, SizedArrayImpl<BfIRValue>& args)
  11308. {
  11309. BP_ZONE("BfModule::TryConstCalcAppend");
  11310. if (mCompiler->mIsResolveOnly)
  11311. return BfTypedValue();
  11312. // We want to regenerate all ctor calls when the method internals change
  11313. {
  11314. auto checkTypeInst = methodInst->GetOwner();
  11315. while (checkTypeInst->mTypeDef->mHasAppendCtor)
  11316. {
  11317. AddDependency(checkTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_InlinedCall);
  11318. checkTypeInst = GetBaseType(checkTypeInst);
  11319. }
  11320. }
  11321. if (!methodInst->mMayBeConst)
  11322. return BfTypedValue();
  11323. // Do we need to iterate in order to resolve mAppendAllocAlign?
  11324. bool isFirstRun = methodInst->mAppendAllocAlign < 0;
  11325. bool wasAllConst = true;
  11326. int argIdx = 0;
  11327. int paramIdx = 0;
  11328. while (true)
  11329. {
  11330. if (argIdx >= (int)args.size())
  11331. break;
  11332. auto paramType = methodInst->GetParamType(paramIdx);
  11333. PopulateType(paramType);
  11334. int argCount = 0;
  11335. if (!paramType->IsValuelessType())
  11336. {
  11337. if (methodInst->GetParamIsSplat(paramIdx))
  11338. argCount = paramType->GetSplatCount();
  11339. else
  11340. argCount = 1;
  11341. for (int argOfs = 0; argOfs < argCount; argOfs++)
  11342. {
  11343. auto arg = args[argIdx + argOfs];
  11344. if (!arg.IsConst())
  11345. {
  11346. wasAllConst = false;
  11347. if (!isFirstRun)
  11348. {
  11349. auto& param = methodInst->mParams[argIdx];
  11350. if (param.mReferencedInConstPass)
  11351. {
  11352. // If this param is required as part of the const calculation then
  11353. // we require that it be const...
  11354. return BfTypedValue();
  11355. }
  11356. }
  11357. }
  11358. }
  11359. }
  11360. paramIdx++;
  11361. argIdx += argCount;
  11362. }
  11363. auto methodDef = methodInst->mMethodDef;
  11364. auto methodDecl = methodDef->GetMethodDeclaration();
  11365. auto methodDeclBlock = BfNodeDynCast<BfBlock>(methodDecl->mBody);
  11366. if (methodDeclBlock == NULL)
  11367. return BfTypedValue();
  11368. BfTypedValue constValue;
  11369. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  11370. auto checkState = mCurMethodState->mConstResolveState;
  11371. while (checkState != NULL)
  11372. {
  11373. if (checkState->mMethodInstance == methodInst)
  11374. {
  11375. return BfTypedValue();
  11376. }
  11377. checkState = checkState->mPrevConstResolveState;
  11378. }
  11379. //auto accumValue = GetConstValue(0);
  11380. bool failed = false;
  11381. //
  11382. {
  11383. BfConstResolveState constResolveState;
  11384. constResolveState.mMethodInstance = methodInst;
  11385. constResolveState.mPrevConstResolveState = mCurMethodState->mConstResolveState;
  11386. SetAndRestoreValue<bool> ignoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  11387. BfMethodState methodState;
  11388. SetAndRestoreValue<BfTypeInstance*> prevTypeInst(mCurTypeInstance, methodInst->GetOwner());
  11389. SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, methodInst);
  11390. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  11391. methodState.mTempKind = BfMethodState::TempKind_NonStatic;
  11392. methodState.mConstResolveState = &constResolveState;
  11393. int argIdx = 0;
  11394. for (int paramIdx = 0; paramIdx < methodInst->GetParamCount(); paramIdx++)
  11395. {
  11396. if (methodInst->GetParamKind(paramIdx) == BfParamKind_AppendIdx)
  11397. continue;
  11398. auto paramType = methodInst->GetParamType(paramIdx);
  11399. // Fix this after we allow structs to be consts
  11400. //BF_ASSERT(!paramType->IsSplattable());
  11401. BfLocalVariable* localVar = new BfLocalVariable();
  11402. localVar->mName = methodInst->GetParamName(paramIdx);
  11403. localVar->mResolvedType = paramType;
  11404. localVar->mConstValue = args[argIdx];
  11405. localVar->mParamIdx = paramIdx;
  11406. AddLocalVariableDef(localVar);
  11407. argIdx++;
  11408. }
  11409. AppendAllocVisitor appendAllocVisitor;
  11410. appendAllocVisitor.mConstAccum = GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr));
  11411. appendAllocVisitor.mIsFirstConstPass = isFirstRun;
  11412. BfTypedValue baseCtorAppendValue = CallBaseCtorCalc(true);
  11413. if (baseCtorAppendValue)
  11414. {
  11415. if (baseCtorAppendValue.mValue.IsFake())
  11416. appendAllocVisitor.mFailed = true;
  11417. else
  11418. appendAllocVisitor.mConstAccum = baseCtorAppendValue;
  11419. }
  11420. appendAllocVisitor.mModule = this;
  11421. appendAllocVisitor.VisitChild(methodDecl->mBody);
  11422. if (!appendAllocVisitor.mFailed)
  11423. constValue = appendAllocVisitor.mConstAccum;
  11424. if (isFirstRun)
  11425. mCurMethodInstance->mEndingAppendAllocAlign = appendAllocVisitor.mCurAppendAlign;
  11426. if (isFirstRun)
  11427. {
  11428. for (int paramIdx = 0; paramIdx < methodInst->GetParamCount(); paramIdx++)
  11429. {
  11430. auto localVar = mCurMethodState->mLocals[paramIdx];
  11431. if (localVar->mReadFromId != -1)
  11432. {
  11433. auto& param = methodInst->mParams[paramIdx];
  11434. param.mReferencedInConstPass = true;
  11435. }
  11436. }
  11437. }
  11438. }
  11439. mBfIRBuilder->SetInsertPoint(prevBlock);
  11440. if (!constValue)
  11441. {
  11442. // If we did a 'force' then some params may not have been const -- only clear mMayBeConst if we had
  11443. // all-const args
  11444. if (wasAllConst)
  11445. {
  11446. methodInst->mMayBeConst = false;
  11447. }
  11448. }
  11449. return constValue;
  11450. }
  11451. BfTypedValue BfModule::CallBaseCtorCalc(bool constOnly)
  11452. {
  11453. // Any errors should only be shown in the actual CTOR call
  11454. SetAndRestoreValue<bool> prevIgnoreWrites(mIgnoreErrors, true);
  11455. auto methodDef = mCurMethodInstance->mMethodDef;
  11456. BF_ASSERT((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend));
  11457. auto ctorDeclaration = (BfConstructorDeclaration*)methodDef->mMethodDeclaration;
  11458. BfTypeInstance* targetType = NULL;
  11459. if (ctorDeclaration->mInitializer != NULL)
  11460. {
  11461. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorDeclaration->mInitializer->mTarget);
  11462. targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  11463. }
  11464. else
  11465. targetType = mCurTypeInstance->mBaseType;
  11466. if ((targetType == NULL) || (targetType == mContext->mBfObjectType))
  11467. return NULL;
  11468. auto targetRefNode = methodDef->GetRefNode();
  11469. BfType* targetThisType = targetType;
  11470. BfTypedValue target(mBfIRBuilder->GetFakeVal(), targetThisType);
  11471. BfExprEvaluator exprEvaluator(this);
  11472. BfResolvedArgs argValues;
  11473. if ((ctorDeclaration != NULL) && (ctorDeclaration->mInitializer != NULL))
  11474. {
  11475. argValues.Init(&ctorDeclaration->mInitializer->mArguments);
  11476. }
  11477. //
  11478. {
  11479. }
  11480. BfFunctionBindResult bindResult;
  11481. bindResult.mSkipThis = true;
  11482. bindResult.mWantsArgs = true;
  11483. {
  11484. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  11485. exprEvaluator.ResolveArgValues(argValues, BfResolveArgFlag_DeferParamEval);
  11486. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(exprEvaluator.mFunctionBindResult, &bindResult);
  11487. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, true);
  11488. }
  11489. if (bindResult.mMethodInstance == NULL)
  11490. {
  11491. AssertErrorState();
  11492. return BfTypedValue();
  11493. }
  11494. if (!bindResult.mMethodInstance->mMethodDef->mHasAppend)
  11495. {
  11496. return BfTypedValue();
  11497. }
  11498. BF_ASSERT(bindResult.mIRArgs[0].IsFake());
  11499. bindResult.mIRArgs.RemoveAt(0);
  11500. auto calcAppendMethodModule = GetMethodInstanceAtIdx(bindResult.mMethodInstance->GetOwner(), bindResult.mMethodInstance->mMethodDef->mIdx + 1, BF_METHODNAME_CALCAPPEND);
  11501. BfTypedValue appendSizeTypedValue = TryConstCalcAppend(calcAppendMethodModule.mMethodInstance, bindResult.mIRArgs);
  11502. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mAppendAllocAlign >= 0);
  11503. mCurMethodInstance->mAppendAllocAlign = BF_MAX((int)mCurMethodInstance->mAppendAllocAlign, calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  11504. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign > -1);
  11505. mCurMethodState->mCurAppendAlign = BF_MAX(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign, 0);
  11506. if (appendSizeTypedValue)
  11507. return appendSizeTypedValue;
  11508. if (constOnly)
  11509. return BfTypedValue(mBfIRBuilder->GetFakeVal(), GetPrimitiveType(BfTypeCode_IntPtr));
  11510. bool needsRecalc = false;
  11511. for (auto irArg : bindResult.mIRArgs)
  11512. {
  11513. if (irArg.IsFake())
  11514. needsRecalc = true;
  11515. }
  11516. auto calcAppendArgs = bindResult.mIRArgs;
  11517. if (needsRecalc)
  11518. {
  11519. // Do it again, but without mIgnoreWrites set
  11520. BfResolvedArgs argValues;
  11521. argValues.Init(&ctorDeclaration->mInitializer->mArguments);
  11522. exprEvaluator.ResolveArgValues(argValues, BfResolveArgFlag_DeferParamEval);
  11523. BfFunctionBindResult bindResult;
  11524. bindResult.mSkipThis = true;
  11525. bindResult.mWantsArgs = true;
  11526. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(exprEvaluator.mFunctionBindResult, &bindResult);
  11527. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, true);
  11528. BF_ASSERT(bindResult.mIRArgs[0].IsFake());
  11529. bindResult.mIRArgs.RemoveAt(0);
  11530. calcAppendArgs = bindResult.mIRArgs;
  11531. }
  11532. BF_ASSERT(calcAppendMethodModule.mFunc);
  11533. appendSizeTypedValue = exprEvaluator.CreateCall(calcAppendMethodModule.mMethodInstance, calcAppendMethodModule.mFunc, false, calcAppendArgs);
  11534. BF_ASSERT(appendSizeTypedValue.mType == GetPrimitiveType(BfTypeCode_IntPtr));
  11535. return appendSizeTypedValue;
  11536. }
  11537. // This method never throws errors - it relies on the proper ctor actually throwing the errors
  11538. void BfModule::EmitCtorCalcAppend()
  11539. {
  11540. if (mCompiler->mIsResolveOnly)
  11541. return;
  11542. auto methodDef = mCurMethodInstance->mMethodDef;
  11543. auto methodDecl = methodDef->GetMethodDeclaration();
  11544. Array<BfAstNode*> deferredNodeList;
  11545. auto methodDeclBlock = BfNodeDynCast<BfBlock>(methodDecl->mBody);
  11546. if (methodDeclBlock == NULL)
  11547. return;
  11548. AppendAllocVisitor appendAllocVisitor;
  11549. auto baseCalcAppend = CallBaseCtorCalc(false);
  11550. if (baseCalcAppend)
  11551. {
  11552. mBfIRBuilder->CreateStore(baseCalcAppend.mValue, mCurMethodState->mRetVal.mValue);
  11553. }
  11554. appendAllocVisitor.mModule = this;
  11555. appendAllocVisitor.VisitChild(methodDecl->mBody);
  11556. }
  11557. void BfModule::CreateStaticCtor()
  11558. {
  11559. auto typeDef = mCurTypeInstance->mTypeDef;
  11560. auto methodDef = mCurMethodInstance->mMethodDef;
  11561. BfIRBlock exitBB;
  11562. if ((HasCompiledOutput()) && (!mCurMethodInstance->mIsUnspecialized) && (mCurMethodInstance->mChainType != BfMethodChainType_ChainMember))
  11563. {
  11564. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  11565. auto didStaticInitVarAddr = mBfIRBuilder->CreateGlobalVariable(
  11566. mBfIRBuilder->MapType(boolType),
  11567. false,
  11568. BfIRLinkageType_Internal,
  11569. GetDefaultValue(boolType),
  11570. "didStaticInit");
  11571. auto initBB = mBfIRBuilder->CreateBlock("init", true);
  11572. mCurMethodState->mIRExitBlock = mBfIRBuilder->CreateBlock("exit", true);
  11573. auto didStaticInitVar = mBfIRBuilder->CreateLoad(didStaticInitVarAddr);
  11574. mBfIRBuilder->CreateCondBr(didStaticInitVar, mCurMethodState->mIRExitBlock, initBB);
  11575. mBfIRBuilder->SetInsertPoint(initBB);
  11576. mBfIRBuilder->CreateStore(GetConstValue(1, boolType), didStaticInitVarAddr);
  11577. }
  11578. // Do DLL imports
  11579. if (!mDllImportEntries.empty())
  11580. {
  11581. auto internalType = ResolveTypeDef(mCompiler->mInternalTypeDef);
  11582. PopulateType(internalType);
  11583. auto getSharedProcAddressInstance = GetMethodByName(internalType->ToTypeInstance(), "GetSharedProcAddress");
  11584. if (!getSharedProcAddressInstance)
  11585. {
  11586. if (!mCompiler->mPassInstance->HasFailed())
  11587. Fail("Internal error: System.Internal doesn't contain LoadSharedLibrary method");
  11588. }
  11589. }
  11590. // Fill in initializer values
  11591. if ((!mCompiler->mIsResolveOnly) || (mCompiler->mResolvePassData->mAutoComplete == NULL))
  11592. {
  11593. for (auto fieldDef : typeDef->mFields)
  11594. {
  11595. if ((!fieldDef->mIsConst) && (fieldDef->mIsStatic) && (fieldDef->mInitializer != NULL))
  11596. {
  11597. // For extensions, only handle these fields in the appropriate extension
  11598. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  11599. continue;
  11600. UpdateSrcPos(fieldDef->mInitializer);
  11601. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  11602. if (!fieldInst->mFieldIncluded)
  11603. continue;
  11604. if (fieldInst->mResolvedType->IsVar())
  11605. {
  11606. continue;
  11607. }
  11608. auto assignValue = GetFieldInitializerValue(fieldInst);
  11609. if (assignValue)
  11610. {
  11611. assignValue = LoadValue(assignValue);
  11612. if (!assignValue.mType->IsValuelessType())
  11613. {
  11614. auto staticVarRef = ReferenceStaticField(fieldInst).mValue;
  11615. mBfIRBuilder->CreateStore(assignValue.mValue, staticVarRef);
  11616. }
  11617. }
  11618. }
  11619. }
  11620. }
  11621. else
  11622. {
  11623. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  11624. {
  11625. if (tempTypeDef->mFullName == typeDef->mFullName)
  11626. {
  11627. for (auto fieldDef : tempTypeDef->mFields)
  11628. {
  11629. if ((fieldDef->mIsStatic) && (!fieldDef->mIsConst))
  11630. {
  11631. if (fieldDef->mInitializer != NULL)
  11632. {
  11633. if (mCompiler->mResolvePassData->mSourceClassifier != NULL)
  11634. {
  11635. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(fieldDef->mInitializer, BfSourceElementType_Normal);
  11636. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(fieldDef->mInitializer);
  11637. }
  11638. BfType* wantType = NULL;
  11639. if ((!BfNodeIsA<BfVarTypeReference>(fieldDef->mTypeRef)) && (!BfNodeIsA<BfLetTypeReference>(fieldDef->mTypeRef)))
  11640. {
  11641. wantType = ResolveTypeRef(fieldDef->mTypeRef);
  11642. }
  11643. CreateValueFromExpression(fieldDef->mInitializer, wantType, BfEvalExprFlags_FieldInitializer);
  11644. }
  11645. }
  11646. }
  11647. }
  11648. }
  11649. }
  11650. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  11651. CallChainedMethods(mCurMethodInstance, false);
  11652. }
  11653. void BfModule::EmitDtorBody()
  11654. {
  11655. if (mCurTypeInstance->IsClosure())
  11656. {
  11657. BfFieldInstance* fieldInstance = &mCurTypeInstance->mFieldInstances.back();
  11658. BF_ASSERT(fieldInstance->GetFieldDef()->mName == "__dtorThunk");
  11659. auto thisVal = GetThis();
  11660. auto dtorThunkPtr = mBfIRBuilder->CreateInBoundsGEP(thisVal.mValue, 0, fieldInstance->mDataIdx);
  11661. auto dtorThunk = mBfIRBuilder->CreateLoad(dtorThunkPtr);
  11662. auto funcPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapMethod(mCurMethodInstance));
  11663. auto dtorPtr = mBfIRBuilder->CreateBitCast(dtorThunk, funcPtrType);
  11664. SizedArray<BfIRValue, 1> args;
  11665. args.push_back(thisVal.mValue);
  11666. auto result = mBfIRBuilder->CreateCall(dtorPtr, args);
  11667. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_CDecl);
  11668. // Fall through to Object::~this call
  11669. auto dtorFunc = GetMethodByName(mContext->mBfObjectType, "~this");
  11670. auto basePtr = mBfIRBuilder->CreateBitCast(thisVal.mValue, mBfIRBuilder->MapTypeInstPtr(mContext->mBfObjectType));
  11671. SizedArray<BfIRValue, 1> vals = { basePtr };
  11672. result = mBfIRBuilder->CreateCall(dtorFunc.mFunc, vals);
  11673. mBfIRBuilder->SetCallCallingConv(result, GetCallingConvention(dtorFunc.mMethodInstance));
  11674. mBfIRBuilder->SetTailCall(result);
  11675. return;
  11676. }
  11677. auto typeDef = mCurTypeInstance->mTypeDef;
  11678. auto methodDef = mCurMethodInstance->mMethodDef;
  11679. auto methodDeclaration = methodDef->GetMethodDeclaration();
  11680. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  11681. CallChainedMethods(mCurMethodInstance, true);
  11682. if (auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody))
  11683. {
  11684. VisitCodeBlock(bodyBlock);
  11685. if (bodyBlock->mCloseBrace != NULL)
  11686. {
  11687. UpdateSrcPos(bodyBlock->mCloseBrace);
  11688. }
  11689. }
  11690. else
  11691. {
  11692. if (methodDeclaration != NULL)
  11693. UpdateSrcPos(methodDeclaration);
  11694. else if (typeDef->mTypeDeclaration != NULL)
  11695. UpdateSrcPos(typeDef->mTypeDeclaration);
  11696. if ((methodDeclaration != NULL) && (methodDeclaration->mFatArrowToken != NULL))
  11697. {
  11698. Fail("Destructors cannot have expression bodies", methodDeclaration->mFatArrowToken);
  11699. }
  11700. }
  11701. if ((!mCompiler->mIsResolveOnly) || (mCompiler->mResolvePassData->mAutoComplete == NULL))
  11702. {
  11703. for (int fieldIdx = (int)mCurTypeInstance->mFieldInstances.size() - 1; fieldIdx >= 0; fieldIdx--)
  11704. {
  11705. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldIdx];
  11706. auto fieldDef = fieldInst->GetFieldDef();
  11707. if ((fieldDef != NULL) && (fieldDef->mIsStatic == methodDef->mIsStatic) && (fieldDef->mFieldDeclaration != NULL) && (fieldDef->mFieldDeclaration->mFieldDtor != NULL))
  11708. {
  11709. if ((!methodDef->mIsStatic) && (mCurTypeInstance->IsValueType()))
  11710. {
  11711. Fail("Structs cannot have field destructors", fieldDef->mFieldDeclaration->mFieldDtor->mTildeToken);
  11712. }
  11713. SetAndRestoreValue<BfFilePosition> prevFilePos(mCurFilePosition);
  11714. auto fieldDtor = fieldDef->mFieldDeclaration->mFieldDtor;
  11715. if ((fieldDef->mIsStatic) != (methodDef->mIsStatic))
  11716. continue;
  11717. UpdateSrcPos(fieldDtor);
  11718. BfScopeData scopeData;
  11719. mCurMethodState->AddScope(&scopeData);
  11720. NewScopeState();
  11721. UpdateSrcPos(fieldDtor);
  11722. bool hasDbgInfo = (!fieldDef->mIsConst);
  11723. if (hasDbgInfo)
  11724. {
  11725. mBfIRBuilder->SaveDebugLocation();
  11726. mBfIRBuilder->ClearDebugLocation();
  11727. }
  11728. BfIRValue value;
  11729. if (fieldDef->mIsStatic)
  11730. {
  11731. value = ReferenceStaticField(fieldInst).mValue;
  11732. }
  11733. else
  11734. {
  11735. if (!mCurTypeInstance->IsValueType())
  11736. {
  11737. auto thisValue = GetThis();
  11738. value = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInst->mDataIdx);
  11739. }
  11740. else
  11741. {
  11742. AssertErrorState();
  11743. value = mBfIRBuilder->CreateConstNull(mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(fieldInst->mResolvedType)));
  11744. }
  11745. }
  11746. BfIRValue staticVal;
  11747. if (hasDbgInfo)
  11748. {
  11749. BfIRValue dbgShowValue = value;
  11750. BfLocalVariable* localDef = new BfLocalVariable();
  11751. localDef->mName = "_";
  11752. localDef->mResolvedType = fieldInst->mResolvedType;
  11753. localDef->mAddr = value;
  11754. if ((mBfIRBuilder->DbgHasInfo()) && (!IsTargetingBeefBackend()))
  11755. {
  11756. // Create another pointer indirection, a ref to the gep
  11757. auto refFieldType = CreateRefType(fieldInst->mResolvedType);
  11758. auto allocaInst = CreateAlloca(refFieldType);
  11759. auto storeResult = mBfIRBuilder->CreateStore(value, allocaInst);
  11760. localDef->mResolvedType = refFieldType;
  11761. localDef->mAddr = allocaInst;
  11762. }
  11763. mBfIRBuilder->RestoreDebugLocation();
  11764. auto defLocalVar = AddLocalVariableDef(localDef, true);
  11765. // Put back so we actually modify the correct value*/
  11766. defLocalVar->mResolvedType = fieldInst->mResolvedType;
  11767. defLocalVar->mAddr = value;
  11768. }
  11769. while (fieldDtor != NULL)
  11770. {
  11771. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  11772. {
  11773. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(fieldDtor, BfSourceElementType_Normal);
  11774. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(fieldDtor);
  11775. }
  11776. UpdateSrcPos(fieldDtor);
  11777. VisitEmbeddedStatement(fieldDtor->mBody);
  11778. fieldDtor = fieldDtor->mNextFieldDtor;
  11779. }
  11780. RestoreScopeState();
  11781. }
  11782. }
  11783. if (!methodDef->mIsStatic)
  11784. {
  11785. auto checkBaseType = mCurTypeInstance->mBaseType;
  11786. while (checkBaseType != NULL)
  11787. {
  11788. if (auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody))
  11789. {
  11790. if (bodyBlock->mCloseBrace != NULL)
  11791. UpdateSrcPos(bodyBlock->mCloseBrace);
  11792. }
  11793. else
  11794. {
  11795. UpdateSrcPos(typeDef->mTypeDeclaration->mNameNode);
  11796. }
  11797. if (checkBaseType->mTypeDef->mDtorDef != NULL)
  11798. {
  11799. auto dtorMethodInstance = GetMethodInstance(checkBaseType, checkBaseType->mTypeDef->mDtorDef, BfTypeVector());
  11800. if (mCompiler->IsSkippingExtraResolveChecks())
  11801. {
  11802. // Nothing
  11803. }
  11804. else if (dtorMethodInstance.mMethodInstance->GetParamCount() == 0)
  11805. {
  11806. if ((!mCompiler->IsSkippingExtraResolveChecks()) && (!checkBaseType->IsUnspecializedType()))
  11807. {
  11808. auto basePtr = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapTypeInstPtr(checkBaseType));
  11809. SizedArray<BfIRValue, 1> vals = { basePtr };
  11810. auto callInst = mBfIRBuilder->CreateCall(dtorMethodInstance.mFunc, vals);
  11811. mBfIRBuilder->SetCallCallingConv(callInst, GetCallingConvention(dtorMethodInstance.mMethodInstance));
  11812. }
  11813. }
  11814. else
  11815. {
  11816. // Invalid base dtor declaration
  11817. AssertErrorState();
  11818. }
  11819. break;
  11820. }
  11821. checkBaseType = checkBaseType->mBaseType;
  11822. }
  11823. }
  11824. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  11825. }
  11826. else
  11827. {
  11828. // The reason we can't just do the 'normal' path for this is that the BfTypeInstance here is NOT the
  11829. // autocomplete type instance, so FieldInstance initializer values contain expressions from the full
  11830. // resolve pass, NOT the autocomplete expression
  11831. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  11832. {
  11833. if (tempTypeDef->mFullName == typeDef->mFullName)
  11834. {
  11835. for (auto fieldDef : tempTypeDef->mFields)
  11836. {
  11837. if ((fieldDef->mIsStatic == methodDef->mIsStatic) && (fieldDef->mFieldDeclaration != NULL) &&
  11838. (fieldDef->mFieldDeclaration->mFieldDtor != NULL) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  11839. {
  11840. BfType* fieldType = NULL;
  11841. for (int curFieldIdx = 0; curFieldIdx < (int)mCurTypeInstance->mFieldInstances.size(); curFieldIdx++)
  11842. {
  11843. auto curFieldInstance = &mCurTypeInstance->mFieldInstances[curFieldIdx];
  11844. auto curFieldDef = curFieldInstance->GetFieldDef();
  11845. if ((curFieldDef != NULL) && (fieldDef->mName == curFieldDef->mName))
  11846. fieldType = curFieldInstance->GetResolvedType();
  11847. }
  11848. auto fieldDtor = fieldDef->mFieldDeclaration->mFieldDtor;
  11849. BfScopeData scopeData;
  11850. mCurMethodState->AddScope(&scopeData);
  11851. NewScopeState();
  11852. // This is just for autocomplete, it doesn't matter that mAddr is incorrect
  11853. if (fieldType != NULL)
  11854. {
  11855. BfLocalVariable* localDef = new BfLocalVariable();
  11856. localDef->mName = "_";
  11857. localDef->mResolvedType = fieldType;
  11858. localDef->mAddr = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(fieldType));
  11859. localDef->mIsAssigned = true;
  11860. AddLocalVariableDef(localDef);
  11861. }
  11862. while (fieldDtor != NULL)
  11863. {
  11864. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(fieldDtor, BfSourceElementType_Normal);
  11865. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(fieldDtor);
  11866. UpdateSrcPos(fieldDtor);
  11867. VisitEmbeddedStatement(fieldDtor->mBody);
  11868. fieldDtor = fieldDtor->mNextFieldDtor;
  11869. }
  11870. RestoreScopeState();
  11871. }
  11872. }
  11873. }
  11874. }
  11875. }
  11876. }
  11877. BfIRValue BfModule::CreateDllImportGlobalVar(BfMethodInstance* methodInstance, bool define)
  11878. {
  11879. auto typeInstance = methodInstance->GetOwner();
  11880. bool foundDllImportAttr = false;
  11881. BfCallingConvention callingConvention = methodInstance->mMethodDef->mCallingConvention;
  11882. for (auto customAttr : methodInstance->GetCustomAttributes()->mAttributes)
  11883. {
  11884. if (customAttr.mType->mTypeDef->mFullName.ToString() == "System.ImportAttribute")
  11885. {
  11886. foundDllImportAttr = true;
  11887. }
  11888. }
  11889. if (!foundDllImportAttr)
  11890. {
  11891. AssertErrorState();
  11892. return BfIRValue();
  11893. }
  11894. String name = "bf_hs_preserve@";
  11895. BfMangler::Mangle(name, mCompiler->GetMangleKind(), methodInstance);
  11896. name += "__imp";
  11897. BfIRType returnType;
  11898. SizedArray<BfIRType, 8> paramTypes;
  11899. methodInstance->GetIRFunctionInfo(this, returnType, paramTypes);
  11900. BfIRFunctionType externFunctionType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes, false);
  11901. auto ptrType = mBfIRBuilder->GetPointerTo(externFunctionType);
  11902. BfIRValue initVal;
  11903. if (define)
  11904. {
  11905. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  11906. initVal = mBfIRBuilder->CreateConstNull(ptrType);
  11907. }
  11908. auto globalVar = mBfIRBuilder->CreateGlobalVariable(ptrType, false, BfIRLinkageType_External, initVal, name);
  11909. if ((define) && (mBfIRBuilder->DbgHasInfo()))
  11910. {
  11911. auto voidType = GetPrimitiveType(BfTypeCode_None);
  11912. auto ptrType = CreatePointerType(voidType);
  11913. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, name, name, BfIRMDNode(), 0, mBfIRBuilder->DbgGetType(ptrType), false, globalVar);
  11914. }
  11915. return globalVar;
  11916. }
  11917. void BfModule::CreateDllImportMethod()
  11918. {
  11919. if (mBfIRBuilder->mIgnoreWrites)
  11920. return;
  11921. auto globalVar = mFuncReferences[mCurMethodInstance];
  11922. if (!globalVar)
  11923. return;
  11924. bool allowTailCall = true;
  11925. mBfIRBuilder->ClearDebugLocation();
  11926. bool isHotCompile = mCompiler->IsHotCompile();
  11927. // If we are hot swapping, we need to have this stub because we may need to call the LoadSharedLibraries on demand
  11928. if (isHotCompile)
  11929. {
  11930. auto loadSharedLibsFunc = GetBuiltInFunc(BfBuiltInFuncType_LoadSharedLibraries);
  11931. mBfIRBuilder->CreateCall(loadSharedLibsFunc, SizedArray<BfIRValue, 0>());
  11932. }
  11933. auto callingConvention = GetCallingConvention(mCurTypeInstance, mCurMethodInstance->mMethodDef);
  11934. BfIRType returnType;
  11935. SizedArray<BfIRType, 8> paramTypes;
  11936. mCurMethodInstance->GetIRFunctionInfo(this, returnType, paramTypes);
  11937. SizedArray<BfIRValue, 8> args;
  11938. for (int i = 0; i < (int)paramTypes.size(); i++)
  11939. args.push_back(mBfIRBuilder->GetArgument(i));
  11940. BfIRFunctionType externFunctionType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes, false);
  11941. if (isHotCompile)
  11942. {
  11943. BfIRValue funcVal = mBfIRBuilder->CreateLoad(globalVar);
  11944. auto result = mBfIRBuilder->CreateCall(funcVal, args);
  11945. if (callingConvention == BfIRCallingConv_StdCall)
  11946. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_StdCall);
  11947. else
  11948. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_CDecl);
  11949. if (allowTailCall)
  11950. mBfIRBuilder->SetTailCall(result);
  11951. CreateReturn(result);
  11952. mCurMethodState->mHadReturn = true;
  11953. }
  11954. if (HasCompiledOutput())
  11955. {
  11956. BfDllImportEntry dllImportEntry;
  11957. dllImportEntry.mFuncVar = globalVar;
  11958. dllImportEntry.mMethodInstance = mCurMethodInstance;
  11959. mDllImportEntries.push_back(dllImportEntry);
  11960. }
  11961. }
  11962. BfIRCallingConv BfModule::GetCallingConvention(BfTypeInstance* typeInst, BfMethodDef* methodDef)
  11963. {
  11964. if ((mCompiler->mOptions.mMachineType != BfMachineType_x86) || (mCompiler->mOptions.mPlatformType != BfPlatformType_Windows))
  11965. return BfIRCallingConv_CDecl;
  11966. if (methodDef->mCallingConvention == BfCallingConvention_Stdcall)
  11967. return BfIRCallingConv_StdCall;
  11968. if ((!methodDef->mIsStatic) && (!typeInst->IsValuelessType()) &&
  11969. ((!typeInst->IsSplattable()) || (methodDef->HasNoThisSplat())))
  11970. return BfIRCallingConv_ThisCall;
  11971. return BfIRCallingConv_CDecl;
  11972. }
  11973. BfIRCallingConv BfModule::GetCallingConvention(BfMethodInstance* methodInstance)
  11974. {
  11975. return GetCallingConvention(methodInstance->GetOwner(), methodInstance->mMethodDef);
  11976. }
  11977. void BfModule::SetupIRMethod(BfMethodInstance* methodInstance, BfIRFunction func, bool isInlined)
  11978. {
  11979. BfMethodDef* methodDef = NULL;
  11980. if (methodInstance != NULL)
  11981. methodDef = methodInstance->mMethodDef;
  11982. if (!func)
  11983. return;
  11984. if (mCompiler->mOptions.mNoFramePointerElim)
  11985. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_NoFramePointerElim);
  11986. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_NoUnwind);
  11987. if (mSystem->mPtrSize == 8) // We need unwind info for debugging
  11988. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_UWTable);
  11989. if (methodInstance == NULL)
  11990. return;
  11991. if (methodDef->mImportKind == BfImportKind_Export)
  11992. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_DllExport);
  11993. if (methodDef->mNoReturn)
  11994. mBfIRBuilder->Func_AddAttribute(func, -1, BfIRAttribute_NoReturn);
  11995. auto callingConv = GetCallingConvention(methodInstance->GetOwner(), methodDef);
  11996. if (callingConv != BfIRCallingConv_CDecl)
  11997. mBfIRBuilder->SetFuncCallingConv(func, callingConv);
  11998. if (isInlined)
  11999. {
  12000. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_AlwaysInline);
  12001. }
  12002. int argIdx = 0;
  12003. int paramIdx = 0;
  12004. if (methodInstance->HasThis())
  12005. {
  12006. paramIdx = -1;
  12007. }
  12008. int argCount = methodInstance->GetIRFunctionParamCount(this);
  12009. if (methodInstance->HasStructRet())
  12010. {
  12011. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_NoAlias);
  12012. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_StructRet);
  12013. argIdx++;
  12014. }
  12015. while (argIdx < argCount)
  12016. {
  12017. while ((paramIdx != -1) && (methodInstance->IsParamSkipped(paramIdx)))
  12018. paramIdx++;
  12019. BfType* resolvedTypeRef = NULL;
  12020. String paramName;
  12021. bool isSplattable = false;
  12022. bool isThis = paramIdx == -1;
  12023. if (isThis)
  12024. {
  12025. paramName = "this";
  12026. if (methodInstance->mIsClosure)
  12027. resolvedTypeRef = mCurMethodState->mClosureState->mClosureType;
  12028. else
  12029. resolvedTypeRef = methodInstance->GetOwner();
  12030. isSplattable = (resolvedTypeRef->IsSplattable()) && (!methodDef->HasNoThisSplat());
  12031. }
  12032. else if (!methodDef->mNoSplat)
  12033. {
  12034. paramName = methodInstance->GetParamName(paramIdx);
  12035. resolvedTypeRef = methodInstance->GetParamType(paramIdx);
  12036. if (resolvedTypeRef->IsMethodRef())
  12037. isSplattable = true;
  12038. else if (resolvedTypeRef->IsSplattable())
  12039. {
  12040. if (resolvedTypeRef->GetSplatCount() + argIdx <= mCompiler->mOptions.mMaxSplatRegs)
  12041. isSplattable = true;
  12042. }
  12043. }
  12044. //
  12045. {
  12046. auto loweredTypeCode = resolvedTypeRef->GetLoweredType();
  12047. if (loweredTypeCode != BfTypeCode_None)
  12048. resolvedTypeRef = GetPrimitiveType(loweredTypeCode);
  12049. }
  12050. auto _SetupParam = [&](const StringImpl& paramName, BfType* resolvedTypeRef)
  12051. {
  12052. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, paramName);
  12053. int addDeref = -1;
  12054. if (resolvedTypeRef->IsRef())
  12055. {
  12056. auto refType = (BfRefType*)resolvedTypeRef;
  12057. auto elementType = refType->mElementType;
  12058. PopulateType(elementType, BfPopulateType_Data);
  12059. addDeref = elementType->mSize;
  12060. if ((addDeref <= 0) && (!elementType->IsValuelessType()))
  12061. AssertErrorState();
  12062. }
  12063. if ((resolvedTypeRef->IsComposite()) && (!resolvedTypeRef->IsTypedPrimitive()))
  12064. {
  12065. if (mCompiler->mOptions.mAllowStructByVal)
  12066. {
  12067. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_ByVal);
  12068. }
  12069. else
  12070. {
  12071. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_NoCapture);
  12072. PopulateType(resolvedTypeRef, BfPopulateType_Data);
  12073. addDeref = resolvedTypeRef->mSize;
  12074. }
  12075. }
  12076. else if (resolvedTypeRef->IsPrimitiveType())
  12077. {
  12078. auto primType = (BfPrimitiveType*)resolvedTypeRef;
  12079. if (primType->mTypeDef->mTypeCode == BfTypeCode_Boolean)
  12080. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_ZExt);
  12081. }
  12082. if (addDeref >= 0)
  12083. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_Dereferencable, addDeref);
  12084. argIdx++;
  12085. };
  12086. if (isSplattable)
  12087. {
  12088. std::function<void(BfType*, const StringImpl&)> checkTypeLambda = [&](BfType* checkType, const StringImpl& curName)
  12089. {
  12090. if (checkType->IsStruct())
  12091. {
  12092. auto checkTypeInstance = checkType->ToTypeInstance();
  12093. if (checkTypeInstance->mBaseType != NULL)
  12094. checkTypeLambda(checkTypeInstance->mBaseType, curName);
  12095. if (checkTypeInstance->mIsUnion)
  12096. {
  12097. BfType* unionInnerType = checkTypeInstance->GetUnionInnerType();
  12098. checkTypeLambda(unionInnerType, curName + "_data");
  12099. }
  12100. else
  12101. {
  12102. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  12103. {
  12104. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  12105. auto fieldDef = fieldInstance->GetFieldDef();
  12106. if (fieldInstance->mDataIdx >= 0)
  12107. {
  12108. checkTypeLambda(fieldInstance->GetResolvedType(), curName + "_" + fieldInstance->GetFieldDef()->mName);
  12109. }
  12110. }
  12111. }
  12112. if (checkTypeInstance->IsEnum())
  12113. {
  12114. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, curName + "_dscr");
  12115. argIdx++;
  12116. }
  12117. }
  12118. else if (checkType->IsMethodRef())
  12119. {
  12120. auto methodRefType = (BfMethodRefType*)checkType;
  12121. BfMethodInstance* methodRefMethodInst = methodRefType->mMethodRef;
  12122. for (int dataIdx = 0; dataIdx < (int)methodRefType->GetCaptureDataCount(); dataIdx++)
  12123. {
  12124. int methodRefParamIdx = methodRefType->GetParamIdxFromDataIdx(dataIdx);
  12125. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  12126. {
  12127. checkTypeLambda(methodRefType->GetCaptureType(dataIdx), curName + "_" + methodRefMethodInst->GetParamName(methodRefParamIdx));
  12128. }
  12129. else
  12130. {
  12131. _SetupParam(curName + "_" + methodRefMethodInst->GetParamName(methodRefParamIdx), methodRefType->GetCaptureType(dataIdx));
  12132. }
  12133. }
  12134. }
  12135. else if (!checkType->IsValuelessType())
  12136. {
  12137. _SetupParam(curName, checkType);
  12138. }
  12139. };
  12140. checkTypeLambda(resolvedTypeRef, paramName);
  12141. paramIdx++;
  12142. continue;
  12143. }
  12144. _SetupParam(paramName, resolvedTypeRef);
  12145. //argIdx++;
  12146. paramIdx++;
  12147. }
  12148. }
  12149. void BfModule::EmitCtorBody(bool& skipBody)
  12150. {
  12151. auto methodInstance = mCurMethodInstance;
  12152. auto methodDef = methodInstance->mMethodDef;
  12153. auto methodDeclaration = methodDef->mMethodDeclaration;
  12154. auto ctorDeclaration = (BfConstructorDeclaration*)methodDef->mMethodDeclaration;
  12155. auto typeDef = mCurTypeInstance->mTypeDef;
  12156. // Prologue
  12157. mBfIRBuilder->ClearDebugLocation();
  12158. bool hadThisInitializer = false;
  12159. if ((ctorDeclaration != NULL) && (ctorDeclaration->mInitializer != NULL))
  12160. {
  12161. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorDeclaration->mInitializer->mTarget);
  12162. auto targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  12163. if (targetToken->GetToken() == BfToken_This)
  12164. {
  12165. hadThisInitializer = true;
  12166. // Since we call a 'this', it's that other ctor's responsibility to fully assign the fields
  12167. mCurMethodState->LocalDefined(GetThisVariable());
  12168. }
  12169. }
  12170. // Zero out memory for default ctor
  12171. if ((methodDeclaration == NULL) && (mCurTypeInstance->IsStruct()))
  12172. {
  12173. if (mCurTypeInstance->IsTypedPrimitive())
  12174. {
  12175. auto thisRef = mCurMethodState->mLocals[0]->mValue;
  12176. mBfIRBuilder->CreateStore(GetDefaultValue(mCurTypeInstance), thisRef);
  12177. }
  12178. else if (mCurTypeInstance->mInstSize > 0)
  12179. {
  12180. BfIRValue fillValue = GetConstValue8(0);
  12181. BfIRValue sizeValue = GetConstValue(mCurTypeInstance->mInstSize);
  12182. auto thisRef = mCurMethodState->mLocals[0]->mValue;
  12183. BfIRValue destBits = mBfIRBuilder->CreateBitCast(thisRef, mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr));
  12184. mBfIRBuilder->CreateMemSet(destBits, fillValue, sizeValue, mCurTypeInstance->mAlign);
  12185. }
  12186. }
  12187. BfAstNode* baseCtorNode = NULL;
  12188. if ((ctorDeclaration != NULL) && (ctorDeclaration->mInitializer != NULL) && (ctorDeclaration->mInitializer->mTarget != NULL))
  12189. baseCtorNode = ctorDeclaration->mInitializer->mTarget;
  12190. else if (methodDef->mBody != NULL)
  12191. baseCtorNode = methodDef->mBody;
  12192. else if (ctorDeclaration != NULL)
  12193. baseCtorNode = ctorDeclaration;
  12194. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  12195. baseCtorNode = mCurTypeInstance->mTypeDef->mTypeDeclaration->mNameNode;
  12196. else if ((mCurTypeInstance->mBaseType != NULL) && (mCurTypeInstance->mBaseType->mTypeDef->mTypeDeclaration != NULL))
  12197. baseCtorNode = mCurTypeInstance->mBaseType->mTypeDef->mTypeDeclaration;
  12198. else
  12199. baseCtorNode = mContext->mBfObjectType->mTypeDef->mTypeDeclaration;
  12200. if ((!mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType == BfMethodType_Ctor))
  12201. {
  12202. // Call the root type's default ctor (with no body) to initialize its fields and call the chained ctors
  12203. if (methodDef->mDeclaringType->mTypeCode == BfTypeCode_Extension)
  12204. {
  12205. BfMethodDef* defaultCtor = NULL;
  12206. for (auto methodDef : mCurTypeInstance->mTypeDef->mMethods)
  12207. {
  12208. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) && (methodDef->mDeclaringType->mTypeCode != BfTypeCode_Extension))
  12209. {
  12210. defaultCtor = methodDef;
  12211. }
  12212. }
  12213. if (defaultCtor != NULL)
  12214. {
  12215. UpdateSrcPos(mCurTypeInstance->mTypeDef->GetRefNode());
  12216. SetIllegalSrcPos();
  12217. auto moduleMethodInstance = GetMethodInstance(mCurTypeInstance, defaultCtor, BfTypeVector());
  12218. BfExprEvaluator exprEvaluator(this);
  12219. SizedArray<BfIRValue, 1> irArgs;
  12220. exprEvaluator.PushThis(NULL, GetThis(), moduleMethodInstance.mMethodInstance, irArgs);
  12221. exprEvaluator.CreateCall(moduleMethodInstance.mMethodInstance, moduleMethodInstance.mFunc, false, irArgs);
  12222. }
  12223. }
  12224. }
  12225. // Initialize fields (if applicable)
  12226. if (mCurTypeInstance->IsBoxed())
  12227. {
  12228. skipBody = true;
  12229. }
  12230. else if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mDeclaringType->mTypeCode == BfTypeCode_Extension))
  12231. {
  12232. // Field initializers occur in CtorNoBody methods for extensions
  12233. }
  12234. else if (!hadThisInitializer)
  12235. {
  12236. // If we had a 'this' initializer, that other ctor will have initialized our fields
  12237. if ((!mCompiler->mIsResolveOnly) ||
  12238. (mCompiler->mResolvePassData->mAutoComplete == NULL) ||
  12239. (mCompiler->mResolvePassData->mAutoComplete->mResolveType == BfResolveType_ShowFileSymbolReferences))
  12240. {
  12241. bool hadInlineInitBlock = false;
  12242. BfScopeData scopeData;
  12243. for (auto fieldDef : typeDef->mFields)
  12244. {
  12245. // For extensions, only handle these fields in the appropriate extension
  12246. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  12247. continue;
  12248. if ((!fieldDef->mIsConst) && (!fieldDef->mIsStatic))
  12249. {
  12250. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  12251. if (!fieldInst->mFieldIncluded)
  12252. continue;
  12253. if (fieldInst->mDataIdx < 0)
  12254. continue;
  12255. if (fieldDef->mInitializer == NULL)
  12256. {
  12257. if (fieldDef->mProtection != BfProtection_Hidden)
  12258. continue;
  12259. if (mCurTypeInstance->IsObject()) // Already zeroed out
  12260. continue;
  12261. }
  12262. if (fieldInst->mResolvedType == NULL)
  12263. {
  12264. BF_ASSERT(mHadBuildError);
  12265. continue;
  12266. }
  12267. if (fieldDef->mInitializer != NULL)
  12268. {
  12269. if (!hadInlineInitBlock)
  12270. {
  12271. if ((mBfIRBuilder->DbgHasInfo()) && (!mCurTypeInstance->IsUnspecializedType()) && (mHasFullDebugInfo))
  12272. {
  12273. UpdateSrcPos(baseCtorNode);
  12274. // 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
  12275. EmitEnsureInstructionAt();
  12276. BfType* thisType = mCurTypeInstance;
  12277. if (thisType->IsValueType())
  12278. thisType = CreateRefType(thisType);
  12279. SizedArray<BfIRMDNode, 1> diParamTypes;
  12280. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParamTypes);
  12281. mCurMethodState->AddScope(&scopeData);
  12282. NewScopeState();
  12283. int flags = 0;
  12284. mCurMethodState->mCurScope->mDIInlinedAt = mBfIRBuilder->DbgGetCurrentLocation();
  12285. BF_ASSERT(mCurMethodState->mCurScope->mDIInlinedAt);
  12286. // mCurMethodState->mCurScope->mDIInlinedAt may still be null ifwe don't have an explicit ctor
  12287. mCurMethodState->mCurScope->mDIScope = mBfIRBuilder->DbgCreateFunction(mBfIRBuilder->DbgGetTypeInst(mCurTypeInstance), "this$initFields", "", mCurFilePosition.mFileInstance->mDIFile,
  12288. mCurFilePosition.mCurLine + 1, diFuncType, false, true, mCurFilePosition.mCurLine + 1, flags, false, BfIRValue());
  12289. UpdateSrcPos(fieldDef->mInitializer);
  12290. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  12291. "this", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(thisType));
  12292. //
  12293. {
  12294. auto loadedThis = GetThis();
  12295. // LLVM can't handle two variables pointing to the same value
  12296. BfIRValue copiedThisPtr;
  12297. copiedThisPtr = CreateAlloca(thisType);
  12298. auto storeInst = mBfIRBuilder->CreateStore(loadedThis.mValue, copiedThisPtr);
  12299. mBfIRBuilder->ClearDebugLocation(storeInst);
  12300. mBfIRBuilder->DbgInsertDeclare(copiedThisPtr, diVariable);
  12301. }
  12302. hadInlineInitBlock = true;
  12303. }
  12304. }
  12305. UpdateSrcPos(fieldDef->mInitializer);
  12306. }
  12307. BfIRValue fieldAddr;
  12308. if ((!mCurTypeInstance->IsTypedPrimitive()) && (!fieldInst->mResolvedType->IsVar()))
  12309. {
  12310. fieldAddr = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, fieldInst->mDataIdx /*, fieldDef->mName*/);
  12311. }
  12312. else
  12313. {
  12314. AssertErrorState();
  12315. }
  12316. auto assignValue = GetFieldInitializerValue(fieldInst);
  12317. if ((fieldAddr) && (assignValue))
  12318. mBfIRBuilder->CreateStore(assignValue.mValue, fieldAddr);
  12319. }
  12320. }
  12321. if (hadInlineInitBlock)
  12322. {
  12323. RestoreScopeState();
  12324. // This gets set to false because of AddScope but we actually are still in the head block
  12325. mCurMethodState->mInHeadScope = true;
  12326. }
  12327. }
  12328. else // Autocomplete case
  12329. {
  12330. // The reason we can't just do the 'normal' path for this is that the BfTypeInstance here is NOT the
  12331. // autocomplete type instance, so FieldInstance initializer values contain expressions from the full
  12332. // resolve pass, NOT the autocomplete expression
  12333. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  12334. {
  12335. if (tempTypeDef->mFullName == typeDef->mFullName)
  12336. {
  12337. for (auto fieldDef : tempTypeDef->mFields)
  12338. {
  12339. if ((!fieldDef->mIsStatic) && (fieldDef->mInitializer != NULL) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  12340. {
  12341. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(fieldDef->mInitializer, BfSourceElementType_Normal);
  12342. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(fieldDef->mInitializer);
  12343. auto wantType = ResolveTypeRef(fieldDef->mTypeRef);
  12344. if ((wantType != NULL) &&
  12345. ((wantType->IsVar()) || (wantType->IsLet()) || (wantType->IsRef())))
  12346. wantType = NULL;
  12347. CreateValueFromExpression(fieldDef->mInitializer, wantType, BfEvalExprFlags_FieldInitializer);
  12348. }
  12349. }
  12350. }
  12351. }
  12352. // Mark fields from full type with initializers as initialized, to give proper initialization errors within ctor
  12353. for (auto fieldDef : typeDef->mFields)
  12354. {
  12355. if ((!fieldDef->mIsConst) && (!fieldDef->mIsStatic) && (fieldDef->mInitializer != NULL))
  12356. {
  12357. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  12358. if (fieldDef->mInitializer != NULL)
  12359. MarkFieldInitialized(fieldInst);
  12360. }
  12361. }
  12362. }
  12363. }
  12364. // Call base ctor (if applicable)
  12365. BfTypeInstance* targetType = NULL;
  12366. BfAstNode* targetRefNode = NULL;
  12367. if (ctorDeclaration != NULL)
  12368. targetRefNode = ctorDeclaration->mInitializer;
  12369. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(targetRefNode))
  12370. targetRefNode = invocationExpr->mTarget;
  12371. if (baseCtorNode != NULL)
  12372. {
  12373. UpdateSrcPos(baseCtorNode);
  12374. }
  12375. if ((ctorDeclaration != NULL) && (ctorDeclaration->mInitializer != NULL))
  12376. {
  12377. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorDeclaration->mInitializer->mTarget);
  12378. targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  12379. }
  12380. else if ((mCurTypeInstance->mBaseType != NULL) && (!mCurTypeInstance->IsUnspecializedType()))
  12381. {
  12382. auto baseType = mCurTypeInstance->mBaseType;
  12383. if ((!mCurTypeInstance->IsTypedPrimitive()) &&
  12384. (baseType->mTypeDef != mCompiler->mValueTypeTypeDef) &&
  12385. (baseType->mTypeDef != mCompiler->mBfObjectTypeDef))
  12386. {
  12387. // Try to find a ctor without any params first
  12388. bool foundBaseCtor = false;
  12389. bool hadCtorWithAllDefaults = false;
  12390. for (int pass = 0; pass < 2; pass++)
  12391. {
  12392. for (auto checkMethodDef : baseType->mTypeDef->mMethods)
  12393. {
  12394. bool allowPriv = checkMethodDef->mProtection != BfProtection_Private;
  12395. // Allow calling of the default base ctor if it is implicitly defined
  12396. if ((checkMethodDef->mMethodDeclaration == NULL) && (pass == 1) && (!hadCtorWithAllDefaults))
  12397. allowPriv = true;
  12398. if ((checkMethodDef->mMethodType == BfMethodType_Ctor) && (!checkMethodDef->mIsStatic) && (allowPriv))
  12399. {
  12400. if (checkMethodDef->mParams.size() == 0)
  12401. {
  12402. foundBaseCtor = true;
  12403. if (HasCompiledOutput())
  12404. {
  12405. SizedArray<BfIRValue, 1> args;
  12406. auto ctorBodyMethodInstance = GetMethodInstance(mCurTypeInstance->mBaseType, checkMethodDef, BfTypeVector());
  12407. if (!mCurTypeInstance->mBaseType->IsValuelessType())
  12408. {
  12409. auto basePtr = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapTypeInstPtr(mCurTypeInstance->mBaseType));
  12410. args.push_back(basePtr);
  12411. }
  12412. AddCallDependency(ctorBodyMethodInstance.mMethodInstance, true);
  12413. auto callInst = mBfIRBuilder->CreateCall(ctorBodyMethodInstance.mFunc, args);
  12414. auto callingConv = GetCallingConvention(ctorBodyMethodInstance.mMethodInstance->GetOwner(), ctorBodyMethodInstance.mMethodInstance->mMethodDef);
  12415. if (callingConv != BfIRCallingConv_CDecl)
  12416. mBfIRBuilder->SetCallCallingConv(callInst, callingConv);
  12417. // if (!mCurTypeInstance->mBaseType->IsValuelessType())
  12418. // mBfIRBuilder->SetCallCallingConv(callInst, BfIRCallingConv_ThisCall);
  12419. break;
  12420. }
  12421. }
  12422. else if ((checkMethodDef->mParams[0]->mParamDeclaration != NULL) && (checkMethodDef->mParams[0]->mParamDeclaration->mInitializer != NULL))
  12423. hadCtorWithAllDefaults = true;
  12424. }
  12425. }
  12426. if (foundBaseCtor)
  12427. break;
  12428. }
  12429. if (!foundBaseCtor)
  12430. {
  12431. targetType = mCurTypeInstance->mBaseType;
  12432. if (ctorDeclaration != NULL)
  12433. targetRefNode = ctorDeclaration->mThisToken;
  12434. else if (typeDef->mTypeDeclaration != NULL)
  12435. targetRefNode = typeDef->mTypeDeclaration->mNameNode;
  12436. }
  12437. }
  12438. }
  12439. if (methodDef->mHasAppend)
  12440. {
  12441. mCurMethodState->mCurAppendAlign = methodInstance->mAppendAllocAlign;
  12442. }
  12443. if (targetType != NULL)
  12444. {
  12445. auto autoComplete = mCompiler->GetAutoComplete();
  12446. auto wasCapturingMethodInfo = (autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo);
  12447. if ((autoComplete != NULL) && (ctorDeclaration != NULL) && (ctorDeclaration->mInitializer != NULL))
  12448. {
  12449. auto invocationExpr = ctorDeclaration->mInitializer;
  12450. autoComplete->CheckInvocation(invocationExpr, invocationExpr->mOpenParen, invocationExpr->mCloseParen, invocationExpr->mCommas);
  12451. }
  12452. BfType* targetThisType = targetType;
  12453. auto target = Cast(targetRefNode, GetThis(), targetThisType);
  12454. BfExprEvaluator exprEvaluator(this);
  12455. BfResolvedArgs argValues;
  12456. if ((ctorDeclaration != NULL) && (ctorDeclaration->mInitializer != NULL))
  12457. {
  12458. argValues.Init(&ctorDeclaration->mInitializer->mArguments);
  12459. if (gDebugStuff)
  12460. {
  12461. OutputDebugStrF("Expr: %@ %d\n", argValues.mArguments->mVals, argValues.mArguments->mSize);
  12462. }
  12463. }
  12464. exprEvaluator.ResolveArgValues(argValues, BfResolveArgFlag_DeferParamEval);
  12465. BfTypedValue appendIdxVal;
  12466. if (methodDef->mHasAppend)
  12467. {
  12468. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  12469. BF_ASSERT(localVar->mName == "appendIdx");
  12470. auto intRefType = CreateRefType(localVar->mResolvedType);
  12471. appendIdxVal = BfTypedValue(localVar->mValue, intRefType);
  12472. mCurMethodState->mCurAppendAlign = 1; // Don't make any assumptions about how the base leaves the alignment
  12473. }
  12474. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, methodDef->mHasAppend, &appendIdxVal);
  12475. if (autoComplete != NULL)
  12476. {
  12477. if ((wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo))
  12478. {
  12479. if (autoComplete->mMethodMatchInfo != NULL)
  12480. autoComplete->mIsCapturingMethodMatchInfo = true;
  12481. else
  12482. autoComplete->mIsCapturingMethodMatchInfo = false;
  12483. }
  12484. else
  12485. autoComplete->mIsCapturingMethodMatchInfo = false;
  12486. }
  12487. }
  12488. }
  12489. void BfModule::EmitEnumToStringBody()
  12490. {
  12491. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  12492. auto strVal = CreateAlloca(stringType);
  12493. auto int64StructType = GetPrimitiveStructType(BfTypeCode_Int64);
  12494. BfExprEvaluator exprEvaluator(this);
  12495. auto stringDestAddr = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  12496. BfIRBlock appendBlock = mBfIRBuilder->CreateBlock("append");
  12497. BfIRBlock noMatchBlock = mBfIRBuilder->CreateBlock("noMatch");
  12498. BfIRBlock endBlock = mBfIRBuilder->CreateBlock("end");
  12499. BfType* discriminatorType = NULL;
  12500. BfTypedValue rawPayload;
  12501. BfIRValue enumVal;
  12502. if (mCurTypeInstance->IsPayloadEnum())
  12503. {
  12504. discriminatorType = mCurTypeInstance->GetDiscriminatorType();
  12505. auto enumTypedValue = ExtractValue(GetThis(), NULL, 2);
  12506. enumTypedValue = LoadValue(enumTypedValue);
  12507. enumVal = enumTypedValue.mValue;
  12508. rawPayload = ExtractValue(GetThis(), NULL, 1);
  12509. }
  12510. else
  12511. enumVal = mBfIRBuilder->GetArgument(0);
  12512. Array<BfType*> paramTypes;
  12513. paramTypes.Add(stringType);
  12514. auto appendModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  12515. auto switchVal = mBfIRBuilder->CreateSwitch(enumVal, noMatchBlock, (int)mCurTypeInstance->mFieldInstances.size());
  12516. HashSet<int64> handledCases;
  12517. for (auto& fieldInstance : mCurTypeInstance->mFieldInstances)
  12518. {
  12519. if (fieldInstance.mIsEnumPayloadCase)
  12520. {
  12521. int tagId = -fieldInstance.mDataIdx - 1;
  12522. BfIRBlock caseBlock = mBfIRBuilder->CreateBlock("case");
  12523. mBfIRBuilder->AddBlock(caseBlock);
  12524. mBfIRBuilder->SetInsertPoint(caseBlock);
  12525. BF_ASSERT(discriminatorType->IsPrimitiveType());
  12526. auto constVal = mBfIRBuilder->CreateConst(((BfPrimitiveType*)discriminatorType)->mTypeDef->mTypeCode, tagId);
  12527. mBfIRBuilder->AddSwitchCase(switchVal, constVal, caseBlock);
  12528. auto caseStr = GetStringObjectValue(fieldInstance.GetFieldDef()->mName);
  12529. auto stringDestVal = LoadValue(stringDestAddr);
  12530. SizedArray<BfIRValue, 2> args;
  12531. args.Add(stringDestVal.mValue);
  12532. args.Add(caseStr);
  12533. exprEvaluator.CreateCall(appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  12534. auto payloadType = fieldInstance.mResolvedType->ToTypeInstance();
  12535. BF_ASSERT(payloadType->IsTuple());
  12536. if (payloadType->mFieldInstances.size() != 0)
  12537. {
  12538. auto payload = rawPayload;
  12539. if (payload.mType != payloadType)
  12540. {
  12541. payload = Cast(NULL, payload, payloadType, BfCastFlags_Force);
  12542. }
  12543. auto toStringMethod = GetMethodByName(payloadType->ToTypeInstance(), "ToString");
  12544. SizedArray<BfIRValue, 2> irArgs;
  12545. exprEvaluator.PushThis(NULL, payload, toStringMethod.mMethodInstance, irArgs);
  12546. stringDestVal = LoadValue(stringDestAddr);
  12547. irArgs.Add(stringDestVal.mValue);
  12548. exprEvaluator.CreateCall(toStringMethod.mMethodInstance, toStringMethod.mFunc, true, irArgs);
  12549. }
  12550. mBfIRBuilder->CreateBr(endBlock);
  12551. continue;
  12552. }
  12553. if (fieldInstance.mConstIdx == -1)
  12554. continue;
  12555. auto constant = mCurTypeInstance->mConstHolder->GetConstantById(fieldInstance.mConstIdx);
  12556. if (!handledCases.TryAdd(constant->mInt64, NULL))
  12557. {
  12558. // Duplicate
  12559. continue;
  12560. }
  12561. BfIRBlock caseBlock = mBfIRBuilder->CreateBlock("case");
  12562. mBfIRBuilder->AddBlock(caseBlock);
  12563. mBfIRBuilder->SetInsertPoint(caseBlock);
  12564. BfIRValue constVal = ConstantToCurrent(constant, mCurTypeInstance->mConstHolder, mCurTypeInstance);
  12565. mBfIRBuilder->AddSwitchCase(switchVal, constVal, caseBlock);
  12566. auto caseStr = GetStringObjectValue(fieldInstance.GetFieldDef()->mName);
  12567. mBfIRBuilder->CreateStore(caseStr, strVal);
  12568. mBfIRBuilder->CreateBr(appendBlock);
  12569. }
  12570. mBfIRBuilder->AddBlock(appendBlock);
  12571. mBfIRBuilder->SetInsertPoint(appendBlock);
  12572. SizedArray<BfIRValue, 2> args;
  12573. auto stringDestVal = LoadValue(stringDestAddr);
  12574. args.Add(stringDestVal.mValue);
  12575. args.Add(mBfIRBuilder->CreateLoad(strVal));
  12576. exprEvaluator.CreateCall(appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  12577. mBfIRBuilder->CreateBr(endBlock);
  12578. mBfIRBuilder->AddBlock(noMatchBlock);
  12579. mBfIRBuilder->SetInsertPoint(noMatchBlock);
  12580. auto int64Val = mBfIRBuilder->CreateNumericCast(enumVal, false, BfTypeCode_Int64);
  12581. auto toStringModuleMethodInstance = GetMethodByName(int64StructType, "ToString", 1);
  12582. args.clear();
  12583. args.Add(int64Val);
  12584. stringDestVal = LoadValue(stringDestAddr);
  12585. args.Add(stringDestVal.mValue);
  12586. exprEvaluator.CreateCall(toStringModuleMethodInstance.mMethodInstance, toStringModuleMethodInstance.mFunc, false, args);
  12587. mBfIRBuilder->CreateBr(endBlock);
  12588. mBfIRBuilder->AddBlock(endBlock);
  12589. mBfIRBuilder->SetInsertPoint(endBlock);
  12590. }
  12591. void BfModule::EmitTupleToStringBody()
  12592. {
  12593. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  12594. BfExprEvaluator exprEvaluator(this);
  12595. auto stringDestRef = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  12596. Array<BfType*> paramTypes;
  12597. paramTypes.Add(GetPrimitiveType(BfTypeCode_Char8));
  12598. auto appendCharModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  12599. paramTypes.Clear();
  12600. paramTypes.Add(stringType);
  12601. auto appendModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  12602. auto _AppendChar = [&](char c)
  12603. {
  12604. SizedArray<BfIRValue, 2> args;
  12605. auto stringDestVal = LoadValue(stringDestRef);
  12606. args.Add(stringDestVal.mValue);
  12607. args.Add(mBfIRBuilder->CreateConst(BfTypeCode_Char8, (int)c));
  12608. exprEvaluator.CreateCall(appendCharModuleMethodInstance.mMethodInstance, appendCharModuleMethodInstance.mFunc, false, args);
  12609. };
  12610. int fieldIdx = 0;
  12611. auto thisValue = GetThis();
  12612. auto toStringModuleMethodInstance = GetMethodByName(mContext->mBfObjectType, "ToString", 1);
  12613. auto toStringSafeModuleMethodInstance = GetMethodByName(mContext->mBfObjectType, "ToString", 2);
  12614. BfIRValue commaStr;
  12615. auto iPrintableType = ResolveTypeDef(mCompiler->mIPrintableTypeDef)->ToTypeInstance();
  12616. auto printModuleMethodInstance = GetMethodByName(iPrintableType, "Print");
  12617. _AppendChar('(');
  12618. for (auto& fieldInstance : mCurTypeInstance->mFieldInstances)
  12619. {
  12620. if (fieldInstance.mDataIdx == -1)
  12621. continue;
  12622. if (fieldIdx > 0)
  12623. {
  12624. if (!commaStr)
  12625. commaStr = GetStringObjectValue(", ");
  12626. SizedArray<BfIRValue, 2> args;
  12627. auto stringDestVal = LoadValue(stringDestRef);
  12628. args.Add(stringDestVal.mValue);
  12629. args.Add(commaStr);
  12630. exprEvaluator.CreateCall(appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  12631. }
  12632. fieldIdx++;
  12633. if (fieldInstance.mResolvedType->IsValuelessType())
  12634. continue;
  12635. BfTypedValue fieldValue = ExtractValue(thisValue, &fieldInstance, fieldInstance.mDataIdx);
  12636. if (fieldValue.mType->IsPrimitiveType())
  12637. {
  12638. fieldValue.mType = GetPrimitiveStructType(((BfPrimitiveType*)fieldValue.mType)->mTypeDef->mTypeCode);
  12639. }
  12640. auto typeInstance = fieldValue.mType->ToTypeInstance();
  12641. if ((typeInstance != NULL) && (TypeIsSubTypeOf(typeInstance, iPrintableType, false)))
  12642. {
  12643. BfExprEvaluator exprEvaluator(this);
  12644. SizedArray<BfResolvedArg, 0> resolvedArgs;
  12645. BfMethodMatcher methodMatcher(NULL, this, printModuleMethodInstance.mMethodInstance, resolvedArgs);
  12646. methodMatcher.mBestMethodDef = printModuleMethodInstance.mMethodInstance->mMethodDef;
  12647. methodMatcher.mBestMethodTypeInstance = iPrintableType;
  12648. methodMatcher.TryDevirtualizeCall(fieldValue);
  12649. BfTypedValue callVal = Cast(NULL, fieldValue, methodMatcher.mBestMethodTypeInstance);
  12650. BfResolvedArg resolvedArg;
  12651. auto stringDestVal = LoadValue(stringDestRef);
  12652. resolvedArg.mTypedValue = stringDestVal;
  12653. resolvedArg.mResolvedType = stringDestVal.mType;
  12654. resolvedArgs.Add(resolvedArg);
  12655. exprEvaluator.CreateCall(&methodMatcher, callVal);
  12656. continue;
  12657. }
  12658. if (fieldValue.mType->IsObjectOrInterface())
  12659. {
  12660. BF_ASSERT(!fieldValue.IsAddr());
  12661. SizedArray<BfIRValue, 2> args;
  12662. args.Add(mBfIRBuilder->CreateBitCast(fieldValue.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType)));
  12663. auto stringDestVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  12664. stringDestVal = LoadValue(stringDestVal);
  12665. args.Add(stringDestVal.mValue);
  12666. exprEvaluator.CreateCall(toStringSafeModuleMethodInstance.mMethodInstance, toStringSafeModuleMethodInstance.mFunc, false, args);
  12667. continue;
  12668. }
  12669. BfExprEvaluator exprEvaluator(this);
  12670. SizedArray<BfResolvedArg, 0> resolvedArgs;
  12671. BfMethodMatcher methodMatcher(NULL, this, toStringModuleMethodInstance.mMethodInstance, resolvedArgs);
  12672. methodMatcher.mBestMethodDef = toStringModuleMethodInstance.mMethodInstance->mMethodDef;
  12673. methodMatcher.mBestMethodTypeInstance = mContext->mBfObjectType;
  12674. methodMatcher.TryDevirtualizeCall(fieldValue);
  12675. if (methodMatcher.mBestMethodTypeInstance == mContext->mBfObjectType)
  12676. {
  12677. AddCallDependency(appendModuleMethodInstance.mMethodInstance);
  12678. AddDependency(fieldValue.mType, mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  12679. // Just append the type name
  12680. String typeName = TypeToString(fieldInstance.mResolvedType);
  12681. auto strVal = GetStringObjectValue(typeName);
  12682. SizedArray<BfIRValue, 2> args;
  12683. auto stringDestVal = LoadValue(stringDestRef);
  12684. args.Add(stringDestVal.mValue);
  12685. args.Add(strVal);
  12686. exprEvaluator.CreateCall(appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  12687. continue;
  12688. }
  12689. BfTypedValue callVal = Cast(NULL, fieldValue, methodMatcher.mBestMethodTypeInstance);
  12690. BfResolvedArg resolvedArg;
  12691. auto stringDestVal = LoadValue(stringDestRef);
  12692. resolvedArg.mTypedValue = stringDestVal;
  12693. resolvedArg.mResolvedType = stringDestVal.mType;
  12694. resolvedArgs.Add(resolvedArg);
  12695. exprEvaluator.CreateCall(&methodMatcher, callVal);
  12696. }
  12697. _AppendChar(')');
  12698. }
  12699. void BfModule::EmitIteratorBlock(bool& skipBody)
  12700. {
  12701. auto methodInstance = mCurMethodInstance;
  12702. auto methodDef = methodInstance->mMethodDef;
  12703. auto methodDeclaration = methodDef->GetMethodDeclaration();
  12704. auto typeDef = mCurTypeInstance->mTypeDef;
  12705. BfType* innerRetType = NULL;
  12706. BfTypeInstance* usingInterface = NULL;
  12707. auto retTypeInst = mCurMethodInstance->mReturnType->ToGenericTypeInstance();
  12708. if (retTypeInst != NULL)
  12709. {
  12710. if ((retTypeInst->mTypeDef == mCompiler->mGenericIEnumerableTypeDef) ||
  12711. (retTypeInst->mTypeDef == mCompiler->mGenericIEnumeratorTypeDef))
  12712. {
  12713. innerRetType = retTypeInst->mTypeGenericArguments[0];
  12714. }
  12715. }
  12716. if (innerRetType == NULL)
  12717. {
  12718. Fail("Methods with yields must return either System.IEnumerable<T> or System.IEnumerator<T>", methodDeclaration->mReturnType);
  12719. return;
  12720. }
  12721. auto blockBody = BfNodeDynCast<BfBlock>(methodDeclaration->mBody);
  12722. if (blockBody == NULL)
  12723. return;
  12724. }
  12725. void BfModule::EmitGCMarkValue(BfTypedValue markVal, BfModuleMethodInstance markFromGCThreadMethodInstance)
  12726. {
  12727. auto fieldTypeInst = markVal.mType->ToTypeInstance();
  12728. if (fieldTypeInst == NULL)
  12729. return;
  12730. if (!markVal.mType->IsComposite())
  12731. markVal = LoadValue(markVal);
  12732. BfExprEvaluator exprEvaluator(this);
  12733. PopulateType(markVal.mType, BfPopulateType_Data);
  12734. if (markVal.mType->IsObjectOrInterface())
  12735. {
  12736. BfIRValue val = markVal.mValue;
  12737. val = mBfIRBuilder->CreateBitCast(val, mBfIRBuilder->MapType(mContext->mBfObjectType));
  12738. SizedArray<BfIRValue, 1> args;
  12739. args.push_back(val);
  12740. exprEvaluator.CreateCall(markFromGCThreadMethodInstance.mMethodInstance, markFromGCThreadMethodInstance.mFunc, false, args);
  12741. }
  12742. else if ((fieldTypeInst->IsComposite()) && (!fieldTypeInst->IsTypedPrimitive()))
  12743. {
  12744. auto markMemberMethodInstance = GetMethodByName(fieldTypeInst, BF_METHODNAME_MARKMEMBERS, 0, true);
  12745. if (markMemberMethodInstance)
  12746. {
  12747. SizedArray<BfIRValue, 1> args;
  12748. //(1, markVal.mValue);
  12749. //exprEvaluator.PushArg(markVal, args);
  12750. exprEvaluator.PushThis(NULL, markVal, markMemberMethodInstance.mMethodInstance, args);
  12751. exprEvaluator.CreateCall(markMemberMethodInstance.mMethodInstance, markMemberMethodInstance.mFunc, false, args);
  12752. }
  12753. }
  12754. }
  12755. void BfModule::CallChainedMethods(BfMethodInstance* methodInstance, bool reverse)
  12756. {
  12757. Array<BfMethodInstance*> methodInstances;
  12758. for (int methodIdx = 0; methodIdx < (int)mCurTypeInstance->mMethodInstanceGroups.size(); methodIdx++)
  12759. {
  12760. auto& methodInstGroup = mCurTypeInstance->mMethodInstanceGroups[methodIdx];
  12761. auto chainedMethodInst = methodInstGroup.mDefault;
  12762. if ((chainedMethodInst != NULL) && (chainedMethodInst->mChainType == BfMethodChainType_ChainMember))
  12763. {
  12764. if ((chainedMethodInst->mMethodDef->mIsStatic == methodInstance->mMethodDef->mIsStatic) &&
  12765. (CompareMethodSignatures(methodInstance, chainedMethodInst)))
  12766. {
  12767. methodInstances.push_back(chainedMethodInst);
  12768. }
  12769. }
  12770. }
  12771. std::stable_sort(methodInstances.begin(), methodInstances.end(),
  12772. [&](BfMethodInstance* lhs, BfMethodInstance* rhs)
  12773. {
  12774. bool isBetter;
  12775. bool isWorse;
  12776. CompareDeclTypes(lhs->mMethodDef->mDeclaringType, rhs->mMethodDef->mDeclaringType, isBetter, isWorse);
  12777. if (isBetter == isWorse)
  12778. {
  12779. return false;
  12780. }
  12781. return isWorse;
  12782. });
  12783. if (reverse)
  12784. std::reverse(methodInstances.begin(), methodInstances.end());
  12785. for (auto chainedMethodInst : methodInstances)
  12786. {
  12787. auto declModule = this;
  12788. BfGetMethodInstanceFlags flags = BfGetMethodInstanceFlag_None;
  12789. auto moduleMethodInst = declModule->GetMethodInstance(mCurTypeInstance, chainedMethodInst->mMethodDef, BfTypeVector(), flags);
  12790. BfExprEvaluator exprEvaluator(this);
  12791. SizedArray<BfIRValue, 1> args;
  12792. exprEvaluator.PushThis(chainedMethodInst->mMethodDef->GetRefNode(), GetThis(), chainedMethodInst, args);
  12793. exprEvaluator.CreateCall(moduleMethodInst.mMethodInstance, moduleMethodInst.mFunc, true, args);
  12794. }
  12795. }
  12796. void BfModule::AddHotDataReferences(BfHotDataReferenceBuilder* builder)
  12797. {
  12798. BF_ASSERT(mCurMethodInstance->mIsReified);
  12799. if (mCurTypeInstance->mHotTypeData == NULL)
  12800. mCurTypeInstance->mHotTypeData = new BfHotTypeData();
  12801. auto hotMethod = mCurMethodInstance->mHotMethod;
  12802. for (auto depData : hotMethod->mReferences)
  12803. {
  12804. // Only virtual decls are allowed to already be there
  12805. BF_ASSERT((depData->mDataKind == BfHotDepDataKind_VirtualDecl) || (depData->mDataKind == BfHotDepDataKind_DupMethod));
  12806. }
  12807. BF_ASSERT(hotMethod->mSrcTypeVersion != NULL);
  12808. int prevSize = (int)hotMethod->mReferences.size();
  12809. int refCount = (int)(prevSize + builder->mUsedData.size() + builder->mCalledMethods.size() + builder->mDevirtualizedCalledMethods.size());
  12810. if (!mCurMethodInstance->mMethodDef->mIsStatic)
  12811. refCount++;
  12812. hotMethod->mReferences.Reserve(refCount);
  12813. if (!mCurMethodInstance->mMethodDef->mIsStatic)
  12814. {
  12815. auto hotThis = mCompiler->mHotData->GetThisType(mCurMethodInstance->GetOwner()->mHotTypeData->GetLatestVersion());
  12816. hotThis->mRefCount++;
  12817. hotMethod->mReferences.Insert(0, hotThis);
  12818. prevSize++;
  12819. }
  12820. for (auto val : builder->mAllocatedData)
  12821. {
  12822. auto hotAllocation = mCompiler->mHotData->GetAllocation(val);
  12823. hotMethod->mReferences.Add(hotAllocation);
  12824. }
  12825. for (auto val : builder->mUsedData)
  12826. hotMethod->mReferences.Add(val);
  12827. for (auto val : builder->mCalledMethods)
  12828. hotMethod->mReferences.Add(val);
  12829. for (auto val : builder->mDevirtualizedCalledMethods)
  12830. {
  12831. auto devirtualizedMethod = mCompiler->mHotData->GetDevirtualizedMethod(val);
  12832. hotMethod->mReferences.Add(devirtualizedMethod);
  12833. }
  12834. for (auto val : builder->mFunctionPtrs)
  12835. {
  12836. auto funcRef = mCompiler->mHotData->GetFunctionReference(val);
  12837. hotMethod->mReferences.Add(funcRef);
  12838. }
  12839. for (auto val : builder->mInnerMethods)
  12840. {
  12841. auto innerMethod = mCompiler->mHotData->GetInnerMethod(val);
  12842. hotMethod->mReferences.Add(innerMethod);
  12843. }
  12844. for (int refIdx = prevSize; refIdx < (int)hotMethod->mReferences.size(); refIdx++)
  12845. {
  12846. auto depData = hotMethod->mReferences[refIdx];
  12847. BF_ASSERT(depData != NULL);
  12848. depData->mRefCount++;
  12849. }
  12850. //hotMethod->mReferences.Sort([](BfHotDepData* lhs, BfHotDepData* rhs) { return lhs < rhs; });
  12851. }
  12852. void BfModule::ProcessMethod_SetupParams(BfMethodInstance* methodInstance, BfType* thisType, bool wantsDIData, SizedArrayImpl<BfIRMDNode>* diParams)
  12853. {
  12854. auto methodDef = methodInstance->mMethodDef;
  12855. auto methodDeclaration = methodDef->mMethodDeclaration;
  12856. bool isThisStruct = false;
  12857. if (thisType != NULL)
  12858. isThisStruct = thisType->IsStruct() && !thisType->IsTypedPrimitive();
  12859. int argIdx = 0;
  12860. if (methodInstance->HasStructRet())
  12861. argIdx++;
  12862. if (!methodDef->mIsStatic)
  12863. {
  12864. BfLocalVariable* paramVar = new BfLocalVariable();
  12865. paramVar->mResolvedType = thisType;
  12866. paramVar->mName = "this";
  12867. if (!thisType->IsValuelessType())
  12868. paramVar->mValue = mBfIRBuilder->GetArgument(argIdx);
  12869. else
  12870. paramVar->mValue = mBfIRBuilder->GetFakeVal();
  12871. if ((thisType->IsComposite()) && (!methodDef->HasNoThisSplat()))
  12872. {
  12873. if (thisType->IsSplattable())
  12874. paramVar->mIsSplat = true;
  12875. else
  12876. paramVar->mIsLowered = thisType->GetLoweredType() != BfTypeCode_None;
  12877. }
  12878. auto thisTypeInst = thisType->ToTypeInstance();
  12879. paramVar->mIsStruct = isThisStruct;
  12880. paramVar->mAddr = BfIRValue();
  12881. paramVar->mIsThis = true;
  12882. paramVar->mParamIdx = -1;
  12883. if ((methodDef->mMethodType == BfMethodType_Ctor) && (mCurTypeInstance->IsStruct()))
  12884. {
  12885. paramVar->mIsAssigned = false;
  12886. }
  12887. else
  12888. {
  12889. paramVar->mIsAssigned = true;
  12890. }
  12891. paramVar->mReadFromId = -1;
  12892. paramVar->Init();
  12893. if (methodDeclaration == NULL)
  12894. UseDefaultSrcPos();
  12895. AddLocalVariableDef(paramVar);
  12896. if (!thisType->IsValuelessType())
  12897. {
  12898. if (wantsDIData)
  12899. {
  12900. BfType* thisPtrType = thisType;
  12901. auto diType = mBfIRBuilder->DbgGetType(thisPtrType);
  12902. if (!thisType->IsValueType())
  12903. diType = mBfIRBuilder->DbgCreateArtificialType(diType);
  12904. diParams->push_back(diType);
  12905. }
  12906. if (paramVar->mIsSplat)
  12907. {
  12908. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  12909. }
  12910. else
  12911. {
  12912. argIdx++;
  12913. }
  12914. }
  12915. }
  12916. bool hadParams = false;
  12917. bool hasDefault = false;
  12918. int compositeVariableIdx = -1;
  12919. int paramIdx = 0;
  12920. for (paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  12921. {
  12922. // We already issues a type error for this param if we had one in declaration processing
  12923. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  12924. BfLocalVariable* paramVar = new BfLocalVariable();
  12925. bool isParamSkipped = methodInstance->IsParamSkipped(paramIdx);
  12926. BfType* unresolvedType = methodInstance->GetParamType(paramIdx, false);
  12927. if (unresolvedType == NULL)
  12928. {
  12929. AssertErrorState();
  12930. unresolvedType = mContext->mBfObjectType;
  12931. paramVar->mParamFailed = true;
  12932. }
  12933. auto resolvedType = methodInstance->GetParamType(paramIdx, true);
  12934. prevIgnoreErrors.Restore();
  12935. PopulateType(resolvedType, BfPopulateType_Declaration);
  12936. paramVar->mResolvedType = resolvedType;
  12937. paramVar->mName = methodInstance->GetParamName(paramIdx);
  12938. paramVar->mNameNode = methodInstance->GetParamNameNode(paramIdx);
  12939. if (!isParamSkipped)
  12940. {
  12941. paramVar->mValue = mBfIRBuilder->GetArgument(argIdx);
  12942. if (resolvedType->IsMethodRef())
  12943. {
  12944. paramVar->mIsSplat = true;
  12945. }
  12946. else if (resolvedType->IsComposite() && resolvedType->IsSplattable())
  12947. {
  12948. int splatCount = resolvedType->GetSplatCount();
  12949. if (argIdx + splatCount <= mCompiler->mOptions.mMaxSplatRegs)
  12950. paramVar->mIsSplat = true;
  12951. }
  12952. }
  12953. else
  12954. {
  12955. paramVar->mIsSplat = true; // Treat skipped (valueless) as a splat
  12956. paramVar->mValue = mBfIRBuilder->GetFakeVal();
  12957. }
  12958. paramVar->mIsLowered = resolvedType->GetLoweredType() != BfTypeCode_None;
  12959. paramVar->mIsStruct = resolvedType->IsComposite() && !resolvedType->IsTypedPrimitive();
  12960. paramVar->mParamIdx = paramIdx;
  12961. paramVar->mIsImplicitParam = methodInstance->IsImplicitCapture(paramIdx);
  12962. paramVar->mReadFromId = 0;
  12963. if (resolvedType->IsRef())
  12964. {
  12965. auto refType = (BfRefType*)resolvedType;
  12966. paramVar->mIsAssigned = refType->mRefKind != BfRefType::RefKind_Out;
  12967. }
  12968. else
  12969. {
  12970. paramVar->mIsAssigned = true;
  12971. if (methodDef->mMethodType != BfMethodType_Mixin)
  12972. paramVar->mIsReadOnly = true;
  12973. }
  12974. if (paramVar->mResolvedType->IsGenericParam())
  12975. {
  12976. auto genericParamInst = GetGenericParamInstance((BfGenericParamType*)paramVar->mResolvedType);
  12977. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  12978. {
  12979. auto typedVal = GetDefaultTypedValue(genericParamInst->mTypeConstraint, false, BfDefaultValueKind_Undef);
  12980. paramVar->mResolvedType = typedVal.mType;
  12981. paramVar->mConstValue = typedVal.mValue;
  12982. }
  12983. }
  12984. if (paramVar->mResolvedType->IsConstExprValue())
  12985. {
  12986. BfConstExprValueType* constExprValueType = (BfConstExprValueType*)paramVar->mResolvedType;
  12987. auto unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance);
  12988. auto unspecParamType = unspecializedMethodInstance->GetParamType(paramIdx);
  12989. BF_ASSERT(unspecParamType->IsGenericParam());
  12990. if (unspecParamType->IsGenericParam())
  12991. {
  12992. BfGenericParamType* genericParamType = (BfGenericParamType*)unspecParamType;
  12993. if (genericParamType->mGenericParamKind == BfGenericParamKind_Method)
  12994. {
  12995. auto genericParamInst = unspecializedMethodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  12996. if (genericParamInst->mTypeConstraint != NULL)
  12997. {
  12998. BfExprEvaluator exprEvaluator(this);
  12999. exprEvaluator.mExpectingType = genericParamInst->mTypeConstraint;
  13000. exprEvaluator.GetLiteral(NULL, constExprValueType->mValue);
  13001. auto checkType = genericParamInst->mTypeConstraint;
  13002. if (checkType->IsTypedPrimitive())
  13003. checkType = checkType->GetUnderlyingType();
  13004. if (exprEvaluator.mResult.mType == checkType)
  13005. {
  13006. paramVar->mResolvedType = genericParamInst->mTypeConstraint;
  13007. paramVar->mConstValue = exprEvaluator.mResult.mValue;
  13008. BF_ASSERT(paramVar->mConstValue.IsConst());
  13009. }
  13010. else
  13011. {
  13012. AssertErrorState();
  13013. paramVar->mResolvedType = genericParamInst->mTypeConstraint;
  13014. paramVar->mConstValue = GetDefaultValue(genericParamInst->mTypeConstraint);
  13015. }
  13016. }
  13017. }
  13018. }
  13019. //BF_ASSERT(!paramVar->mResolvedType->IsConstExprValue());
  13020. if (paramVar->mResolvedType->IsConstExprValue())
  13021. {
  13022. Fail("Invalid use of constant expression", methodInstance->GetParamTypeRef(paramIdx));
  13023. //AssertErrorState();
  13024. paramVar->mResolvedType = GetPrimitiveType(BfTypeCode_IntPtr);
  13025. paramVar->mConstValue = GetDefaultValue(paramVar->mResolvedType);
  13026. }
  13027. }
  13028. if (methodInstance->GetParamKind(paramIdx) == BfParamKind_DelegateParam)
  13029. {
  13030. if (compositeVariableIdx == -1)
  13031. {
  13032. compositeVariableIdx = (int)mCurMethodState->mLocals.size();
  13033. BfLocalVariable* localVar = new BfLocalVariable();
  13034. auto paramInst = &methodInstance->mParams[paramIdx];
  13035. auto paramDef = methodDef->mParams[paramInst->mParamDefIdx];
  13036. localVar->mName = paramDef->mName;
  13037. localVar->mResolvedType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_NoResolveGenericParam);
  13038. localVar->mCompositeCount = 0;
  13039. DoAddLocalVariable(localVar);
  13040. }
  13041. mCurMethodState->mLocals[compositeVariableIdx]->mCompositeCount++;
  13042. }
  13043. CheckVariableDef(paramVar);
  13044. paramVar->Init();
  13045. AddLocalVariableDef(paramVar);
  13046. if (!isParamSkipped)
  13047. {
  13048. if (wantsDIData)
  13049. diParams->push_back(mBfIRBuilder->DbgGetType(resolvedType));
  13050. if (paramVar->mIsSplat)
  13051. {
  13052. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  13053. }
  13054. else
  13055. {
  13056. argIdx++;
  13057. }
  13058. }
  13059. }
  13060. // Try to find an ending delegate params composite
  13061. if ((compositeVariableIdx == -1) && (methodDef->mParams.size() > 0))
  13062. {
  13063. auto paramDef = methodDef->mParams.back();
  13064. if (paramDef->mParamKind == BfParamKind_Params)
  13065. {
  13066. auto paramsType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_NoResolveGenericParam);
  13067. if (paramsType == NULL)
  13068. {
  13069. AssertErrorState();
  13070. }
  13071. else if (paramsType->IsGenericParam())
  13072. {
  13073. auto genericParamInstance = GetGenericParamInstance((BfGenericParamType*)paramsType);
  13074. if (genericParamInstance->mTypeConstraint != NULL)
  13075. {
  13076. auto typeInstConstraint = genericParamInstance->mTypeConstraint->ToTypeInstance();
  13077. if ((genericParamInstance->mTypeConstraint->IsDelegate()) || (genericParamInstance->mTypeConstraint->IsFunction()) ||
  13078. ((typeInstConstraint != NULL) &&
  13079. ((typeInstConstraint->mTypeDef == mCompiler->mDelegateTypeDef) || (typeInstConstraint->mTypeDef == mCompiler->mFunctionTypeDef))))
  13080. {
  13081. BfLocalVariable* localVar = new BfLocalVariable();
  13082. localVar->mName = paramDef->mName;
  13083. localVar->mResolvedType = paramsType;
  13084. localVar->mCompositeCount = 0;
  13085. DoAddLocalVariable(localVar);
  13086. }
  13087. }
  13088. }
  13089. else if (paramsType->IsDelegate())
  13090. {
  13091. BfMethodInstance* invokeMethodInstance = GetRawMethodInstanceAtIdx(paramsType->ToTypeInstance(), 0, "Invoke");
  13092. if (invokeMethodInstance != NULL)
  13093. {
  13094. // This is only for the case where the delegate didn't actually have any params so the composite is zero-sized
  13095. // and wasn't cleared by the preceding loop
  13096. BF_ASSERT(invokeMethodInstance->GetParamCount() == 0);
  13097. BfLocalVariable* localVar = new BfLocalVariable();
  13098. localVar->mName = paramDef->mName;
  13099. localVar->mResolvedType = paramsType;
  13100. localVar->mCompositeCount = 0;
  13101. DoAddLocalVariable(localVar);
  13102. }
  13103. }
  13104. }
  13105. }
  13106. }
  13107. void BfModule::ProcessMethod_ProcessDeferredLocals(int startIdx)
  13108. {
  13109. // if (mCurMethodState->mPrevMethodState != NULL) // Re-entry
  13110. // return;
  13111. auto _ClearState = [&]()
  13112. {
  13113. mCurMethodState->mLocalMethods.Clear();
  13114. for (auto& local : mCurMethodState->mLocals)
  13115. delete local;
  13116. mCurMethodState->mLocals.Clear();
  13117. mCurMethodState->mLocalVarSet.Clear();
  13118. };
  13119. // 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
  13120. // we show errors in the capture phase. If we somehow pass the capture phase without error then this method WILL show any errors here,
  13121. // however (compiler bug), so this is the safest way
  13122. if (!mCurMethodState->mDeferredLocalMethods.IsEmpty())
  13123. {
  13124. for (int deferredLocalMethodIdx = 0; deferredLocalMethodIdx < (int)mCurMethodState->mDeferredLocalMethods.size(); deferredLocalMethodIdx++)
  13125. {
  13126. auto deferredLocalMethod = mCurMethodState->mDeferredLocalMethods[deferredLocalMethodIdx];
  13127. BfLogSysM("Processing deferred local method %p\n", deferredLocalMethod);
  13128. if (!mHadBuildError)
  13129. {
  13130. // Process as a closure - that allows us to look back and see the const locals and stuff
  13131. BfClosureState closureState;
  13132. mCurMethodState->mClosureState = &closureState;
  13133. closureState.mConstLocals = deferredLocalMethod->mConstLocals;
  13134. closureState.mReturnType = deferredLocalMethod->mMethodInstance->mReturnType;
  13135. closureState.mActiveDeferredLocalMethod = deferredLocalMethod;
  13136. closureState.mLocalMethod = deferredLocalMethod->mLocalMethod;
  13137. if (deferredLocalMethod->mMethodInstance->mMethodInfoEx != NULL)
  13138. closureState.mClosureInstanceInfo = deferredLocalMethod->mMethodInstance->mMethodInfoEx->mClosureInstanceInfo;
  13139. mCurMethodState->mMixinState = deferredLocalMethod->mLocalMethod->mDeclMixinState;
  13140. _ClearState();
  13141. for (auto& constLocal : deferredLocalMethod->mConstLocals)
  13142. {
  13143. auto localVar = new BfLocalVariable();
  13144. *localVar = constLocal;
  13145. DoAddLocalVariable(localVar);
  13146. }
  13147. mCurMethodState->mLocalMethods = deferredLocalMethod->mLocalMethods;
  13148. bool doProcess = !mCompiler->mCanceling;
  13149. if (doProcess)
  13150. {
  13151. BP_ZONE_F("ProcessMethod local %s", deferredLocalMethod->mMethodInstance->mMethodDef->mName.c_str());
  13152. ProcessMethod(deferredLocalMethod->mMethodInstance);
  13153. }
  13154. }
  13155. delete deferredLocalMethod;
  13156. mSystem->CheckLockYield();
  13157. }
  13158. }
  13159. for (auto& kv : mCurMethodState->mLocalMethodCache)
  13160. {
  13161. BF_ASSERT((kv.mValue->mMethodDef == NULL) || (kv.mKey == kv.mValue->mMethodDef->mName));
  13162. }
  13163. if ((!mCurMethodState->mDeferredLambdaInstances.IsEmpty()) && (!mHadBuildError))
  13164. {
  13165. for (int deferredLambdaIdx = 0; deferredLambdaIdx < (int)mCurMethodState->mDeferredLambdaInstances.size(); deferredLambdaIdx++)
  13166. {
  13167. auto lambdaInstance = mCurMethodState->mDeferredLambdaInstances[deferredLambdaIdx];
  13168. BfLogSysM("Processing deferred lambdaInstance %p\n", lambdaInstance);
  13169. BfClosureState closureState;
  13170. mCurMethodState->mClosureState = &closureState;
  13171. //closureState.mConstLocals = deferredLocalMethod->mConstLocals;
  13172. closureState.mReturnType = lambdaInstance->mMethodInstance->mReturnType;
  13173. if (lambdaInstance->mClosureTypeInstance != NULL)
  13174. closureState.mClosureType = lambdaInstance->mClosureTypeInstance;
  13175. else
  13176. closureState.mClosureType = lambdaInstance->mDelegateTypeInstance;
  13177. closureState.mClosureInstanceInfo = lambdaInstance->mMethodInstance->mMethodInfoEx->mClosureInstanceInfo;
  13178. mCurMethodState->mMixinState = lambdaInstance->mDeclMixinState;
  13179. _ClearState();
  13180. for (auto& constLocal : lambdaInstance->mConstLocals)
  13181. {
  13182. //if (constLocal.mIsThis)
  13183. {
  13184. // Valueless 'this'
  13185. closureState.mConstLocals.Add(constLocal);
  13186. }
  13187. /*else
  13188. {
  13189. auto localVar = new BfLocalVariable();
  13190. *localVar = constLocal;
  13191. DoAddLocalVariable(localVar);
  13192. }*/
  13193. }
  13194. BfMethodInstanceGroup methodInstanceGroup;
  13195. methodInstanceGroup.mOwner = mCurTypeInstance;
  13196. methodInstanceGroup.mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  13197. bool doProcess = !mCompiler->mCanceling;
  13198. if (doProcess)
  13199. {
  13200. BP_ZONE_F("ProcessMethod lambdaInstance %s", lambdaInstance->mMethodInstance->mMethodDef->mName.c_str());
  13201. lambdaInstance->mMethodInstance->mMethodInstanceGroup = &methodInstanceGroup;
  13202. ProcessMethod(lambdaInstance->mMethodInstance);
  13203. if (lambdaInstance->mDtorMethodInstance != NULL)
  13204. {
  13205. lambdaInstance->mDtorMethodInstance->mMethodInstanceGroup = &methodInstanceGroup;
  13206. ProcessMethod(lambdaInstance->mDtorMethodInstance);
  13207. }
  13208. }
  13209. }
  13210. mSystem->CheckLockYield();
  13211. }
  13212. }
  13213. void BfModule::EmitGCMarkValue(BfTypedValue& thisValue, BfType* checkType, int memberDepth, int curOffset, HashSet<int>& objectOffsets, BfModuleMethodInstance markFromGCThreadMethodInstance)
  13214. {
  13215. if (checkType->IsComposite())
  13216. PopulateType(checkType, BfPopulateType_Data);
  13217. if (!checkType->WantsGCMarking())
  13218. return;
  13219. auto typeInstance = checkType->ToTypeInstance();
  13220. bool callMarkMethod = false;
  13221. // Call the actual marking method
  13222. if (memberDepth == 0)
  13223. {
  13224. // Don't call marking method on self
  13225. }
  13226. else if (checkType->IsObjectOrInterface())
  13227. {
  13228. if (!objectOffsets.Add(curOffset))
  13229. {
  13230. return;
  13231. }
  13232. callMarkMethod = true;
  13233. }
  13234. else if (checkType->IsSizedArray())
  13235. {
  13236. callMarkMethod = true;
  13237. }
  13238. else if (typeInstance != NULL)
  13239. {
  13240. typeInstance->mTypeDef->PopulateMemberSets();
  13241. BfMemberSetEntry* entry = NULL;
  13242. BfMethodDef* methodDef = NULL;
  13243. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(String(BF_METHODNAME_MARKMEMBERS), &entry))
  13244. {
  13245. methodDef = (BfMethodDef*)entry->mMemberDef;
  13246. if (methodDef->HasBody())
  13247. {
  13248. callMarkMethod = true;
  13249. }
  13250. }
  13251. }
  13252. if (callMarkMethod)
  13253. {
  13254. BfTypedValue markValue;
  13255. auto memberType = checkType;
  13256. if (memberType->IsObjectOrInterface())
  13257. memberType = mContext->mBfObjectType; // Just to avoid that extra cast for the call itself
  13258. auto memberPtrType = CreatePointerType(memberType);
  13259. if (curOffset == 0)
  13260. {
  13261. markValue = BfTypedValue(mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(memberPtrType)), memberType, true);
  13262. }
  13263. else
  13264. {
  13265. if (!thisValue.mType->IsPointer())
  13266. {
  13267. auto int8Type = GetPrimitiveType(BfTypeCode_UInt8);
  13268. auto int8PtrType = CreatePointerType(int8Type);
  13269. thisValue = BfTypedValue(mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(int8PtrType)), int8PtrType);
  13270. }
  13271. auto offsetValue = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, curOffset);
  13272. markValue = BfTypedValue(mBfIRBuilder->CreateBitCast(offsetValue, mBfIRBuilder->MapType(memberPtrType)), memberType, true);
  13273. }
  13274. EmitGCMarkValue(markValue, markFromGCThreadMethodInstance);
  13275. return;
  13276. }
  13277. auto methodDef = mCurMethodInstance->mMethodDef;
  13278. if (checkType->IsPayloadEnum())
  13279. {
  13280. for (auto& fieldInst : typeInstance->mFieldInstances)
  13281. {
  13282. if (!fieldInst.mIsEnumPayloadCase)
  13283. continue;
  13284. auto fieldDef = fieldInst.GetFieldDef();
  13285. EmitGCMarkValue(thisValue, fieldInst.mResolvedType, memberDepth + 1, curOffset, objectOffsets, markFromGCThreadMethodInstance);
  13286. }
  13287. return;
  13288. }
  13289. if (typeInstance == NULL)
  13290. return;
  13291. for (auto& fieldInst : typeInstance->mFieldInstances)
  13292. {
  13293. auto fieldDef = fieldInst.GetFieldDef();
  13294. if (fieldDef == NULL)
  13295. continue;
  13296. if (fieldDef->mIsStatic)
  13297. continue;
  13298. if (typeInstance == mCurTypeInstance)
  13299. {
  13300. // Note: we don't do method chaining when we are marking members of members. Theoretically this means
  13301. // we may be marking member values that can never contain a value anyway, but this is benign
  13302. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  13303. continue;
  13304. }
  13305. EmitGCMarkValue(thisValue, fieldInst.mResolvedType, memberDepth + 1, curOffset + fieldInst.mDataOffset, objectOffsets, markFromGCThreadMethodInstance);
  13306. }
  13307. if ((typeInstance->mBaseType != NULL) && (typeInstance->mBaseType != mContext->mBfObjectType))
  13308. {
  13309. EmitGCMarkValue(thisValue, typeInstance->mBaseType, memberDepth, curOffset, objectOffsets, markFromGCThreadMethodInstance);
  13310. }
  13311. }
  13312. void BfModule::EmitGCMarkMembers()
  13313. {
  13314. auto methodDef = mCurMethodInstance->mMethodDef;
  13315. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef, BfPopulateType_DataAndMethods);
  13316. BfModuleMethodInstance markFromGCThreadMethodInstance;
  13317. if (gcType != NULL)
  13318. markFromGCThreadMethodInstance = GetMethodByName(gcType->ToTypeInstance(), "Mark", 1);
  13319. if ((markFromGCThreadMethodInstance.mMethodInstance != NULL) && (!mCurMethodInstance->mIsUnspecialized))
  13320. {
  13321. if (mCurTypeInstance->IsBoxed())
  13322. {
  13323. // This already gets filled in by the normal boxed forwarding
  13324. }
  13325. else
  13326. {
  13327. auto thisValue = GetThis();
  13328. if (thisValue.IsSplat())
  13329. {
  13330. BfIRFunction func = mCurMethodInstance->mIRFunction;
  13331. int argIdx = 0;
  13332. std::function<void(BfType*)> checkTypeLambda = [&](BfType* checkType)
  13333. {
  13334. if (checkType->IsStruct())
  13335. {
  13336. auto checkTypeInstance = checkType->ToTypeInstance();
  13337. if (checkTypeInstance->mBaseType != NULL)
  13338. checkTypeLambda(checkTypeInstance->mBaseType);
  13339. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  13340. {
  13341. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  13342. if (fieldInstance->mDataIdx >= 0)
  13343. checkTypeLambda(fieldInstance->GetResolvedType());
  13344. }
  13345. }
  13346. else if (checkType->IsMethodRef())
  13347. {
  13348. BF_FATAL("Not handled");
  13349. }
  13350. else if (checkType->WantsGCMarking())
  13351. {
  13352. BfTypedValue markValue(mBfIRBuilder->GetArgument(argIdx), checkType);
  13353. EmitGCMarkValue(markValue, markFromGCThreadMethodInstance);
  13354. argIdx++;
  13355. }
  13356. };
  13357. checkTypeLambda(thisValue.mType);
  13358. }
  13359. else if (!methodDef->mIsStatic)
  13360. {
  13361. if ((mCurTypeInstance->mBaseType != NULL) && (!mCurTypeInstance->IsTypedPrimitive()) && (mCurTypeInstance->mBaseType->WantsGCMarking()))
  13362. {
  13363. BfModuleMethodInstance moduleMethodInst = GetMethodByName(mCurTypeInstance->mBaseType, BF_METHODNAME_MARKMEMBERS, 0, true);
  13364. if (moduleMethodInst)
  13365. {
  13366. auto methodBaseType = moduleMethodInst.mMethodInstance->GetOwner();
  13367. if (methodBaseType != mContext->mBfObjectType)
  13368. {
  13369. auto thisValue = GetThis();
  13370. auto baseValue = Cast(NULL, thisValue, methodBaseType, BfCastFlags_Explicit);
  13371. SizedArray<BfIRValue, 1> args;
  13372. if (moduleMethodInst.mMethodInstance->GetParamIsSplat(-1))
  13373. {
  13374. BfExprEvaluator exprEvaluator(this);
  13375. exprEvaluator.SplatArgs(baseValue, args);
  13376. }
  13377. else
  13378. {
  13379. args.push_back(baseValue.mValue);
  13380. }
  13381. mBfIRBuilder->CreateCall(moduleMethodInst.mFunc, args);
  13382. }
  13383. }
  13384. }
  13385. }
  13386. if (!methodDef->mIsStatic)
  13387. {
  13388. HashSet<int> objectOffsets;
  13389. EmitGCMarkValue(thisValue, mCurTypeInstance, 0, 0, objectOffsets, markFromGCThreadMethodInstance);
  13390. }
  13391. else
  13392. {
  13393. for (auto& fieldInst : mCurTypeInstance->mFieldInstances)
  13394. {
  13395. if (thisValue.IsSplat())
  13396. break;
  13397. auto fieldDef = fieldInst.GetFieldDef();
  13398. if (fieldDef == NULL)
  13399. continue;
  13400. if (fieldInst.mIsThreadLocal)
  13401. continue;
  13402. if (fieldDef->mIsStatic == methodDef->mIsStatic)
  13403. {
  13404. // For extensions, only handle these fields in the appropriate extension
  13405. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  13406. continue;
  13407. if (!fieldInst.mFieldIncluded)
  13408. continue;
  13409. auto fieldTypeInst = fieldInst.mResolvedType->ToTypeInstance();
  13410. if (fieldTypeInst != NULL)
  13411. {
  13412. auto fieldDef = fieldInst.GetFieldDef();
  13413. BfTypedValue markVal;
  13414. if (fieldDef->mIsConst)
  13415. continue;
  13416. if ((!fieldTypeInst->IsObjectOrInterface()) && (!fieldTypeInst->IsComposite()))
  13417. continue;
  13418. mBfIRBuilder->PopulateType(fieldTypeInst);
  13419. if (fieldTypeInst->IsValuelessType())
  13420. continue;
  13421. if ((fieldDef->mIsStatic) && (!fieldDef->mIsConst))
  13422. {
  13423. markVal = ReferenceStaticField(&fieldInst);
  13424. }
  13425. else if (!fieldDef->mIsStatic)
  13426. {
  13427. markVal = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInst.mDataIdx/*, fieldDef->mName*/), fieldInst.mResolvedType, true);
  13428. }
  13429. if (markVal)
  13430. EmitGCMarkValue(markVal, markFromGCThreadMethodInstance);
  13431. }
  13432. }
  13433. }
  13434. }
  13435. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  13436. CallChainedMethods(mCurMethodInstance, false);
  13437. }
  13438. }
  13439. }
  13440. void BfModule::EmitGCFindTLSMembers()
  13441. {
  13442. auto methodDef = mCurMethodInstance->mMethodDef;
  13443. auto gcTypeInst = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  13444. auto reportTLSMark = GetMethodByName(gcTypeInst, "ReportTLSMember", 2);
  13445. BF_ASSERT(reportTLSMark);
  13446. for (auto& fieldInst : mCurTypeInstance->mFieldInstances)
  13447. {
  13448. auto fieldDef = fieldInst.GetFieldDef();
  13449. if (fieldDef == NULL)
  13450. continue;
  13451. if (!fieldInst.mIsThreadLocal)
  13452. continue;
  13453. // For extensions, only handle these fields in the appropriate extension
  13454. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  13455. continue;
  13456. if (!fieldInst.mFieldIncluded)
  13457. continue;
  13458. if (fieldDef->mIsConst)
  13459. continue;
  13460. auto fieldType = fieldInst.mResolvedType;
  13461. if ((!fieldType->IsObjectOrInterface()) && (!fieldType->IsComposite()))
  13462. continue;
  13463. if (fieldType->IsValuelessType())
  13464. continue;
  13465. BfTypedValue markVal = ReferenceStaticField(&fieldInst);
  13466. if (markVal)
  13467. {
  13468. BfIRValue fieldRefPtr = mBfIRBuilder->CreateBitCast(markVal.mValue, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  13469. BfIRValue markFuncPtr = GetMarkFuncPtr(fieldType);
  13470. SizedArray<BfIRValue, 2> llvmArgs;
  13471. llvmArgs.push_back(fieldRefPtr);
  13472. llvmArgs.push_back(markFuncPtr);
  13473. mBfIRBuilder->CreateCall(reportTLSMark.mFunc, llvmArgs);
  13474. }
  13475. }
  13476. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  13477. CallChainedMethods(mCurMethodInstance, false);
  13478. }
  13479. void BfModule::ProcessMethod(BfMethodInstance* methodInstance, bool isInlineDup)
  13480. {
  13481. BP_ZONE_F("BfModule::ProcessMethod %s", BP_DYN_STR(methodInstance->mMethodDef->mName.c_str()));
  13482. if (mAwaitingInitFinish)
  13483. FinishInit();
  13484. if (!methodInstance->mIsReified)
  13485. BF_ASSERT(!mIsReified);
  13486. if (methodInstance->mMethodInfoEx != NULL)
  13487. {
  13488. for (auto methodGenericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  13489. {
  13490. if (methodGenericArg->IsMethodRef())
  13491. {
  13492. auto methodRefType = (BfMethodRefType*)methodGenericArg;
  13493. BF_ASSERT(methodRefType->mOwnerRevision == methodRefType->mOwner->mRevision);
  13494. }
  13495. }
  13496. }
  13497. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mWantsIRIgnoreWrites || methodInstance->mIsUnspecialized);
  13498. bool ignoreWrites = mBfIRBuilder->mIgnoreWrites;
  13499. if ((HasCompiledOutput()) && (!mBfIRBuilder->mIgnoreWrites))
  13500. {
  13501. BF_ASSERT(!methodInstance->mIRFunction.IsFake() || (methodInstance->GetImportCallKind() != BfImportCallKind_None));
  13502. }
  13503. SetAndRestoreValue<BfSourceClassifier*> prevSourceClassifier;
  13504. if (((methodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend) || (methodInstance->mIsForeignMethodDef) || (methodInstance->IsSpecializedGenericMethod())) &&
  13505. (mCompiler->mResolvePassData != NULL))
  13506. {
  13507. // Don't classify on the CtorCalcAppend, just on the actual Ctor
  13508. prevSourceClassifier.Init(mCompiler->mResolvePassData->mSourceClassifier, NULL);
  13509. }
  13510. if (methodInstance->mHasBeenProcessed)
  13511. {
  13512. BfLogSysM("ProcessMethod %p HasBeenProcessed\n", methodInstance);
  13513. return;
  13514. }
  13515. if (methodInstance->mFailedConstraints)
  13516. {
  13517. // The only way this should be able to happen is if we fail our generic param check
  13518. BF_ASSERT(methodInstance->IsSpecializedGenericMethod());
  13519. BfLogSysM("Method instance marked as 'failed' at start of ProcessMethod %p\n", methodInstance);
  13520. methodInstance->mHasBeenProcessed = true;
  13521. return;
  13522. }
  13523. BfMethodInstance* defaultMethodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  13524. BF_ASSERT(methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_NotSet);
  13525. if ((methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_AlwaysInclude) &&
  13526. (methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_Referenced))
  13527. {
  13528. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Referenced;
  13529. auto owningModule = methodInstance->GetOwner()->mModule;
  13530. if (owningModule->mIsScratchModule)
  13531. {
  13532. BF_ASSERT(owningModule->mOnDemandMethodCount == 0);
  13533. }
  13534. else
  13535. {
  13536. BF_ASSERT((owningModule->mOnDemandMethodCount > 0) || (!HasCompiledOutput()) || (owningModule->mExtensionCount > 0));
  13537. if (owningModule->mOnDemandMethodCount > 0)
  13538. owningModule->mOnDemandMethodCount--;
  13539. }
  13540. }
  13541. // We set mHasBeenProcessed to true immediately -- this helps avoid stack overflow during recursion for things like
  13542. // self-referencing append allocations in ctor@calcAppend
  13543. methodInstance->mHasBeenProcessed = true;
  13544. mIncompleteMethodCount--;
  13545. BF_ASSERT((mIsSpecialModule) || (mIncompleteMethodCount >= 0));
  13546. auto typeDef = methodInstance->mMethodInstanceGroup->mOwner->mTypeDef;
  13547. auto methodDef = methodInstance->mMethodDef;
  13548. auto methodDeclaration = methodDef->GetMethodDeclaration();
  13549. if ((methodInstance->mIsReified) && (methodInstance->mVirtualTableIdx != -1))
  13550. {
  13551. // If we reify a virtual method in a HotCompile then we need to make sure the type data gets written out
  13552. // so we get the new vdata for it
  13553. methodInstance->GetOwner()->mDirty = true;
  13554. }
  13555. int dependentGenericStartIdx = 0;
  13556. if (methodDef->mIsLocalMethod) // See DoMethodDeclaration for an explaination of dependentGenericStartIdx
  13557. dependentGenericStartIdx = (int)mCurMethodState->GetRootMethodState()->mMethodInstance->GetNumGenericArguments();
  13558. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  13559. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, methodInstance->mMethodInstanceGroup->mOwner);
  13560. SetAndRestoreValue<BfFilePosition> prevFilePos(mCurFilePosition);
  13561. SetAndRestoreValue<bool> prevHadBuildError(mHadBuildError, false);
  13562. SetAndRestoreValue<bool> prevHadWarning(mHadBuildWarning, false);
  13563. SetAndRestoreValue<bool> prevIgnoreWarnings(mIgnoreWarnings, false);
  13564. if ((methodInstance->mIsReified) &&
  13565. ((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorNoBody)))
  13566. {
  13567. mCurTypeInstance->mHasBeenInstantiated = true;
  13568. }
  13569. // Warnings are shown in the capture phase
  13570. if ((methodDef->mIsLocalMethod) || (mCurTypeInstance->IsClosure()))
  13571. mIgnoreWarnings = true;
  13572. if ((methodDeclaration == NULL) && (mCurMethodState == NULL))
  13573. UseDefaultSrcPos();
  13574. // We may not actually be populated in relatively rare autocompelte cases
  13575. PopulateType(mCurTypeInstance, BfPopulateType_DataAndMethods);
  13576. mBfIRBuilder->PopulateType(mCurTypeInstance, BfIRPopulateType_Full);
  13577. BfAstNode* nameNode = NULL;
  13578. if (methodDeclaration != NULL)
  13579. {
  13580. nameNode = methodDeclaration->mNameNode;
  13581. if (nameNode == NULL)
  13582. {
  13583. if (auto ctorDeclaration = BfNodeDynCast<BfConstructorDeclaration>(methodDeclaration))
  13584. nameNode = ctorDeclaration->mThisToken;
  13585. }
  13586. }
  13587. if ((mCompiler->mResolvePassData != NULL) && (methodDeclaration != NULL) && (nameNode != NULL) &&
  13588. (mCompiler->mResolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Method) && (methodDef->mIdx >= 0))
  13589. {
  13590. if (methodInstance->GetExplicitInterface() == NULL)
  13591. mCompiler->mResolvePassData->HandleMethodReference(nameNode, typeDef, methodDef);
  13592. else
  13593. {
  13594. for (auto& ifaceEntry : mCurTypeInstance->mInterfaces)
  13595. {
  13596. auto ifaceInst = ifaceEntry.mInterfaceType;
  13597. int startIdx = ifaceEntry.mStartInterfaceTableIdx;
  13598. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  13599. if (methodInstance->GetExplicitInterface() != ifaceInst)
  13600. continue;
  13601. ifaceInst->mTypeDef->PopulateMemberSets();
  13602. BfMethodDef* nextMethod = NULL;
  13603. BfMemberSetEntry* entry = NULL;
  13604. if (ifaceInst->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  13605. nextMethod = (BfMethodDef*)entry->mMemberDef;
  13606. while (nextMethod != NULL)
  13607. {
  13608. auto checkMethod = nextMethod;
  13609. nextMethod = nextMethod->mNextWithSameName;
  13610. BfMethodInstance* implMethodInst = mCurTypeInstance->mInterfaceMethodTable[startIdx + checkMethod->mIdx].mMethodRef;
  13611. if (implMethodInst == methodInstance)
  13612. {
  13613. auto ifaceMethodDef = ifaceInst->mTypeDef->mMethods[checkMethod->mIdx];
  13614. mCompiler->mResolvePassData->HandleMethodReference(nameNode, ifaceInst->mTypeDef, ifaceMethodDef);
  13615. }
  13616. }
  13617. }
  13618. }
  13619. if (methodDef->mIsOverride)
  13620. {
  13621. for (int virtIdx = 0; virtIdx < (int)mCurTypeInstance->mVirtualMethodTable.size(); virtIdx++)
  13622. {
  13623. auto& ventry = mCurTypeInstance->mVirtualMethodTable[virtIdx];
  13624. if (ventry.mDeclaringMethod.mMethodNum == -1)
  13625. continue;
  13626. BfMethodInstance* virtMethod = ventry.mImplementingMethod;
  13627. if (virtMethod != NULL)
  13628. {
  13629. if (virtMethod == methodInstance)
  13630. {
  13631. // Is matching method
  13632. if (virtIdx < (int)mCurTypeInstance->mBaseType->mVirtualMethodTable.size())
  13633. {
  13634. auto baseType = mCurTypeInstance->mBaseType;
  13635. if (baseType != NULL)
  13636. {
  13637. while ((baseType->mBaseType != NULL) && (virtIdx < baseType->mBaseType->mVirtualMethodTableSize))
  13638. baseType = baseType->mBaseType;
  13639. BfMethodInstance* baseVirtMethod = baseType->mVirtualMethodTable[virtIdx].mImplementingMethod;
  13640. mCompiler->mResolvePassData->HandleMethodReference(nameNode, baseType->mTypeDef, baseVirtMethod->mMethodDef);
  13641. }
  13642. }
  13643. break;
  13644. }
  13645. }
  13646. }
  13647. }
  13648. }
  13649. BfLogSysM("ProcessMethod %p Unspecialized: %d Module: %p IRFunction: %d Reified: %d\n", methodInstance, mCurTypeInstance->IsUnspecializedType(), this, methodInstance->mIRFunction.mId, methodInstance->mIsReified);
  13650. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  13651. {
  13652. if (mBfIRBuilder->mIgnoreWrites)
  13653. return;
  13654. BfLogSysM("DllImportGlobalVar processing %p\n", methodInstance);
  13655. if (!methodInstance->mIRFunction)
  13656. {
  13657. BfIRValue dllImportGlobalVar = CreateDllImportGlobalVar(methodInstance, true);
  13658. methodInstance->mIRFunction = mBfIRBuilder->GetFakeVal();
  13659. mFuncReferences[mCurMethodInstance] = dllImportGlobalVar;
  13660. }
  13661. if (HasCompiledOutput())
  13662. {
  13663. BfDllImportEntry dllImportEntry;
  13664. dllImportEntry.mFuncVar = methodInstance->mIRFunction;
  13665. dllImportEntry.mMethodInstance = mCurMethodInstance;
  13666. mDllImportEntries.push_back(dllImportEntry);
  13667. }
  13668. return;
  13669. }
  13670. StringT<128> mangledName;
  13671. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  13672. if (!methodInstance->mIRFunction)
  13673. {
  13674. bool isIntrinsic = false;
  13675. SetupIRFunction(methodInstance, mangledName, false, &isIntrinsic);
  13676. }
  13677. if (methodInstance->mIsIntrinsic)
  13678. return;
  13679. auto prevActiveFunction = mBfIRBuilder->GetActiveFunction();
  13680. mBfIRBuilder->SetActiveFunction(mCurMethodInstance->mIRFunction);
  13681. if (methodDef->mBody != NULL)
  13682. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  13683. else if (methodDeclaration != NULL)
  13684. UpdateSrcPos(methodDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  13685. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  13686. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  13687. if (mCurMethodState == NULL) // Only do initial classify for the 'outer' method state, not any local methods or lambdas
  13688. {
  13689. if ((mCompiler->mIsResolveOnly) && (methodDef->mBody != NULL) && (!mCurTypeInstance->IsBoxed()) &&
  13690. (methodDef->mBody->IsFromParser(mCompiler->mResolvePassData->mParser)) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  13691. {
  13692. mCompiler->mResolvePassData->mSourceClassifier->VisitChildNoRef(methodDef->mBody);
  13693. }
  13694. }
  13695. BfHotDataReferenceBuilder hotDataReferenceBuilder;
  13696. BfMethodState methodState;
  13697. if (mCurMethodState != NULL)
  13698. methodState.mClosureState = mCurMethodState->mClosureState;
  13699. if ((mCompiler->mOptions.mAllowHotSwapping) && (methodInstance->mIsReified) && (!methodInstance->mIsUnspecialized) && (!isInlineDup))
  13700. {
  13701. //BF_ASSERT(methodInstance->mHotMethod != NULL);
  13702. if (methodInstance->mHotMethod == NULL)
  13703. CheckHotMethod(methodInstance, mangledName);
  13704. methodState.mHotDataReferenceBuilder = &hotDataReferenceBuilder;
  13705. }
  13706. methodState.mPrevMethodState = mCurMethodState;
  13707. methodState.mMethodInstance = methodInstance;
  13708. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  13709. if (methodInstance->GetCustomAttributes() != NULL)
  13710. {
  13711. int typeOptionsIdx = GenerateTypeOptions(methodInstance->GetCustomAttributes(), mCurTypeInstance, false);
  13712. if (typeOptionsIdx != -1)
  13713. methodState.mMethodTypeOptions = mSystem->GetTypeOptions(typeOptionsIdx);
  13714. }
  13715. BfTypeState typeState(mCurTypeInstance);
  13716. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  13717. bool isGenericVariation = (methodInstance->mIsUnspecializedVariation) || (mCurTypeInstance->IsUnspecializedTypeVariation());
  13718. BfMethodInstance* unspecializedMethodInstance = NULL;
  13719. if ((prevMethodState.mPrevVal != NULL) &&
  13720. ((methodState.mClosureState == NULL) || (methodState.mClosureState->mActiveDeferredLocalMethod == NULL)))
  13721. {
  13722. // This is 'inner' (probably a closure) - use binding from outer function
  13723. methodState.mGenericTypeBindings = prevMethodState.mPrevVal->mGenericTypeBindings;
  13724. }
  13725. else if ((methodInstance->mIsUnspecialized) ||
  13726. ((mCurTypeInstance->IsUnspecializedType()) && (!isGenericVariation)))
  13727. {
  13728. methodState.mGenericTypeBindings = &methodInstance->GetMethodInfoEx()->mGenericTypeBindings;
  13729. }
  13730. else if ((((methodInstance->mMethodInfoEx != NULL) && ((int)methodInstance->mMethodInfoEx->mMethodGenericArguments.size() > dependentGenericStartIdx)) ||
  13731. ((mCurTypeInstance->IsGenericTypeInstance()) && (!isGenericVariation))))
  13732. {
  13733. unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance);
  13734. BF_ASSERT(unspecializedMethodInstance != methodInstance);
  13735. if (!unspecializedMethodInstance->mHasBeenProcessed)
  13736. {
  13737. // Make sure the unspecialized method is processed so we can take its bindings
  13738. // Clear mCurMethodState so we don't think we're in a local method
  13739. SetAndRestoreValue<BfMethodState*> prevMethodState_Unspec(mCurMethodState, prevMethodState.mPrevVal);
  13740. mContext->ProcessMethod(unspecializedMethodInstance);
  13741. }
  13742. methodState.mGenericTypeBindings = &unspecializedMethodInstance->GetMethodInfoEx()->mGenericTypeBindings;
  13743. }
  13744. if (methodDef->mMethodType == BfMethodType_Operator)
  13745. {
  13746. auto operatorDef = (BfOperatorDef*) methodDef;
  13747. BfAstNode* refNode = operatorDef->mOperatorDeclaration->mOperatorToken;
  13748. auto paramErrorRefNode = refNode;
  13749. if (operatorDef->mOperatorDeclaration->mOpenParen != NULL)
  13750. paramErrorRefNode = operatorDef->mOperatorDeclaration->mOpenParen;
  13751. if ((mCurMethodInstance->GetParamCount() > 0) && (mCurMethodInstance->GetParamTypeRef(0) != NULL))
  13752. paramErrorRefNode = mCurMethodInstance->GetParamTypeRef(0);
  13753. if (operatorDef->mOperatorDeclaration->mBinOp != BfBinaryOp_None)
  13754. {
  13755. if (methodDef->mParams.size() != 2)
  13756. {
  13757. Fail("Binary operators must declare two parameters", paramErrorRefNode);
  13758. }
  13759. else
  13760. {
  13761. if ((mCurMethodInstance->GetParamType(0) != mCurTypeInstance) && (!mCurMethodInstance->GetParamType(0)->IsSelf()) &&
  13762. (mCurMethodInstance->GetParamType(1) != mCurTypeInstance) && (!mCurMethodInstance->GetParamType(1)->IsSelf()))
  13763. {
  13764. Fail("At least one of the parameters of a binary operator must be the containing type", paramErrorRefNode);
  13765. }
  13766. }
  13767. BfType* wantType = NULL;
  13768. if (operatorDef->mOperatorDeclaration->mBinOp == BfBinaryOp_Compare)
  13769. {
  13770. wantType = GetPrimitiveType(BfTypeCode_IntPtr);
  13771. }
  13772. if ((wantType != NULL) && (methodInstance->mReturnType != wantType))
  13773. Fail(StrFormat("The return type for the '%s' operator must be '%s'", BfGetOpName(operatorDef->mOperatorDeclaration->mBinOp),
  13774. TypeToString(wantType).c_str()), operatorDef->mOperatorDeclaration->mReturnType);
  13775. }
  13776. else if (operatorDef->mOperatorDeclaration->mUnaryOp != BfUnaryOp_None)
  13777. {
  13778. if (methodDef->mParams.size() != 1)
  13779. {
  13780. Fail("Unary operators must declare one parameter", paramErrorRefNode);
  13781. }
  13782. else if ((mCurMethodInstance->GetParamType(0) != mCurTypeInstance) && (!mCurMethodInstance->GetParamType(0)->IsSelf()))
  13783. {
  13784. Fail("The parameter of a unary operator must be the containing type", paramErrorRefNode);
  13785. }
  13786. if (((operatorDef->mOperatorDeclaration->mUnaryOp == BfUnaryOp_Increment) ||
  13787. (operatorDef->mOperatorDeclaration->mUnaryOp == BfUnaryOp_Decrement)) &&
  13788. (!TypeIsSubTypeOf(mCurMethodInstance->mReturnType->ToTypeInstance(), mCurTypeInstance)))
  13789. {
  13790. Fail("The return type for the '++' or '--' operator must match the parameter type or be derived from the parameter type", operatorDef->mOperatorDeclaration->mReturnType);
  13791. }
  13792. }
  13793. else if (operatorDef->mOperatorDeclaration->mAssignOp != BfAssignmentOp_None)
  13794. {
  13795. if (methodDef->mParams.size() != 1)
  13796. {
  13797. Fail("Assignment operators must declare one parameter", paramErrorRefNode);
  13798. }
  13799. if (mCurMethodInstance->mReturnType->IsVoid())
  13800. {
  13801. Fail("The return type for assignment operator must be 'void'", operatorDef->mOperatorDeclaration->mReturnType);
  13802. }
  13803. }
  13804. else // Conversion
  13805. {
  13806. if (!operatorDef->mOperatorDeclaration->mIsConvOperator)
  13807. {
  13808. if (operatorDef->mOperatorDeclaration->mReturnType != NULL)
  13809. Fail("Conversion operators must declare their target type after the 'operator' token, not before", operatorDef->mOperatorDeclaration->mReturnType);
  13810. }
  13811. if (methodDef->mParams.size() != 1)
  13812. {
  13813. auto refNode = paramErrorRefNode;
  13814. if (!operatorDef->mOperatorDeclaration->mCommas.empty())
  13815. refNode = operatorDef->mOperatorDeclaration->mCommas[0];
  13816. Fail("Conversion operators must declare one parameter", refNode);
  13817. }
  13818. else
  13819. {
  13820. if ((mCurMethodInstance->GetParamType(0) != mCurTypeInstance) && (!mCurMethodInstance->GetParamType(0)->IsSelf()) &&
  13821. (mCurMethodInstance->mReturnType != mCurTypeInstance) && (!mCurMethodInstance->mReturnType->IsSelf()))
  13822. Fail("User-defined conversion must convert to or from the enclosing type", paramErrorRefNode);
  13823. if (mCurMethodInstance->GetParamType(0) == mCurMethodInstance->mReturnType)
  13824. Fail("User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type", operatorDef->mOperatorDeclaration->mReturnType);
  13825. // On type lookup error we default to 'object', so don't do the 'base class' error if that may have
  13826. // happened here
  13827. if ((!mHadBuildError) || ((mCurMethodInstance->mReturnType != mContext->mBfObjectType) && (mCurMethodInstance->GetParamType(0) != mContext->mBfObjectType)))
  13828. {
  13829. auto isToBase = TypeIsSubTypeOf(mCurTypeInstance->mBaseType, mCurMethodInstance->mReturnType->ToTypeInstance());
  13830. bool isFromBase = TypeIsSubTypeOf(mCurTypeInstance->mBaseType, mCurMethodInstance->GetParamType(0)->ToTypeInstance());
  13831. if ((mCurTypeInstance->IsObject()) && (isToBase || isFromBase))
  13832. Fail("User-defined conversions to or from a base class are not allowed", paramErrorRefNode);
  13833. else if ((mCurTypeInstance->IsStruct()) && (isToBase))
  13834. Fail("User-defined conversions to a base struct are not allowed", paramErrorRefNode);
  13835. }
  13836. }
  13837. }
  13838. }
  13839. bool wantsDIData = (mBfIRBuilder->DbgHasInfo()) && (!methodDef->IsEmptyPartial()) && (!mCurMethodInstance->mIsUnspecialized) && (mHasFullDebugInfo);
  13840. if (methodDef->mMethodType == BfMethodType_Mixin)
  13841. wantsDIData = false;
  13842. if ((mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType != BfMethodType_Ctor))
  13843. wantsDIData = false;
  13844. bool wantsDIVariables = wantsDIData;
  13845. if (methodDef->mIsExtern)
  13846. wantsDIVariables = false;
  13847. SizedArray<BfIRMDNode, 8> diParams;
  13848. diParams.push_back(mBfIRBuilder->DbgGetType(methodInstance->mReturnType));
  13849. bool isThisStruct = mCurTypeInstance->IsStruct() && !mCurTypeInstance->IsTypedPrimitive();
  13850. BfType* thisType = NULL;
  13851. if (!methodDef->mIsStatic)
  13852. {
  13853. if ((methodState.mClosureState != NULL) && (methodState.mClosureState->mClosureType != NULL))
  13854. thisType = methodState.mClosureState->mClosureType;
  13855. else
  13856. thisType = mCurTypeInstance;
  13857. }
  13858. PopulateType(methodInstance->mReturnType, BfPopulateType_Data);
  13859. ProcessMethod_SetupParams(methodInstance, thisType, wantsDIData, &diParams);
  13860. //////////////////////////////////////////////////////////////////////////
  13861. //
  13862. {
  13863. if (methodDeclaration != NULL)
  13864. UpdateSrcPos(methodDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  13865. else if (methodDef->mBody != NULL)
  13866. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  13867. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  13868. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  13869. }
  13870. BfIRMDNode diFunction;
  13871. if (wantsDIData)
  13872. {
  13873. BP_ZONE("BfModule::BfMethodDeclaration.DISetup");
  13874. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParams);
  13875. int defLine = mCurFilePosition.mCurLine;
  13876. if (mDICompileUnit)
  13877. {
  13878. int flags = 0;
  13879. BfIRMDNode funcScope = mBfIRBuilder->DbgGetTypeInst(mCurTypeInstance);
  13880. if (methodDef->mProtection == BfProtection_Public)
  13881. flags = llvm::DINode::FlagPublic;
  13882. else if (methodDef->mProtection == BfProtection_Protected)
  13883. flags = llvm::DINode::FlagProtected;
  13884. else
  13885. flags = llvm::DINode::FlagPrivate;
  13886. if (methodDef->mIsOverride)
  13887. {
  13888. //flags |= llvm::DINode::FlagVirtual;
  13889. }
  13890. else if (methodDef->mIsVirtual)
  13891. flags |= llvm::DINode::FlagIntroducedVirtual;
  13892. if ((methodDef->mIsStatic) || (methodDef->mMethodType == BfMethodType_Mixin))
  13893. flags |= llvm::DINode::FlagStaticMember;
  13894. else
  13895. {
  13896. if ((mCurTypeInstance->IsValuelessType()) || (mCurTypeInstance->IsSplattable()))
  13897. flags |= llvm::DINode::FlagStaticMember;
  13898. }
  13899. flags |= llvm::DINode::FlagPrototyped;
  13900. if (methodDef->mMethodType == BfMethodType_Ctor)
  13901. {
  13902. flags |= llvm::DINode::FlagArtificial;
  13903. }
  13904. auto llvmFunction = methodInstance->mIRFunction;
  13905. SizedArray<BfIRMDNode, 1> genericArgs;
  13906. SizedArray<BfIRValue, 1> genericConstValueArgs;
  13907. String methodName;
  13908. if (methodInstance->GetForeignType() != NULL)
  13909. {
  13910. methodName += TypeToString(methodInstance->GetForeignType());
  13911. methodName += ".";
  13912. }
  13913. if (methodInstance->GetExplicitInterface() != NULL)
  13914. {
  13915. methodName += TypeToString(methodInstance->GetExplicitInterface());
  13916. methodName += ".";
  13917. }
  13918. methodName += methodDef->mName;
  13919. if (methodInstance->GetNumGenericArguments() != 0)
  13920. {
  13921. for (auto genericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  13922. {
  13923. if (genericArg->IsConstExprValue())
  13924. {
  13925. BfConstExprValueType* constExprValueType = (BfConstExprValueType*)genericArg;
  13926. while (genericConstValueArgs.size() < genericArgs.size())
  13927. genericConstValueArgs.push_back(BfIRValue());
  13928. genericConstValueArgs.push_back(mBfIRBuilder->CreateConst(BfTypeCode_UInt64, constExprValueType->mValue.mUInt64));
  13929. genericArgs.push_back(mBfIRBuilder->DbgGetType(GetPrimitiveType(BfTypeCode_Int64)));
  13930. }
  13931. else
  13932. genericArgs.push_back(mBfIRBuilder->DbgGetType(genericArg));
  13933. }
  13934. methodName += "<";
  13935. for (int i = 0; i < (int)methodInstance->mMethodInfoEx->mMethodGenericArguments.size(); i++)
  13936. {
  13937. if (i > 0)
  13938. methodName += ", ";
  13939. BfType* type = methodInstance->mMethodInfoEx->mMethodGenericArguments[i];
  13940. methodName += TypeToString(type);
  13941. }
  13942. methodName += ">";
  13943. }
  13944. if ((methodName.empty()) && (methodDeclaration != NULL))
  13945. {
  13946. if (auto operatorDecl = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  13947. {
  13948. methodName += "operator";
  13949. if (operatorDecl->mIsConvOperator)
  13950. {
  13951. methodName += " ";
  13952. methodName += TypeToString(methodInstance->mReturnType);
  13953. }
  13954. else if (operatorDecl->mOpTypeToken != NULL)
  13955. methodName += operatorDecl->mOpTypeToken->ToString();
  13956. }
  13957. }
  13958. methodState.mDIFile = mCurFilePosition.mFileInstance->mDIFile;
  13959. // diFunction = mBfIRBuilder->DbgCreateMethod(funcScope, methodName, mangledName, methodState.mDIFile,
  13960. // defLine + 1, diFuncType, false, true,
  13961. // (methodInstance->mVirtualTableIdx != -1) ? llvm::dwarf::DW_VIRTUALITY_virtual : llvm::dwarf::DW_VIRTUALITY_none,
  13962. // (methodInstance->mVirtualTableIdx != -1) ? methodInstance->DbgGetVirtualMethodNum() : 0,
  13963. // nullptr, flags, IsOptimized(), llvmFunction, genericArgs, genericConstValueArgs);
  13964. diFunction = mBfIRBuilder->DbgCreateMethod(funcScope, methodName, mangledName, methodState.mDIFile,
  13965. defLine + 1, diFuncType, false, true,
  13966. llvm::dwarf::DW_VIRTUALITY_none,
  13967. 0,
  13968. nullptr, flags, IsOptimized(), llvmFunction, genericArgs, genericConstValueArgs);
  13969. }
  13970. }
  13971. //////////////////////////////////////////////////////////////////////////
  13972. // Head and Init get rolled into Entry afterwards.
  13973. methodState.mIRFunction = methodInstance->mIRFunction;
  13974. methodState.mIRHeadBlock = mBfIRBuilder->CreateBlock("head", true);
  13975. methodState.mIRInitBlock = mBfIRBuilder->CreateBlock("init", true);
  13976. methodState.mIREntryBlock = mBfIRBuilder->CreateBlock("entry", true);
  13977. methodState.mCurScope->mDIScope = diFunction;
  13978. auto llvmEntryBlock = methodState.mIREntryBlock;
  13979. mBfIRBuilder->SetInsertPoint(llvmEntryBlock);
  13980. if (methodDef->mBody != NULL)
  13981. {
  13982. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  13983. }
  13984. else if ((mHasFullDebugInfo) && (diFunction) && (typeDef->mTypeDeclaration != NULL))
  13985. {
  13986. // We want to be able to step into delegate invokes -- we actually step over them
  13987. if (methodDef->mName != "Invoke")
  13988. {
  13989. UpdateSrcPos(typeDef->mTypeDeclaration);
  13990. mBfIRBuilder->DbgCreateAnnotation(diFunction, "StepOver", GetConstValue32(1));
  13991. }
  13992. }
  13993. // Clear out DebugLoc - to mark the ".addr" code as part of prologue
  13994. mBfIRBuilder->ClearDebugLocation();
  13995. bool isTypedPrimitiveFunc = mCurTypeInstance->IsTypedPrimitive() && (methodDef->mMethodType != BfMethodType_Ctor);
  13996. int irParamCount = methodInstance->GetIRFunctionParamCount(this);
  13997. if (methodDef->mImportKind != BfImportKind_Dynamic)
  13998. {
  13999. int localIdx = 0;
  14000. int argIdx = 0;
  14001. if (methodInstance->HasStructRet())
  14002. argIdx++;
  14003. //
  14004. bool doDbgAgg = false;
  14005. Array<BfIRValue> splatAddrValues;
  14006. for ( ; argIdx < irParamCount; localIdx++)
  14007. {
  14008. bool isThis = ((localIdx == 0) && (!mCurMethodInstance->mMethodDef->mIsStatic));
  14009. if ((isThis) && (thisType->IsValuelessType()))
  14010. isThis = false;
  14011. BfLocalVariable* paramVar = NULL;
  14012. while (true)
  14013. {
  14014. BF_ASSERT(localIdx < methodState.mLocals.size());
  14015. paramVar = methodState.mLocals[localIdx];
  14016. if ((paramVar->mCompositeCount == -1) &&
  14017. ((!paramVar->mResolvedType->IsValuelessType()) || (paramVar->mResolvedType->IsMethodRef())))
  14018. break;
  14019. localIdx++;
  14020. }
  14021. if ((isThis) && (mCurTypeInstance->IsValueType()) && (methodDef->mMethodType != BfMethodType_Ctor) && (!methodDef->HasNoThisSplat()))
  14022. {
  14023. paramVar->mIsReadOnly = true;
  14024. }
  14025. bool wantsAddr = (wantsDIVariables) || (!paramVar->mIsReadOnly) || (paramVar->mResolvedType->GetLoweredType() != BfTypeCode_None);
  14026. if (paramVar->mResolvedType->IsMethodRef())
  14027. wantsAddr = false;
  14028. // if ((methodDef->mHasAppend) && (argIdx == 1))
  14029. // {
  14030. // BF_ASSERT(paramVar->mName == "appendIdx");
  14031. // wantsAddr = true;
  14032. // }
  14033. if ((!doDbgAgg) && (paramVar->mIsSplat))
  14034. {
  14035. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  14036. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  14037. BfTypeUtils::SplatIterate([&](BfType* checkType)
  14038. {
  14039. BfIRType splatIRType;
  14040. if (checkType->IsComposite())
  14041. splatIRType = mBfIRBuilder->MapType(CreatePointerType(checkType));
  14042. else
  14043. splatIRType = mBfIRBuilder->MapType(checkType);
  14044. auto allocaInst = mBfIRBuilder->CreateAlloca(splatIRType);
  14045. mBfIRBuilder->SetAllocaAlignment(allocaInst, checkType->mAlign);
  14046. if (!paramVar->mAddr)
  14047. paramVar->mAddr = allocaInst;
  14048. if (WantsLifetimes())
  14049. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  14050. splatAddrValues.push_back(allocaInst);
  14051. }, paramVar->mResolvedType);
  14052. mBfIRBuilder->SetInsertPoint(prevInsert);
  14053. }
  14054. else if (isThis)
  14055. {
  14056. if (wantsAddr)
  14057. {
  14058. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  14059. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  14060. BfIRType thisAddrType = mBfIRBuilder->MapType(thisType);
  14061. if (paramVar->mIsSplat)
  14062. {
  14063. if (doDbgAgg)
  14064. {
  14065. auto allocaInst = mBfIRBuilder->CreateAlloca(thisAddrType);
  14066. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  14067. mBfIRBuilder->SetAllocaAlignment(allocaInst, thisType->mAlign);
  14068. paramVar->mAddr = allocaInst;
  14069. if (WantsLifetimes())
  14070. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  14071. }
  14072. }
  14073. else
  14074. {
  14075. bool wantPtr = (thisType->IsComposite()) && (!paramVar->mIsLowered);
  14076. if ((thisType->IsTypedPrimitive()) && (methodDef->HasNoThisSplat()))
  14077. wantPtr = true;
  14078. if (wantPtr)
  14079. {
  14080. thisAddrType = mBfIRBuilder->MapTypeInstPtr(thisType->ToTypeInstance());
  14081. }
  14082. auto allocaInst = mBfIRBuilder->CreateAlloca(thisAddrType);
  14083. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  14084. mBfIRBuilder->SetAllocaAlignment(allocaInst, mSystem->mPtrSize);
  14085. paramVar->mAddr = allocaInst;
  14086. if (WantsLifetimes())
  14087. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  14088. }
  14089. mBfIRBuilder->SetInsertPoint(prevInsert);
  14090. }
  14091. }
  14092. else if ((!isThis) && ((paramVar->mIsStruct) || (paramVar->mResolvedType->IsRef())))
  14093. {
  14094. // Address doesn't change so we don't have to alloca it
  14095. BfIRType allocType;
  14096. int alignSize = mSystem->mPtrSize;
  14097. if (paramVar->mResolvedType->IsRef())
  14098. {
  14099. allocType = mBfIRBuilder->MapType(paramVar->mResolvedType);
  14100. }
  14101. else if ((paramVar->mIsSplat) || (paramVar->mIsLowered))
  14102. {
  14103. allocType = mBfIRBuilder->MapType(paramVar->mResolvedType);
  14104. alignSize = paramVar->mResolvedType->mAlign;
  14105. }
  14106. else
  14107. {
  14108. paramVar->mHasLocalStructBacking = true;
  14109. auto typeInst = paramVar->mResolvedType->ToTypeInstance();
  14110. if (typeInst != NULL)
  14111. allocType = mBfIRBuilder->MapTypeInstPtr(paramVar->mResolvedType->ToTypeInstance());
  14112. else
  14113. allocType = mBfIRBuilder->MapType(CreatePointerType(paramVar->mResolvedType));
  14114. }
  14115. if (wantsAddr)
  14116. {
  14117. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  14118. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  14119. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  14120. auto allocaInst = mBfIRBuilder->CreateAlloca(allocType);
  14121. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  14122. mBfIRBuilder->SetAllocaAlignment(allocaInst, alignSize);
  14123. paramVar->mAddr = allocaInst;
  14124. mBfIRBuilder->SetInsertPoint(prevInsert);
  14125. if (WantsLifetimes())
  14126. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  14127. }
  14128. }
  14129. else if (wantsAddr)
  14130. {
  14131. auto allocaInst = CreateAlloca(paramVar->mResolvedType);
  14132. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  14133. paramVar->mAddr = allocaInst;
  14134. }
  14135. if (paramVar->mIsSplat)
  14136. {
  14137. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  14138. }
  14139. else
  14140. {
  14141. argIdx++;
  14142. }
  14143. }
  14144. if (methodDef->mBody != NULL)
  14145. UpdateSrcPos(methodDef->mBody);
  14146. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  14147. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration);
  14148. int declArgIdx = 0;
  14149. localIdx = 0;
  14150. argIdx = 0;
  14151. if (methodInstance->HasStructRet())
  14152. argIdx++;
  14153. int splatAddrIdx = 0;
  14154. while (localIdx < (int)methodState.mLocals.size())
  14155. {
  14156. int curLocalIdx = localIdx++;
  14157. BfLocalVariable* paramVar = methodState.mLocals[curLocalIdx];
  14158. if (!paramVar->IsParam())
  14159. continue;
  14160. if (paramVar->mCompositeCount != -1)
  14161. continue;
  14162. bool isThis = ((curLocalIdx == 0) && (!mCurMethodInstance->mMethodDef->mIsStatic));
  14163. if ((isThis) && (thisType->IsValuelessType()))
  14164. isThis = false;
  14165. BfIRMDNode diVariable;
  14166. if (wantsDIData)
  14167. {
  14168. String paramName = paramVar->mName;
  14169. BfIRMDNode diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  14170. if (isThis)
  14171. {
  14172. if ((mCurMethodState->mClosureState != NULL) && (mCurMethodState->mClosureState->mClosureType != NULL))
  14173. paramName = "__closure";
  14174. if ((paramVar->mResolvedType->IsValueType()) && (!paramVar->mIsSplat) && (!paramVar->mIsLowered))
  14175. {
  14176. diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  14177. bool wantRef = paramVar->mResolvedType->IsComposite();
  14178. if ((paramVar->mResolvedType->IsTypedPrimitive()) && (methodDef->HasNoThisSplat()))
  14179. wantRef = true;
  14180. if (wantRef)
  14181. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  14182. }
  14183. else if (!paramVar->mResolvedType->IsValueType())
  14184. {
  14185. diType = mBfIRBuilder->DbgCreateArtificialType(diType);
  14186. }
  14187. }
  14188. else
  14189. {
  14190. if ((paramVar->mResolvedType->IsComposite()) && (!paramVar->mIsSplat) && (!paramVar->mIsLowered))
  14191. {
  14192. diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  14193. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  14194. diType = mBfIRBuilder->DbgCreateConstType(diType);
  14195. }
  14196. }
  14197. if ((!paramVar->mIsSplat) || (doDbgAgg))
  14198. {
  14199. if (paramVar->mResolvedType->IsValuelessType())
  14200. {
  14201. diVariable = mBfIRBuilder->DbgCreateAutoVariable(diFunction,
  14202. paramName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  14203. }
  14204. else if (paramVar->mIsImplicitParam)
  14205. {
  14206. // Annotate this specially?
  14207. diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  14208. paramName, argIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, true, 0);
  14209. }
  14210. else
  14211. {
  14212. diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  14213. paramName, argIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, true, 0);
  14214. }
  14215. paramVar->mDbgVarInst = diVariable;
  14216. }
  14217. else if ((paramVar->mIsSplat) && (paramVar->mResolvedType->GetSplatCount() == 0))
  14218. {
  14219. // if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables))
  14220. // {
  14221. // // Only add this placeholder if we don't have any values
  14222. // auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  14223. // paramName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  14224. // mBfIRBuilder->DbgInsertValueIntrinsic(GetConstValue(0), diVariable);
  14225. // }
  14226. }
  14227. }
  14228. bool isTypedPrimCtor = mCurTypeInstance->IsTypedPrimitive() && (methodDef->mMethodType == BfMethodType_Ctor);
  14229. if ((!paramVar->mParamFailed) && (paramVar->mAddr))
  14230. {
  14231. // Write our argument value into the .addr
  14232. mBfIRBuilder->ClearDebugLocation();
  14233. if (paramVar->mIsSplat)
  14234. {
  14235. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  14236. if (doDbgAgg)
  14237. {
  14238. auto curArgIdx = argIdx;
  14239. std::function<void(BfType*, BfIRValue)> checkTypeLambda = [&](BfType* checkType, BfIRValue curDestAddr)
  14240. {
  14241. if (checkType->IsStruct())
  14242. {
  14243. auto checkTypeInstance = checkType->ToTypeInstance();
  14244. if (checkTypeInstance->mBaseType != NULL)
  14245. {
  14246. auto baseDestAddr = mBfIRBuilder->CreateBitCast(curDestAddr, mBfIRBuilder->MapTypeInstPtr(checkTypeInstance->mBaseType));
  14247. checkTypeLambda(checkTypeInstance->mBaseType, baseDestAddr);
  14248. }
  14249. if (checkTypeInstance->mIsUnion)
  14250. {
  14251. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  14252. if (!unionInnerType->IsValuelessType())
  14253. {
  14254. auto newDestAddr = mBfIRBuilder->CreateInBoundsGEP(curDestAddr, 0, 1);
  14255. checkTypeLambda(unionInnerType, newDestAddr);
  14256. }
  14257. if (checkTypeInstance->IsEnum())
  14258. {
  14259. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  14260. auto newDestAddr = mBfIRBuilder->CreateInBoundsGEP(curDestAddr, 0, 2);
  14261. checkTypeLambda(dscrType, newDestAddr);
  14262. }
  14263. }
  14264. else
  14265. {
  14266. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  14267. {
  14268. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  14269. if (fieldInstance->mDataIdx >= 0)
  14270. {
  14271. auto newDestAddr = mBfIRBuilder->CreateInBoundsGEP(curDestAddr, 0, fieldInstance->mDataIdx);
  14272. checkTypeLambda(fieldInstance->GetResolvedType(), newDestAddr);
  14273. }
  14274. }
  14275. }
  14276. }
  14277. else if (checkType->IsMethodRef())
  14278. {
  14279. BF_FATAL("Unimplemented");
  14280. // BfMethodRefType* methodRefType = (BfMethodRefType*)checkType;
  14281. // for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  14282. // {
  14283. // checkTypeLambda->
  14284. // }
  14285. }
  14286. else if (!checkType->IsValuelessType())
  14287. {
  14288. mBfIRBuilder->CreateAlignedStore(mBfIRBuilder->GetArgument(curArgIdx), curDestAddr, paramVar->mResolvedType->mAlign);
  14289. curArgIdx++;
  14290. }
  14291. };
  14292. checkTypeLambda(paramVar->mResolvedType, paramVar->mAddr);
  14293. }
  14294. }
  14295. else
  14296. {
  14297. bool handled = false;
  14298. //if ((!isThis) || (!methodDef->mIsMutating && !methodDef->mNoSplat))
  14299. if (paramVar->mIsLowered)
  14300. {
  14301. auto loweredTypeCode = paramVar->mResolvedType->GetLoweredType();
  14302. BF_ASSERT(loweredTypeCode != BfTypeCode_None);
  14303. if (loweredTypeCode != BfTypeCode_None)
  14304. {
  14305. // We have a lowered type coming in, so we have to cast the .addr before storing
  14306. auto primType = GetPrimitiveType(loweredTypeCode);
  14307. auto primPtrType = CreatePointerType(primType);
  14308. auto primPtrVal = mBfIRBuilder->CreateBitCast(paramVar->mAddr, mBfIRBuilder->MapType(primPtrType));
  14309. mBfIRBuilder->CreateAlignedStore(paramVar->mValue, primPtrVal, paramVar->mResolvedType->mSize);
  14310. // We don't want to allow directly using value
  14311. paramVar->mValue = BfIRValue();
  14312. handled = true;
  14313. }
  14314. }
  14315. if (!handled)
  14316. mBfIRBuilder->CreateAlignedStore(paramVar->mValue, paramVar->mAddr, paramVar->mResolvedType->mAlign);
  14317. }
  14318. }
  14319. if (!isThis)
  14320. declArgIdx++;
  14321. if (methodDef->mBody != NULL)
  14322. UpdateSrcPos(methodDef->mBody);
  14323. else if (methodDef->mDeclaringType->mTypeDeclaration != NULL)
  14324. UpdateSrcPos(methodDef->mDeclaringType->mTypeDeclaration);
  14325. else if (methodDeclaration == NULL)
  14326. UseDefaultSrcPos();
  14327. // Write our argument value into the .addr
  14328. if ((!doDbgAgg) && (paramVar->mIsSplat))
  14329. {
  14330. int splatComponentIdx = 0;
  14331. auto curArgIdx = argIdx;
  14332. auto _FinishSplats = [&] (BfType* checkType, const StringImpl& name)
  14333. {
  14334. BfIRValue splatAddrValue = splatAddrValues[splatAddrIdx++];
  14335. methodState.mSplatDecompAddrs.push_back(splatAddrValue);
  14336. auto storeInst = mBfIRBuilder->CreateAlignedStore(mBfIRBuilder->GetArgument(curArgIdx), splatAddrValue, checkType->mAlign);
  14337. mBfIRBuilder->ClearDebugLocation(storeInst);
  14338. if (wantsDIData)
  14339. {
  14340. BfIRMDNode diType;
  14341. if (checkType->IsComposite())
  14342. diType = mBfIRBuilder->DbgGetType(CreateRefType(checkType));
  14343. else
  14344. diType = mBfIRBuilder->DbgGetType(checkType);
  14345. auto diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  14346. name, curArgIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  14347. if (wantsDIVariables)
  14348. {
  14349. mBfIRBuilder->DbgInsertDeclare(splatAddrValue, diVariable);
  14350. }
  14351. }
  14352. curArgIdx++;
  14353. splatComponentIdx++;
  14354. };
  14355. std::function<void(BfType*, const StringImpl&)> _FinishSplatsIterate = [&](BfType* checkType, const StringImpl& name)
  14356. {
  14357. if (checkType->IsStruct())
  14358. {
  14359. auto checkTypeInstance = checkType->ToTypeInstance();
  14360. if (checkTypeInstance->mBaseType != NULL)
  14361. {
  14362. _FinishSplatsIterate(checkTypeInstance->mBaseType, name + "$b");
  14363. }
  14364. if (checkTypeInstance->mIsUnion)
  14365. {
  14366. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  14367. if (!unionInnerType->IsValuelessType())
  14368. {
  14369. _FinishSplatsIterate(unionInnerType, name + "$u");
  14370. }
  14371. if (checkTypeInstance->IsEnum())
  14372. {
  14373. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  14374. _FinishSplatsIterate(dscrType, name + "$d");
  14375. }
  14376. }
  14377. else
  14378. {
  14379. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  14380. {
  14381. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  14382. auto fieldDef = fieldInstance->GetFieldDef();
  14383. if (fieldInstance->mDataIdx >= 0)
  14384. {
  14385. _FinishSplatsIterate(fieldInstance->GetResolvedType(), name + "$m$" + fieldDef->mName);
  14386. }
  14387. }
  14388. }
  14389. }
  14390. else if (checkType->IsMethodRef())
  14391. {
  14392. auto methodRefType = (BfMethodRefType*)checkType;
  14393. BfMethodInstance* methodInstance = methodRefType->mMethodRef;
  14394. // int implicitParamCount = methodInstance->GetImplicitParamCount();
  14395. // for (int implicitParamIdx = methodInstance->HasThis() ? -1 : 0; implicitParamIdx < implicitParamCount; implicitParamIdx++)
  14396. // {
  14397. // auto paramType = methodInstance->GetParamType(implicitParamIdx);
  14398. // if (!paramType->IsValuelessType())
  14399. // _FinishSplats(paramType, name + "$m$" + methodInstance->GetParamName(implicitParamIdx));
  14400. // }
  14401. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  14402. {
  14403. int paramIdx = methodRefType->GetParamIdxFromDataIdx(dataIdx);
  14404. String paramName = methodInstance->GetParamName(paramIdx);
  14405. if (paramName == "this")
  14406. paramName = "__this";
  14407. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  14408. {
  14409. _FinishSplatsIterate(methodRefType->GetCaptureType(dataIdx), name + "$m$" + paramName);
  14410. }
  14411. else
  14412. {
  14413. _FinishSplats(methodRefType->GetCaptureType(dataIdx), name + "$m$" + paramName);
  14414. }
  14415. }
  14416. }
  14417. else if (!checkType->IsValuelessType())
  14418. {
  14419. _FinishSplats(checkType, name);
  14420. }
  14421. };
  14422. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  14423. if (!paramVar->mConstValue)
  14424. _FinishSplatsIterate(paramVar->mResolvedType, "$" + paramVar->mName);
  14425. }
  14426. BfIRValue declareCall;
  14427. if (diVariable)
  14428. {
  14429. if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables))
  14430. {
  14431. if (!paramVar->mAddr)
  14432. {
  14433. if ((!paramVar->mValue) || (paramVar->mValue.IsFake()))
  14434. {
  14435. if ((!paramVar->mIsThis) && (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU)) // DWARF chokes on this:
  14436. {
  14437. // We don't need to set the location for this
  14438. mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  14439. }
  14440. }
  14441. else
  14442. declareCall = mBfIRBuilder->DbgInsertDeclare(paramVar->mValue, diVariable);
  14443. }
  14444. else
  14445. {
  14446. declareCall = mBfIRBuilder->DbgInsertDeclare(paramVar->mAddr, diVariable);
  14447. }
  14448. }
  14449. }
  14450. if ((isThis) && (!paramVar->mIsSplat) && (paramVar->mAddr))
  14451. {
  14452. // We don't allow actually assignment to "this", so we just do a single load
  14453. // Keep in mind we don't use the ACTUAL mValue value because that's a register, but
  14454. // we need to store it in the stack frame for debugging purposes
  14455. auto loadedThis = mBfIRBuilder->CreateLoad(paramVar->mAddr/*, "this"*/);
  14456. mBfIRBuilder->ClearDebugLocation(loadedThis);
  14457. paramVar->mValue = loadedThis;
  14458. }
  14459. if ((wantsDIData) && (declareCall))
  14460. mBfIRBuilder->UpdateDebugLocation(declareCall);
  14461. if (paramVar->mIsSplat)
  14462. {
  14463. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  14464. }
  14465. else if (!paramVar->mResolvedType->IsValuelessType())
  14466. {
  14467. argIdx++;
  14468. }
  14469. }
  14470. if (wantsDIData)
  14471. {
  14472. BF_ASSERT(splatAddrIdx == (int)splatAddrValues.size());
  14473. }
  14474. }
  14475. for (int varIdx = 0; varIdx < (int)mCurMethodState->mLocals.size(); varIdx++)
  14476. {
  14477. auto paramVar = mCurMethodState->mLocals[varIdx];
  14478. // 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
  14479. // splat member. If the "splat" is valueless then we do create a placeholder, but further up in this method
  14480. // if (paramVar->mIsSplat)
  14481. // {
  14482. // if (wantsDIVariables)
  14483. // {
  14484. // auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(diFunction, paramVar->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(paramVar->mResolvedType));
  14485. // mBfIRBuilder->DbgInsertValueIntrinsic(mBfIRBuilder->CreateConst(BfTypeCode_Int64, 0), diVariable);
  14486. // }
  14487. // }
  14488. if (paramVar->mResolvedType->IsValuelessType())
  14489. {
  14490. if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables) && (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU)) // DWARF chokes on this:
  14491. {
  14492. // Only add this placeholder if we don't have any values
  14493. auto diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  14494. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  14495. paramVar->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  14496. mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  14497. }
  14498. }
  14499. }
  14500. if (IsTargetingBeefBackend())
  14501. mCurMethodState->mCurScope->mValueScopeStart = mBfIRBuilder->CreateValueScopeStart();
  14502. if (methodState.mClosureState != NULL)
  14503. {
  14504. for (auto& constLocal : methodState.mClosureState->mConstLocals)
  14505. {
  14506. BfLocalVariable* localVar = new BfLocalVariable();
  14507. *localVar = constLocal;
  14508. AddLocalVariableDef(localVar, true);
  14509. }
  14510. }
  14511. bool wantsRemoveBody = false;
  14512. bool skipBody = false;
  14513. bool skipUpdateSrcPos = false;
  14514. bool skipEndChecks = false;
  14515. bool hasExternSpecifier = (methodDeclaration != NULL) && (methodDeclaration->mExternSpecifier != NULL) && (methodDef->mImportKind != BfImportKind_Dynamic);
  14516. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  14517. if ((methodDef != NULL) && (propertyDeclaration != NULL) && (propertyDeclaration->mExternSpecifier != NULL))
  14518. hasExternSpecifier = true;
  14519. // Allocate, clear, set classVData
  14520. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mIsStatic))
  14521. {
  14522. CreateStaticCtor();
  14523. }
  14524. else if ((mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType != BfMethodType_Ctor) && (methodDef->mName != BF_METHODNAME_DYNAMICCAST) && (methodDef->mName != BF_METHODNAME_DYNAMICCAST_INTERFACE))
  14525. {
  14526. skipBody = true;
  14527. skipEndChecks = true;
  14528. if (HasCompiledOutput())
  14529. {
  14530. // Clear out DebugLoc - to mark the ".addr" code as part of prologue
  14531. mBfIRBuilder->ClearDebugLocation();
  14532. BfBoxedType* boxedType = (BfBoxedType*) mCurTypeInstance;
  14533. BfTypeInstance* innerType = boxedType->mElementType;
  14534. PopulateType(innerType, BfPopulateType_DataAndMethods);
  14535. mBfIRBuilder->PopulateType(mCurTypeInstance);
  14536. BfGetMethodInstanceFlags flags = BfGetMethodInstanceFlag_None;
  14537. if (methodInstance->mIsForeignMethodDef)
  14538. {
  14539. flags = BfGetMethodInstanceFlag_ForeignMethodDef;
  14540. }
  14541. BfTypeVector methodGenericArguments;
  14542. if (methodInstance->mMethodInfoEx != NULL)
  14543. methodGenericArguments = methodInstance->mMethodInfoEx->mMethodGenericArguments;
  14544. auto innerMethodInstance = GetMethodInstance(innerType, methodDef, methodGenericArguments, flags, methodInstance->GetForeignType());
  14545. if (innerMethodInstance.mMethodInstance->IsSkipCall())
  14546. {
  14547. if (!methodInstance->mReturnType->IsValuelessType())
  14548. {
  14549. auto retVal = GetDefaultValue(methodInstance->mReturnType);
  14550. CreateReturn(retVal);
  14551. }
  14552. }
  14553. else
  14554. {
  14555. BF_ASSERT(innerMethodInstance.mMethodInstance->mMethodDef == methodDef);
  14556. SizedArray<BfIRValue, 8> innerParams;
  14557. BfExprEvaluator exprEvaluator(this);
  14558. if (!innerType->IsValuelessType())
  14559. {
  14560. BfIRValue thisValue = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, 1);
  14561. BfTypedValue innerVal(thisValue, innerType, true);
  14562. if (boxedType->IsBoxedStructPtr())
  14563. {
  14564. innerVal = LoadValue(innerVal);
  14565. innerVal = BfTypedValue(innerVal.mValue, innerType, true);
  14566. }
  14567. exprEvaluator.PushThis(NULL, innerVal, innerMethodInstance.mMethodInstance, innerParams);
  14568. }
  14569. for (int i = 1; i < (int)mCurMethodState->mLocals.size(); i++)
  14570. {
  14571. BfLocalVariable* localVar = mCurMethodState->mLocals[i];
  14572. BfTypedValue localVal = exprEvaluator.LoadLocal(localVar, true);
  14573. exprEvaluator.PushArg(localVal, innerParams);
  14574. }
  14575. if (!innerMethodInstance.mFunc)
  14576. {
  14577. BF_ASSERT(innerType->IsUnspecializedType());
  14578. }
  14579. else if (methodInstance->HasStructRet())
  14580. {
  14581. mBfIRBuilder->PopulateType(methodInstance->mReturnType);
  14582. auto returnType = BfTypedValue(mBfIRBuilder->GetArgument(0), methodInstance->mReturnType, true);
  14583. exprEvaluator.mReceivingValue = &returnType;
  14584. auto retVal = exprEvaluator.CreateCall(innerMethodInstance.mMethodInstance, innerMethodInstance.mFunc, true, innerParams, NULL, true);
  14585. BF_ASSERT(exprEvaluator.mReceivingValue == NULL); // Ensure it was actually used
  14586. mBfIRBuilder->CreateRetVoid();
  14587. }
  14588. else
  14589. {
  14590. mBfIRBuilder->PopulateType(methodInstance->mReturnType);
  14591. auto retVal = exprEvaluator.CreateCall(innerMethodInstance.mMethodInstance, innerMethodInstance.mFunc, true, innerParams, NULL, true);
  14592. if (mCurMethodInstance->mReturnType->IsValueType())
  14593. retVal = LoadValue(retVal);
  14594. CreateReturn(retVal.mValue);
  14595. }
  14596. }
  14597. }
  14598. mCurMethodState->SetHadReturn(true);
  14599. mCurMethodState->mLeftBlockUncond = true;
  14600. }
  14601. else if (methodDef->mMethodType == BfMethodType_CtorClear)
  14602. {
  14603. SetIllegalSrcPos();
  14604. mBfIRBuilder->ClearDebugLocation();
  14605. PopulateType(mCurTypeInstance, BfPopulateType_Data);
  14606. auto thisVal = GetThis();
  14607. int prevSize = mContext->mBfObjectType->mInstSize;
  14608. int curSize = mCurTypeInstance->mInstSize;
  14609. if (curSize > prevSize)
  14610. {
  14611. auto int8PtrType = CreatePointerType(GetPrimitiveType(BfTypeCode_Int8));
  14612. auto int8PtrVal = mBfIRBuilder->CreateBitCast(thisVal.mValue, mBfIRBuilder->MapType(int8PtrType));
  14613. int8PtrVal = mBfIRBuilder->CreateInBoundsGEP(int8PtrVal, GetConstValue(prevSize));
  14614. mBfIRBuilder->CreateMemSet(int8PtrVal, GetConstValue8(0), GetConstValue(curSize - prevSize), GetConstValue(mCurTypeInstance->mInstAlign));
  14615. }
  14616. skipUpdateSrcPos = true;
  14617. }
  14618. else if (((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorNoBody)) && (!hasExternSpecifier))
  14619. {
  14620. EmitCtorBody(skipBody);
  14621. }
  14622. else if ((methodDef->mMethodType == BfMethodType_Dtor) && (!hasExternSpecifier))
  14623. {
  14624. EmitDtorBody();
  14625. skipBody = true;
  14626. }
  14627. if ((!mCurTypeInstance->IsBoxed()) && (methodDeclaration != NULL) && (methodDeclaration->mHadYield) && (methodDef->mBody != NULL))
  14628. {
  14629. EmitIteratorBlock(skipBody);
  14630. }
  14631. if (methodDef->mName == BF_METHODNAME_MARKMEMBERS)
  14632. {
  14633. // We need to be able to mark deleted objects
  14634. mCurMethodState->mIgnoreObjectAccessCheck = true;
  14635. }
  14636. auto customAttributes = methodInstance->GetCustomAttributes();
  14637. if ((customAttributes != NULL) && (customAttributes->Contains(mCompiler->mDisableObjectAccessChecksAttributeTypeDef)))
  14638. mCurMethodState->mIgnoreObjectAccessCheck = true;
  14639. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) && (!methodDef->mIsStatic) &&
  14640. ((methodInstance->mChainType == BfMethodChainType_ChainHead) || (methodInstance->mChainType == BfMethodChainType_None)))
  14641. {
  14642. // We chain even non-default ctors to the default ctors
  14643. auto defaultCtor = methodInstance;
  14644. if (defaultCtor->mChainType == BfMethodChainType_ChainHead)
  14645. CallChainedMethods(defaultCtor, false);
  14646. }
  14647. auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody);
  14648. if (methodDef->mBody == NULL)
  14649. {
  14650. if (methodDeclaration != NULL)
  14651. {
  14652. if (auto operatorDeclaration = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  14653. {
  14654. if (operatorDeclaration->mIsConvOperator)
  14655. wantsRemoveBody = true;
  14656. }
  14657. }
  14658. bool isDllImport = false;
  14659. if (methodDef->mImportKind == BfImportKind_Static)
  14660. {
  14661. for (auto customAttr : methodInstance->GetCustomAttributes()->mAttributes)
  14662. {
  14663. if (customAttr.mType->mTypeDef->mFullName.ToString() == "System.ImportAttribute")
  14664. {
  14665. if (customAttr.mCtorArgs.size() == 1)
  14666. {
  14667. auto fileNameArg = customAttr.mCtorArgs[0];
  14668. int strNum = 0;
  14669. auto constant = mCurTypeInstance->mConstHolder->GetConstant(fileNameArg);
  14670. if (constant != NULL)
  14671. {
  14672. if (constant->IsNull())
  14673. continue; // Invalid
  14674. strNum = constant->mInt32;
  14675. }
  14676. else
  14677. {
  14678. strNum = GetStringPoolIdx(fileNameArg, mCurTypeInstance->mConstHolder);
  14679. }
  14680. if (!mImportFileNames.Contains(strNum))
  14681. mImportFileNames.Add(strNum);
  14682. }
  14683. }
  14684. }
  14685. //mImportFileNames
  14686. }
  14687. else if (methodDef->mImportKind == BfImportKind_Dynamic)
  14688. {
  14689. CreateDllImportMethod();
  14690. }
  14691. else if (((mCurTypeInstance->mTypeDef->mIsDelegate) || (mCurTypeInstance->mTypeDef->mIsFunction)) &&
  14692. (methodDef->mName == "Invoke") && (methodDef->mMethodType == BfMethodType_Normal))
  14693. {
  14694. if (mCurTypeInstance->mTypeDef->mIsFunction)
  14695. {
  14696. // Emit nothing
  14697. }
  14698. else
  14699. {
  14700. CreateDelegateInvokeMethod();
  14701. mCurMethodState->SetHadReturn(true);
  14702. mCurMethodState->mLeftBlockUncond = true;
  14703. }
  14704. }
  14705. else if ((methodDef->mName == BF_METHODNAME_DYNAMICCAST) || (methodDef->mName == BF_METHODNAME_DYNAMICCAST_INTERFACE))
  14706. {
  14707. if (mCurTypeInstance->IsObject())
  14708. {
  14709. CreateDynamicCastMethod();
  14710. }
  14711. else
  14712. {
  14713. mBfIRBuilder->CreateRet(GetDefaultValue(methodInstance->mReturnType));
  14714. mCurMethodState->mHadReturn = true;
  14715. }
  14716. }
  14717. else if ((methodDef->mName == BF_METHODNAME_ENUM_HASFLAG) && (mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()))
  14718. {
  14719. BfIRValue ret;
  14720. if (mCurMethodState->mLocals[1]->mResolvedType != mCurTypeInstance)
  14721. {
  14722. // This can happen if we provide an invalid name
  14723. AssertErrorState();
  14724. ret = mBfIRBuilder->CreateRet(GetDefaultValue(GetPrimitiveType(BfTypeCode_Boolean)));
  14725. }
  14726. else
  14727. {
  14728. // Unfortunate DebugLoc shenanigans-
  14729. // 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,
  14730. // so we only set the loc on the CreateRet which gets inlined out
  14731. mBfIRBuilder->SaveDebugLocation();
  14732. mBfIRBuilder->ClearDebugLocation();
  14733. BfIRValue fromBool;
  14734. if (!mCurTypeInstance->IsTypedPrimitive())
  14735. {
  14736. fromBool = GetDefaultValue(methodInstance->mReturnType);
  14737. }
  14738. else
  14739. {
  14740. auto andResult = mBfIRBuilder->CreateAnd(mCurMethodState->mLocals[0]->mValue, mCurMethodState->mLocals[1]->mValue);
  14741. auto toBool = mBfIRBuilder->CreateCmpNE(andResult, GetDefaultValue(mCurMethodState->mLocals[0]->mResolvedType));
  14742. fromBool = mBfIRBuilder->CreateNumericCast(toBool, false, BfTypeCode_Boolean);
  14743. }
  14744. mBfIRBuilder->RestoreDebugLocation();
  14745. ret = mBfIRBuilder->CreateRet(fromBool);
  14746. //ExtendLocalLifetimes(0);
  14747. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  14748. }
  14749. mCurMethodState->SetHadReturn(true);
  14750. mCurMethodState->mLeftBlockUncond = true;
  14751. }
  14752. else if (((methodDef->mName == BF_METHODNAME_ENUM_GETUNDERLYINGREF) || (methodDef->mName == BF_METHODNAME_ENUM_GETUNDERLYING)) &&
  14753. (mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()))
  14754. {
  14755. BfIRValue ret;
  14756. // Unfortunate DebugLoc shenanigans-
  14757. // 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,
  14758. // so we only set the loc on the CreateRet which gets inlined out
  14759. mBfIRBuilder->SaveDebugLocation();
  14760. mBfIRBuilder->ClearDebugLocation();
  14761. BfIRValue fromBool;
  14762. mBfIRBuilder->RestoreDebugLocation();
  14763. ret = mBfIRBuilder->CreateRet(GetThis().mValue);
  14764. //ExtendLocalLifetimes(0);
  14765. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  14766. mCurMethodState->SetHadReturn(true);
  14767. mCurMethodState->mLeftBlockUncond = true;
  14768. }
  14769. else if ((mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()) && (methodDef->mName == BF_METHODNAME_TO_STRING))
  14770. {
  14771. auto enumType = ResolveTypeDef(mCompiler->mEnumTypeDef);
  14772. if (HasCompiledOutput())
  14773. {
  14774. EmitEnumToStringBody();
  14775. }
  14776. mBfIRBuilder->CreateRetVoid();
  14777. mCurMethodState->SetHadReturn(true);
  14778. mCurMethodState->mLeftBlockUncond = true;
  14779. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  14780. }
  14781. else if ((mCurTypeInstance->IsTuple()) && (!mCurTypeInstance->IsBoxed()) && (methodDef->mName == BF_METHODNAME_TO_STRING))
  14782. {
  14783. auto enumType = ResolveTypeDef(mCompiler->mEnumTypeDef);
  14784. if (HasCompiledOutput())
  14785. {
  14786. EmitTupleToStringBody();
  14787. }
  14788. mBfIRBuilder->CreateRetVoid();
  14789. mCurMethodState->SetHadReturn(true);
  14790. mCurMethodState->mLeftBlockUncond = true;
  14791. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  14792. }
  14793. else if (methodDef->mName == BF_METHODNAME_DEFAULT_EQUALS)
  14794. {
  14795. CreateValueTypeEqualsMethod();
  14796. skipBody = true;
  14797. skipEndChecks = true;
  14798. }
  14799. else if ((methodDef->mName == BF_METHODNAME_EQUALS) && (typeDef == mCompiler->mValueTypeTypeDef))
  14800. {
  14801. CreateValueTypeEqualsMethod();
  14802. skipBody = true;
  14803. skipEndChecks = true;
  14804. }
  14805. else if (HasCompiledOutput())
  14806. {
  14807. if ((methodDef->mName == BF_METHODNAME_MARKMEMBERS) || (methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC))
  14808. {
  14809. if (mCompiler->mOptions.mEnableRealtimeLeakCheck)
  14810. {
  14811. EmitGCMarkMembers();
  14812. }
  14813. else if (!mCurTypeInstance->IsObject())
  14814. {
  14815. }
  14816. }
  14817. else if (methodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS)
  14818. {
  14819. if (mCompiler->mOptions.mEnableRealtimeLeakCheck)
  14820. {
  14821. EmitGCFindTLSMembers();
  14822. }
  14823. }
  14824. }
  14825. }
  14826. else if (!skipBody)
  14827. {
  14828. bool isEmptyBodied = BfNodeDynCast<BfTokenNode>(methodDef->mBody) != NULL;
  14829. if (isEmptyBodied) // Generate autoProperty things
  14830. {
  14831. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  14832. if ((propertyDeclaration != NULL) && (!typeDef->HasAutoProperty(propertyDeclaration)))
  14833. {
  14834. if ((!mCurTypeInstance->IsInterface()) && (!hasExternSpecifier))
  14835. Fail("Body expected", methodDef->mBody);
  14836. }
  14837. else if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  14838. {
  14839. if (methodInstance->mReturnType->IsValuelessType())
  14840. {
  14841. mBfIRBuilder->CreateRetVoid();
  14842. }
  14843. else if (HasCompiledOutput())
  14844. {
  14845. String autoPropName = typeDef->GetAutoPropertyName(propertyDeclaration);
  14846. BfFieldInstance* fieldInstance = GetFieldByName(mCurTypeInstance, autoPropName);
  14847. BfFieldDef* fieldDef = NULL;
  14848. if (fieldInstance != NULL)
  14849. fieldDef = fieldInstance->GetFieldDef();
  14850. BfType* retType = methodInstance->mReturnType;
  14851. if (retType->IsRef())
  14852. retType = retType->GetUnderlyingType();
  14853. if ((fieldInstance != NULL) && (fieldInstance->GetResolvedType() == retType) &&
  14854. ((fieldInstance->mDataIdx >= 0) || (fieldDef->IsNonConstStatic())))
  14855. {
  14856. BfTypedValue lookupValue;
  14857. if (fieldDef->IsNonConstStatic())
  14858. lookupValue = ReferenceStaticField(fieldInstance);
  14859. else if (mCurTypeInstance->IsObject())
  14860. lookupValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(GetThis().mValue, 0, fieldInstance->mDataIdx), fieldInstance->mResolvedType, true);
  14861. else
  14862. lookupValue = ExtractValue(GetThis(), fieldInstance, fieldInstance->mFieldIdx);
  14863. if (!methodInstance->mReturnType->IsRef())
  14864. lookupValue = LoadValue(lookupValue);
  14865. mBfIRBuilder->CreateRet(lookupValue.mValue);
  14866. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  14867. }
  14868. else
  14869. {
  14870. // This can happen if we have two properties with the same name but different types
  14871. AssertErrorState();
  14872. mBfIRBuilder->CreateRet(GetDefaultValue(methodInstance->mReturnType));
  14873. }
  14874. }
  14875. else
  14876. {
  14877. // During autocomplete, the actual type may not have the proper field instance
  14878. mBfIRBuilder->CreateRet(GetDefaultValue(methodInstance->mReturnType));
  14879. }
  14880. mCurMethodState->SetHadReturn(true);
  14881. }
  14882. else if (methodDef->mMethodType == BfMethodType_PropertySetter)
  14883. {
  14884. if (!mCompiler->IsAutocomplete())
  14885. {
  14886. String autoPropName = typeDef->GetAutoPropertyName(propertyDeclaration);
  14887. BfFieldInstance* fieldInstance = GetFieldByName(mCurTypeInstance, autoPropName);
  14888. auto fieldDef = fieldInstance->GetFieldDef();
  14889. auto& lastParam = mCurMethodState->mLocals.back();
  14890. if ((fieldInstance != NULL) && (fieldInstance->GetResolvedType() == lastParam->mResolvedType) &&
  14891. ((fieldInstance->mDataIdx >= 0) || (fieldDef->IsNonConstStatic())))
  14892. {
  14893. BfIRValue lookupAddr;
  14894. if (fieldDef->IsNonConstStatic())
  14895. lookupAddr = ReferenceStaticField(fieldInstance).mValue;
  14896. else
  14897. {
  14898. auto thisValue = GetThis();
  14899. if (thisValue.IsSplat())
  14900. {
  14901. BF_FATAL("Should not happen");
  14902. }
  14903. if (mCurTypeInstance->IsObject())
  14904. thisValue = LoadValue(thisValue);
  14905. lookupAddr = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInstance->mDataIdx);
  14906. }
  14907. mBfIRBuilder->CreateStore(lastParam->mValue, lookupAddr);
  14908. }
  14909. else if (!fieldInstance->mResolvedType->IsValuelessType())
  14910. {
  14911. // This can happen if we have two properties with the same name but different types
  14912. AssertErrorState();
  14913. }
  14914. }
  14915. }
  14916. }
  14917. if ((!mCurMethodInstance->mReturnType->IsValuelessType()) && (!isEmptyBodied))
  14918. {
  14919. mBfIRBuilder->PopulateType(mCurMethodInstance->mReturnType);
  14920. if (mCurMethodInstance->HasStructRet())
  14921. {
  14922. auto ptrType = CreatePointerType(mCurMethodInstance->mReturnType);
  14923. auto allocaInst = AllocLocalVariable(ptrType, "__return.addr", false);
  14924. auto storeInst = mBfIRBuilder->CreateStore(mBfIRBuilder->GetArgument(0), allocaInst);
  14925. mBfIRBuilder->ClearDebugLocation(storeInst);
  14926. mCurMethodState->mRetValAddr = allocaInst;
  14927. }
  14928. else
  14929. {
  14930. auto allocaInst = AllocLocalVariable(mCurMethodInstance->mReturnType, "__return", false);
  14931. mCurMethodState->mRetVal = BfTypedValue(allocaInst, mCurMethodInstance->mReturnType, true);
  14932. }
  14933. }
  14934. if (methodDef->mMethodType == BfMethodType_CtorCalcAppend)
  14935. {
  14936. mBfIRBuilder->CreateStore(GetConstValue(0), mCurMethodState->mRetVal.mValue);
  14937. BfGetSymbolReferenceKind prevSymbolKind;
  14938. BfAutoComplete* prevAutoComplete;
  14939. if (mCompiler->mResolvePassData != NULL)
  14940. {
  14941. prevSymbolKind = mCompiler->mResolvePassData->mGetSymbolReferenceKind;
  14942. prevAutoComplete = mCompiler->mResolvePassData->mAutoComplete;
  14943. mCompiler->mResolvePassData->mGetSymbolReferenceKind = BfGetSymbolReferenceKind_None;
  14944. }
  14945. EmitCtorCalcAppend();
  14946. if (mCompiler->mResolvePassData != NULL)
  14947. {
  14948. mCompiler->mResolvePassData->mGetSymbolReferenceKind = prevSymbolKind;
  14949. mCompiler->mResolvePassData->mAutoComplete = prevAutoComplete;
  14950. }
  14951. }
  14952. else if (!isEmptyBodied)
  14953. {
  14954. if (!mCurMethodState->mIRExitBlock)
  14955. mCurMethodState->mIRExitBlock = mBfIRBuilder->CreateBlock("exit", true);
  14956. bool isExpressionBody = false;
  14957. if (methodDeclaration != NULL)
  14958. {
  14959. if (methodDeclaration->mFatArrowToken != NULL)
  14960. isExpressionBody = true;
  14961. }
  14962. else if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  14963. {
  14964. if (auto propBodyExpr = BfNodeDynCast<BfPropertyBodyExpression>(propertyDeclaration->mDefinitionBlock))
  14965. {
  14966. isExpressionBody = true;
  14967. }
  14968. }
  14969. else
  14970. {
  14971. if (auto block = BfNodeDynCast<BfBlock>(methodDef->mBody))
  14972. {
  14973. if (!block->mChildArr.IsEmpty())
  14974. {
  14975. if (auto exprStmt = BfNodeDynCast<BfExpressionStatement>(block->mChildArr.GetLast()))
  14976. {
  14977. if (exprStmt->mTrailingSemicolon == NULL)
  14978. isExpressionBody = true;
  14979. }
  14980. }
  14981. }
  14982. else
  14983. isExpressionBody = true;
  14984. }
  14985. if (auto fieldDtorBody = BfNodeDynCast<BfFieldDtorDeclaration>(methodDef->mBody))
  14986. {
  14987. while (fieldDtorBody != NULL)
  14988. {
  14989. VisitEmbeddedStatement(fieldDtorBody->mBody);
  14990. fieldDtorBody = fieldDtorBody->mNextFieldDtor;
  14991. }
  14992. }
  14993. else if (!isExpressionBody)
  14994. {
  14995. auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody);
  14996. mCurMethodState->mHeadScope.mAstBlock = bodyBlock;
  14997. mCurMethodState->mHeadScope.mCloseNode = bodyBlock->mCloseBrace;
  14998. VisitCodeBlock(bodyBlock);
  14999. }
  15000. else if (auto expressionBody = BfNodeDynCast<BfExpression>(methodDef->mBody))
  15001. {
  15002. if ((methodDef->mMethodType != BfMethodType_Normal) && (propertyDeclaration == NULL))
  15003. {
  15004. BF_ASSERT(methodDeclaration->mFatArrowToken != NULL);
  15005. Fail("Only normal methods can have expression bodies", methodDeclaration->mFatArrowToken);
  15006. }
  15007. auto expectingType = mCurMethodInstance->mReturnType;
  15008. // if ((expectingType->IsVoid()) && (IsInSpecializedSection()))
  15009. // {
  15010. // Warn(0, "Using a 'void' return with an expression-bodied method isn't needed. Consider removing '=>' token", methodDeclaration->mFatArrowToken);
  15011. // }
  15012. //TODO: Why did we have all this stuff for handling void?
  15013. // if (expectingType->IsVoid())
  15014. // {
  15015. // bool wasReturnGenericParam = false;
  15016. // if ((mCurMethodState->mClosureState != NULL) && (mCurMethodState->mClosureState->mReturnType != NULL))
  15017. // {
  15018. // wasReturnGenericParam = mCurMethodState->mClosureState->mReturnType->IsGenericParam();
  15019. // }
  15020. // else
  15021. // {
  15022. // auto unspecializedMethodInstance = GetUnspecializedMethodInstance(mCurMethodInstance);
  15023. // if ((unspecializedMethodInstance != NULL) && (unspecializedMethodInstance->mReturnType->IsGenericParam()))
  15024. // wasReturnGenericParam = true;
  15025. // }
  15026. //
  15027. // // If we the void return was from a generic specialization, allow us to return a void result,
  15028. // // otherwise treat expression as though it must be a statement
  15029. // bool isStatement = expressionBody->VerifyIsStatement(mCompiler->mPassInstance, wasReturnGenericParam);
  15030. // if (isStatement)
  15031. // expectingType = NULL;
  15032. // }
  15033. UpdateSrcPos(expressionBody);
  15034. auto retVal = CreateValueFromExpression(expressionBody, expectingType);
  15035. if ((retVal) && (expectingType != NULL))
  15036. {
  15037. mCurMethodState->mHadReturn = true;
  15038. retVal = LoadValue(retVal);
  15039. EmitReturn(retVal.mValue);
  15040. }
  15041. }
  15042. }
  15043. }
  15044. BF_ASSERT(mCurMethodState->mCurScope == &mCurMethodState->mHeadScope);
  15045. if (skipUpdateSrcPos)
  15046. {
  15047. // Skip
  15048. }
  15049. else if ((bodyBlock != NULL) && (bodyBlock->mCloseBrace != NULL))
  15050. UpdateSrcPos(bodyBlock->mCloseBrace);
  15051. else if (methodDef->mBody != NULL)
  15052. UpdateSrcPos(methodDef->mBody);
  15053. else if (methodDeclaration != NULL)
  15054. UpdateSrcPos(methodDeclaration);
  15055. else if (methodDef->mDeclaringType->mTypeDeclaration != NULL)
  15056. UpdateSrcPos(methodDef->mDeclaringType->mTypeDeclaration);
  15057. else
  15058. UseDefaultSrcPos();
  15059. if (methodDef->mMethodType == BfMethodType_CtorCalcAppend)
  15060. {
  15061. if (mCurMethodState->mRetVal)
  15062. {
  15063. mCurMethodState->SetHadReturn(true);
  15064. auto retVal = mBfIRBuilder->CreateLoad(mCurMethodState->mRetVal.mValue);
  15065. mBfIRBuilder->CreateRet(retVal);
  15066. }
  15067. else
  15068. AssertErrorState();
  15069. }
  15070. if (!mCurMethodState->mHadReturn)
  15071. {
  15072. // Clear off the stackallocs that have occurred after a scopeData break
  15073. EmitDeferredScopeCalls(false, &mCurMethodState->mHeadScope, mCurMethodState->mIRExitBlock);
  15074. }
  15075. if (mCurMethodState->mIRExitBlock)
  15076. {
  15077. for (auto preExitBlock : mCurMethodState->mHeadScope.mAtEndBlocks)
  15078. mBfIRBuilder->MoveBlockToEnd(preExitBlock);
  15079. mBfIRBuilder->MoveBlockToEnd(mCurMethodState->mIRExitBlock);
  15080. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRExitBlock);
  15081. if (!mCurMethodState->mDIRetVal)
  15082. CreateDIRetVal();
  15083. }
  15084. for (auto localVar : mCurMethodState->mLocals)
  15085. {
  15086. if ((skipEndChecks) || (bodyBlock == NULL))
  15087. break;
  15088. LocalVariableDone(localVar, true);
  15089. }
  15090. if (mCurMethodState->mIRExitBlock)
  15091. {
  15092. if ((mCurMethodState->mRetVal) && (!mCurMethodInstance->HasStructRet()))
  15093. {
  15094. auto loadedVal = mBfIRBuilder->CreateLoad(mCurMethodState->mRetVal.mValue);
  15095. CreateReturn(loadedVal);
  15096. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  15097. if (mCurMethodState->mDIRetVal)
  15098. mBfIRBuilder->DbgLifetimeEnd(mCurMethodState->mDIRetVal);
  15099. }
  15100. else
  15101. {
  15102. // Have something on the last line to step onto
  15103. if (mHasFullDebugInfo)
  15104. {
  15105. if ((bodyBlock != NULL) && (bodyBlock->mCloseBrace != NULL))
  15106. UpdateSrcPos(bodyBlock->mCloseBrace);
  15107. EmitEnsureInstructionAt();
  15108. if ((irParamCount == 0) && (!IsTargetingBeefBackend()) && (mCompiler->mOptions.mAllowHotSwapping))
  15109. {
  15110. // This may be a case where we only emit 4 bytes, whereas we need 5 for a hot replace jump
  15111. mBfIRBuilder->EnsureFunctionPatchable();
  15112. }
  15113. }
  15114. mBfIRBuilder->CreateRetVoid();
  15115. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  15116. if (mCurMethodState->mDIRetVal)
  15117. mBfIRBuilder->DbgLifetimeEnd(mCurMethodState->mDIRetVal);
  15118. }
  15119. }
  15120. if ((mCurMethodInstance->mReturnType == NULL) || (mCurMethodInstance->mReturnType->IsValuelessType()))
  15121. {
  15122. if ((!mCurMethodState->mHadReturn) && (!mCurMethodState->mIRExitBlock))
  15123. {
  15124. if ((irParamCount == 0) && (!IsTargetingBeefBackend()) && (mCompiler->mOptions.mAllowHotSwapping))
  15125. {
  15126. // This may be a case where we only emit 4 bytes, whereas we need 5 for a hot replace jump
  15127. mBfIRBuilder->EnsureFunctionPatchable();
  15128. }
  15129. mBfIRBuilder->CreateRetVoid();
  15130. }
  15131. }
  15132. else
  15133. {
  15134. if (!mCurMethodState->mHadReturn)
  15135. {
  15136. auto refNode = mCurMethodInstance->mMethodDef->GetRefNode();
  15137. if (bodyBlock != NULL)
  15138. {
  15139. if (bodyBlock->mCloseBrace != NULL)
  15140. {
  15141. BfAstNode* target = bodyBlock->mCloseBrace;
  15142. Fail("Method must return value", target);
  15143. }
  15144. else
  15145. {
  15146. // It's possible to not have a closing brace if the method ends in an EOF
  15147. AssertErrorState();
  15148. }
  15149. }
  15150. }
  15151. }
  15152. // Move 'init' into 'entry'
  15153. mBfIRBuilder->MergeBlockDown(mCurMethodState->mIRInitBlock, mCurMethodState->mIREntryBlock);
  15154. mBfIRBuilder->MergeBlockDown(mCurMethodState->mIRHeadBlock, mCurMethodState->mIREntryBlock);
  15155. if ((mCurMethodInstance->mIsUnspecialized) /*|| (typeDef->mIsFunction)*/ || (mCurTypeInstance->IsUnspecializedType()))
  15156. {
  15157. // Don't keep instructions for unspecialized types
  15158. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  15159. }
  15160. if ((hasExternSpecifier) && (!skipBody))
  15161. {
  15162. // If we hot swap, we want to make sure at least one method refers to this extern method so it gets pulled in
  15163. // incase it gets called later by some hot-loaded coded
  15164. if (mCompiler->mOptions.mAllowHotSwapping)
  15165. CreateFakeCallerMethod(mangledName);
  15166. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  15167. }
  15168. else if ((methodDef->mImportKind == BfImportKind_Dynamic) && (!mCompiler->IsHotCompile()))
  15169. {
  15170. // We only need the DLL stub when we may be hot swapping
  15171. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  15172. }
  15173. else if (wantsRemoveBody)
  15174. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  15175. // We don't want to hold on to pointers to LLVMFunctions of unspecialized types.
  15176. // This allows us to delete the mScratchModule LLVM module without rebuilding all
  15177. // unspecialized types
  15178. if ((mCurTypeInstance->IsUnspecializedType()) || (mCurTypeInstance->IsInterface()))
  15179. {
  15180. BfLogSysM("ProcessMethod Clearing IRFunction: %p\n", methodInstance);
  15181. methodInstance->mIRFunction = BfIRFunction();
  15182. }
  15183. CheckAddFailType();
  15184. if (mHadBuildError)
  15185. prevHadBuildError.CancelRestore();
  15186. if (mHadBuildWarning)
  15187. prevHadWarning.CancelRestore();
  15188. if (!methodDef->mIsLocalMethod)
  15189. ProcessMethod_ProcessDeferredLocals();
  15190. mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  15191. if (methodState.mHotDataReferenceBuilder != NULL)
  15192. {
  15193. AddHotDataReferences(&hotDataReferenceBuilder);
  15194. }
  15195. else
  15196. {
  15197. if ((methodInstance->mHotMethod != NULL) && (!methodInstance->mIsReified))
  15198. {
  15199. // Remove the hot method data
  15200. auto hotMethod = methodInstance->mHotMethod;
  15201. auto prevMethod = hotMethod->mPrevVersion;
  15202. if (prevMethod != NULL)
  15203. {
  15204. // If there's a prev method then pull its data into the main HotMethod.
  15205. // This, in effect, removes the 'hotMethod' data and rebases 'prevMethod'
  15206. // over to the main HotMethod definition to keep the HotMethod address
  15207. // invariant
  15208. for (auto ref : hotMethod->mReferences)
  15209. ref->Deref();
  15210. hotMethod->mReferences.Clear();
  15211. BF_ASSERT(prevMethod->mRefCount == 1);
  15212. hotMethod->mReferences = prevMethod->mReferences;
  15213. if (hotMethod->mSrcTypeVersion != NULL)
  15214. hotMethod->mSrcTypeVersion->Deref();
  15215. hotMethod->mSrcTypeVersion = prevMethod->mSrcTypeVersion;
  15216. prevMethod->mSrcTypeVersion = NULL;
  15217. prevMethod->mReferences.Clear();
  15218. hotMethod->mPrevVersion = prevMethod->mPrevVersion;
  15219. prevMethod->mPrevVersion = NULL;
  15220. prevMethod->Deref();
  15221. }
  15222. hotMethod->Deref();
  15223. methodInstance->mHotMethod = NULL;
  15224. }
  15225. }
  15226. }
  15227. String BfModule::GetLocalMethodName(const StringImpl& baseName, BfAstNode* anchorNode, BfMethodState* declMethodState, BfMixinState* declMixinState)
  15228. {
  15229. String name;
  15230. bool found = false;
  15231. auto checkMethodState = mCurMethodState;
  15232. while (checkMethodState != NULL)
  15233. {
  15234. if (checkMethodState->mClosureState == NULL)
  15235. break;
  15236. if (checkMethodState->mClosureState->mClosureMethodDef != NULL)
  15237. {
  15238. found = true;
  15239. name += checkMethodState->mClosureState->mClosureMethodDef->mName;
  15240. break;
  15241. }
  15242. checkMethodState = checkMethodState->mPrevMethodState;
  15243. }
  15244. if (!found)
  15245. name += mCurMethodInstance->mMethodDef->mName;
  15246. int prevSepPos = (int)name.LastIndexOf('$');
  15247. if (prevSepPos != -1)
  15248. {
  15249. name.RemoveToEnd(prevSepPos);
  15250. }
  15251. name += "@";
  15252. name += baseName;
  15253. HashContext hashCtx;
  15254. if (anchorNode != NULL)
  15255. {
  15256. hashCtx.Mixin(anchorNode->GetStartCharId());
  15257. }
  15258. //
  15259. {
  15260. auto checkMethodState = declMethodState;
  15261. auto checkMixinState = declMixinState;
  15262. while (checkMethodState != NULL)
  15263. {
  15264. if (checkMixinState != NULL)
  15265. {
  15266. hashCtx.Mixin(checkMixinState->mSource->GetStartCharId());
  15267. }
  15268. checkMethodState = checkMethodState->mPrevMethodState;
  15269. if (checkMethodState != NULL)
  15270. checkMixinState = checkMethodState->mMixinState;
  15271. }
  15272. }
  15273. auto rootMethodState = mCurMethodState->GetRootMethodState();
  15274. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  15275. {
  15276. for (auto methodGenericArg : rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  15277. {
  15278. StringT<128> genericTypeName;
  15279. BfMangler::Mangle(genericTypeName, mCompiler->GetMangleKind(), methodGenericArg);
  15280. hashCtx.MixinStr(genericTypeName);
  15281. }
  15282. }
  15283. uint64 hashVal = hashCtx.Finish64();
  15284. name += "$";
  15285. name += BfTypeUtils::HashEncode64(hashVal);
  15286. return name;
  15287. }
  15288. BfMethodDef* BfModule::GetLocalMethodDef(BfLocalMethod* localMethod)
  15289. {
  15290. if (localMethod->mMethodDef != NULL)
  15291. return localMethod->mMethodDef;
  15292. auto rootMethodState = mCurMethodState->GetRootMethodState();
  15293. auto declMethodState = localMethod->mDeclMethodState;
  15294. auto declMixinState = localMethod->mDeclMixinState;
  15295. auto typeInst = mCurTypeInstance;
  15296. BfAstNode* body = NULL;
  15297. BfAstNode* anchorNode = NULL;
  15298. auto _AllocDirectTypeRef = [&](BfType* type)
  15299. {
  15300. BfDirectTypeReference* directTypeRef = localMethod->mDirectTypeRefs.Alloc();
  15301. directTypeRef->Init(type);
  15302. return directTypeRef;
  15303. };
  15304. auto methodDeclaration = localMethod->mMethodDeclaration;
  15305. if (methodDeclaration != NULL)
  15306. {
  15307. body = methodDeclaration->mBody;
  15308. anchorNode = methodDeclaration->mOpenParen;
  15309. }
  15310. else
  15311. {
  15312. body = localMethod->mLambdaBindExpr->mBody;
  15313. anchorNode = localMethod->mLambdaBindExpr->mFatArrowToken;
  15314. }
  15315. BF_ASSERT(rootMethodState->mCurLocalVarId >= 0);
  15316. int methodLocalIdx = rootMethodState->mCurLocalVarId++;
  15317. BfMethodDef* methodDef;
  15318. if (methodDeclaration != NULL)
  15319. {
  15320. BfDefBuilder defBuilder(mCompiler->mSystem);
  15321. defBuilder.mPassInstance = mCompiler->mPassInstance;
  15322. defBuilder.mCurTypeDef = mCurMethodInstance->mMethodDef->mDeclaringType;
  15323. BfMethodDef* outerMethodDef = NULL;
  15324. if (localMethod->mOuterLocalMethod != NULL)
  15325. outerMethodDef = localMethod->mOuterLocalMethod->mMethodDef;
  15326. else
  15327. outerMethodDef = rootMethodState->mMethodInstance->mMethodDef;
  15328. methodDef = defBuilder.CreateMethodDef(methodDeclaration, outerMethodDef);
  15329. }
  15330. else
  15331. {
  15332. auto invokeMethod = localMethod->mLambdaInvokeMethodInstance;
  15333. methodDef = new BfMethodDef();
  15334. methodDef->mName = localMethod->mMethodName;
  15335. methodDef->mDeclaringType = mCurMethodInstance->mMethodDef->mDeclaringType;
  15336. methodDef->mReturnTypeRef = _AllocDirectTypeRef(invokeMethod->mReturnType);
  15337. methodDef->mBody = body;
  15338. for (int paramIdx = 0; paramIdx < invokeMethod->GetParamCount(); paramIdx++)
  15339. {
  15340. auto paramType = invokeMethod->GetParamType(paramIdx);
  15341. String paramName;
  15342. if (paramIdx < (int)localMethod->mLambdaBindExpr->mParams.size())
  15343. paramName = localMethod->mLambdaBindExpr->mParams[paramIdx]->ToString();
  15344. else
  15345. paramName = invokeMethod->GetParamName(paramIdx);
  15346. auto paramDef = new BfParameterDef();
  15347. paramDef->mTypeRef = _AllocDirectTypeRef(paramType);
  15348. paramDef->mName = paramName;
  15349. methodDef->mParams.Add(paramDef);
  15350. }
  15351. }
  15352. methodDef->mIdx = ~methodLocalIdx;
  15353. BF_ASSERT(!localMethod->mExpectedFullName.IsEmpty());
  15354. methodDef->mName = localMethod->mExpectedFullName;
  15355. // methodDef->mName = GetLocalMethodName(methodDef->mName, anchorNode, declMethodState, declMixinState);
  15356. //
  15357. // if (!localMethod->mExpectedFullName.IsEmpty())
  15358. // BF_ASSERT(methodDef->mName == localMethod->mExpectedFullName);
  15359. methodDef->mIsStatic = true;
  15360. methodDef->mIsLocalMethod = true;
  15361. methodDef->mIsVirtual = false;
  15362. localMethod->mMethodDef = methodDef;
  15363. auto methodInstanceGroup = new BfMethodInstanceGroup();
  15364. localMethod->mMethodInstanceGroup = methodInstanceGroup;
  15365. methodInstanceGroup->mMethodIdx = -1;
  15366. methodInstanceGroup->mOwner = mCurTypeInstance;
  15367. methodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  15368. if ((declMethodState->mMixinState != NULL) && (declMethodState->mMixinState->mTarget))
  15369. {
  15370. methodInstanceGroup->mOwner = declMethodState->mMixinState->mTarget.mType->ToTypeInstance();
  15371. BF_ASSERT(methodInstanceGroup->mOwner != NULL);
  15372. }
  15373. if ((mCompiler->mResolvePassData != NULL) && (methodDeclaration != NULL))
  15374. {
  15375. mCompiler->mResolvePassData->HandleLocalReference(methodDeclaration->mNameNode, typeInst->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, methodLocalIdx);
  15376. auto autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  15377. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(methodDeclaration->mNameNode)))
  15378. {
  15379. autoComplete->SetDefinitionLocation(methodDeclaration->mNameNode);
  15380. autoComplete->mInsertStartIdx = methodDeclaration->mNameNode->GetSrcStart();
  15381. autoComplete->mInsertEndIdx = methodDeclaration->mNameNode->GetSrcEnd();
  15382. autoComplete->mDefType = typeInst->mTypeDef;
  15383. autoComplete->mDefMethod = rootMethodState->mMethodInstance->mMethodDef;
  15384. autoComplete->mReplaceLocalId = methodLocalIdx;
  15385. }
  15386. }
  15387. return localMethod->mMethodDef;
  15388. }
  15389. BfModuleMethodInstance BfModule::GetLocalMethodInstance(BfLocalMethod* localMethod, const BfTypeVector& methodGenericArguments, BfMethodInstance* methodInstance, bool force)
  15390. {
  15391. BP_ZONE_F("GetLocalMethodInstance %s", localMethod->mMethodName.c_str());
  15392. BfLogSysM("GetLocalMethodInstance %p\n", localMethod);
  15393. auto rootMethodState = mCurMethodState->GetRootMethodState();
  15394. auto declMethodState = localMethod->mDeclMethodState;
  15395. auto declMixinState = localMethod->mDeclMixinState;
  15396. auto callerMethodState = mCurMethodState;
  15397. auto typeInst = mCurTypeInstance;
  15398. auto methodDef = GetLocalMethodDef(localMethod);
  15399. BfAstNode* body = NULL;
  15400. auto methodDeclaration = localMethod->mMethodDeclaration;
  15401. if (methodDeclaration != NULL)
  15402. {
  15403. body = methodDeclaration->mBody;
  15404. }
  15405. else
  15406. {
  15407. body = localMethod->mLambdaBindExpr->mBody;
  15408. }
  15409. bool hadConcreteInterfaceGenericArgument = false;
  15410. BfTypeVector sanitizedMethodGenericArguments;
  15411. // Ignore the outermost method's generic method arguments for the purpose of determining if we are the 'default' (ie: unspecialized)
  15412. // version of this method for this pass through the outermost method
  15413. int dependentGenericStartIdx = 0;
  15414. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  15415. dependentGenericStartIdx = (int)rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  15416. BfMethodInstance* outerMethodInstance = mCurMethodInstance;
  15417. if (methodGenericArguments.size() == 0)
  15418. {
  15419. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  15420. sanitizedMethodGenericArguments = rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments;
  15421. }
  15422. else
  15423. {
  15424. int genericArgIdx = 0;
  15425. // for (; genericArgIdx < (int)outerMethodInstance->mMethodGenericArguments.size(); genericArgIdx++)
  15426. // {
  15427. // BF_ASSERT(methodGenericArguments[genericArgIdx] == outerMethodInstance->mMethodGenericArguments[genericArgIdx]);
  15428. // sanitizedMethodGenericArguments.push_back(methodGenericArguments[genericArgIdx]);
  15429. // }
  15430. for (; genericArgIdx < (int)methodGenericArguments.size(); genericArgIdx++)
  15431. {
  15432. auto genericArgType = methodGenericArguments[genericArgIdx];
  15433. BF_ASSERT(!genericArgType->IsRef());
  15434. if (genericArgType->IsConcreteInterfaceType())
  15435. {
  15436. hadConcreteInterfaceGenericArgument = true;
  15437. auto concreteInterfaceType = (BfConcreteInterfaceType*)genericArgType;
  15438. genericArgType = concreteInterfaceType->mInterface;
  15439. }
  15440. sanitizedMethodGenericArguments.push_back(genericArgType);
  15441. }
  15442. }
  15443. bool wantPrematureMethodInstance = false;
  15444. if (!force)
  15445. {
  15446. wantPrematureMethodInstance = (callerMethodState->mClosureState != NULL) && (callerMethodState->mClosureState->mCaptureVisitingBody);
  15447. }
  15448. auto methodInstGroup = localMethod->mMethodInstanceGroup;
  15449. bool isDefaultPass = true;
  15450. BfTypeVector lookupMethodGenericArguments;
  15451. for (int genericArgIdx = dependentGenericStartIdx; genericArgIdx < (int)methodGenericArguments.size(); genericArgIdx++)
  15452. {
  15453. auto genericArgType = methodGenericArguments[genericArgIdx];
  15454. BF_ASSERT(!genericArgType->IsRef());
  15455. lookupMethodGenericArguments.Add(genericArgType);
  15456. if (genericArgType->IsGenericParam())
  15457. {
  15458. auto genericParam = (BfGenericParamType*)genericArgType;
  15459. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  15460. isDefaultPass = false;
  15461. }
  15462. else
  15463. {
  15464. isDefaultPass = false;
  15465. }
  15466. }
  15467. bool hadExistingMethodInstance = false;
  15468. if (methodInstance != NULL)
  15469. {
  15470. hadExistingMethodInstance = true;
  15471. }
  15472. else
  15473. {
  15474. if (isDefaultPass)
  15475. {
  15476. methodInstance = methodInstGroup->mDefault;
  15477. if (methodInstance != NULL)
  15478. {
  15479. hadExistingMethodInstance = true;
  15480. }
  15481. else
  15482. {
  15483. methodInstance = new BfMethodInstance();
  15484. methodInstGroup->mDefault = methodInstance;
  15485. }
  15486. }
  15487. else
  15488. {
  15489. BF_ASSERT(sanitizedMethodGenericArguments.size() != 0);
  15490. if (methodInstGroup->mMethodSpecializationMap == NULL)
  15491. methodInstGroup->mMethodSpecializationMap = new BfMethodInstanceGroup::MapType();
  15492. BfMethodInstance** methodInstancePtr = NULL;
  15493. if (!methodInstGroup->mMethodSpecializationMap->TryAdd(lookupMethodGenericArguments, NULL, &methodInstancePtr))
  15494. {
  15495. methodInstance = *methodInstancePtr;
  15496. hadExistingMethodInstance = true;
  15497. }
  15498. else
  15499. {
  15500. methodInstance = new BfMethodInstance();
  15501. *methodInstancePtr = methodInstance;
  15502. }
  15503. }
  15504. }
  15505. if (hadExistingMethodInstance)
  15506. {
  15507. if ((!methodInstance->mDisallowCalling) ||
  15508. ((wantPrematureMethodInstance) && (methodInstance->mDisallowCalling)))
  15509. return BfModuleMethodInstance(methodInstance);
  15510. BF_ASSERT((methodInstance->mMethodInfoEx == NULL) || (methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState == NULL));
  15511. }
  15512. else
  15513. {
  15514. auto methodInfoEx = methodInstance->GetMethodInfoEx();
  15515. methodInfoEx->mClosureInstanceInfo = new BfClosureInstanceInfo();
  15516. methodInfoEx->mClosureInstanceInfo->mLocalMethod = localMethod;
  15517. methodInstance->mIsReified = mCurMethodInstance->mIsReified;
  15518. methodInstance->mIsAutocompleteMethod = mCurMethodInstance->mIsAutocompleteMethod;
  15519. methodInstance->mMethodDef = methodDef;
  15520. methodInstance->mMethodInstanceGroup = localMethod->mMethodInstanceGroup;
  15521. if (hadConcreteInterfaceGenericArgument)
  15522. methodInstance->mIgnoreBody = true;
  15523. methodInfoEx->mMethodGenericArguments = sanitizedMethodGenericArguments;
  15524. for (auto genericArg : sanitizedMethodGenericArguments)
  15525. {
  15526. if (genericArg->IsPrimitiveType())
  15527. genericArg = GetWrappedStructType(genericArg);
  15528. AddDependency(genericArg, typeInst, BfDependencyMap::DependencyFlag_MethodGenericArg);
  15529. }
  15530. for (int genericParamIdx = (int)sanitizedMethodGenericArguments.size(); genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  15531. {
  15532. auto genericParamType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  15533. methodInfoEx->mMethodGenericArguments.push_back(genericParamType);
  15534. }
  15535. SetupMethodIdHash(methodInstance);
  15536. }
  15537. auto _SetupMethodInstance = [&]()
  15538. {
  15539. BF_ASSERT(methodInstance->GetNumGenericParams() == 0);
  15540. // Generic constraints
  15541. for (int genericParamIdx = 0; genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  15542. {
  15543. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, genericParamIdx);
  15544. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  15545. }
  15546. };
  15547. //////////////////////////////////////////////////////////////////////////
  15548. auto _VisitLambdaBody = [&]()
  15549. {
  15550. if (localMethod->mDeclOnly)
  15551. return;
  15552. if (mCompiler->mCanceling)
  15553. return;
  15554. if (auto blockBody = BfNodeDynCast<BfBlock>(body))
  15555. {
  15556. VisitCodeBlock(blockBody);
  15557. }
  15558. else if (auto bodyExpr = BfNodeDynCast<BfExpression>(body))
  15559. CreateValueFromExpression(bodyExpr);
  15560. };
  15561. auto _SafeResolveTypeRef = [&](BfTypeReference* typeRef)
  15562. {
  15563. SetAndRestoreValue<bool> prevIgnoreError(mIgnoreErrors, true);
  15564. auto result = ResolveTypeRef(typeRef);
  15565. if (result == NULL)
  15566. result = mContext->mBfObjectType;
  15567. return result;
  15568. };
  15569. BfTypeInstance* outerClosure = NULL;
  15570. if ((declMethodState->mClosureState != NULL) && (!declMethodState->mClosureState->mCapturing))
  15571. outerClosure = declMethodState->mClosureState->mClosureType;
  15572. BfMethodState methodState;
  15573. methodState.mPrevMethodState = declMethodState;//mCurMethodState;
  15574. BfIRFunctionType funcType;
  15575. auto voidType = GetPrimitiveType(BfTypeCode_None);
  15576. SizedArray<BfIRType, 0> paramTypes;
  15577. funcType = mBfIRBuilder->CreateFunctionType(mBfIRBuilder->MapType(voidType), paramTypes, false);
  15578. mBfIRBuilder->SaveDebugLocation();
  15579. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  15580. auto prevActiveFunction = mBfIRBuilder->GetActiveFunction();
  15581. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  15582. BfDeferredLocalAssignData deferredLocalAssignData;
  15583. //TODO: Why did we do this? It can cause us to pull in local variables that don't belong to us...
  15584. /*if (declMethodState->mDeferredLocalAssignData != NULL)
  15585. deferredLocalAssignData.ExtendFrom(declMethodState->mDeferredLocalAssignData);*/
  15586. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  15587. methodState.mIRHeadBlock = mBfIRBuilder->CreateBlock("head", true);
  15588. methodState.mIRInitBlock = mBfIRBuilder->CreateBlock("init", true);
  15589. methodState.mIREntryBlock = mBfIRBuilder->CreateBlock("entry", true);
  15590. methodState.mCurScope->mDIScope = localMethod->mDeclDIScope; //declMethodState->mCurScope->mDIScope ;
  15591. //methodState.mCurLocalVarId = declMethodState->mCurLocalVarId;
  15592. methodState.mIRFunction = declMethodState->mIRFunction;
  15593. methodState.mDeferredLocalAssignData = &deferredLocalAssignData;
  15594. mBfIRBuilder->SetInsertPoint(methodState.mIREntryBlock);
  15595. BfClosureState closureState;
  15596. if (methodDef->mMethodType == BfMethodType_Mixin)
  15597. {
  15598. if (declMethodState != NULL)
  15599. {
  15600. if ((declMethodState->mClosureState != NULL) && (declMethodState->mClosureState->mReturnType != NULL))
  15601. closureState.mReturnType = declMethodState->mClosureState->mReturnType;
  15602. else if (declMethodState->mMethodInstance != NULL)
  15603. closureState.mReturnType = declMethodState->mMethodInstance->mReturnType;
  15604. }
  15605. }
  15606. if (closureState.mReturnType == NULL)
  15607. closureState.mReturnType = _SafeResolveTypeRef(methodDef->mReturnTypeRef);
  15608. closureState.mCapturing = true;
  15609. closureState.mLocalMethod = localMethod;
  15610. closureState.mClosureInstanceInfo = methodInstance->mMethodInfoEx->mClosureInstanceInfo;
  15611. closureState.mDeclaringMethodIsMutating = mCurMethodInstance->mMethodDef->mIsMutating;
  15612. methodState.mClosureState = &closureState;
  15613. closureState.mClosureType = outerClosure;
  15614. int outerLocalsCount = (int)methodState.mLocals.size();
  15615. if (!hadExistingMethodInstance)
  15616. {
  15617. BfLogSysM("LocalMethod %p premature DoMethodDeclaration %p (Source:%p)\n", localMethod, methodInstance, (methodDeclaration != NULL) ? methodDeclaration->GetSourceData() : NULL);
  15618. SetAndRestoreValue<bool> prevIgnoreWrites(mWantsIRIgnoreWrites, true);
  15619. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  15620. // Prematurely do declaration. We will have to undo this later, so don't write this one and don't throw errors
  15621. auto declareModule = this;
  15622. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  15623. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  15624. BF_ASSERT(declareModule != NULL);
  15625. methodInstance->mDeclModule = declareModule;
  15626. _SetupMethodInstance();
  15627. declareModule->DoMethodDeclaration(localMethod->mMethodDef->GetMethodDeclaration(), false, false);
  15628. methodInstance->mDisallowCalling = true; // Don't allow us to ACTUALLY call until we add the captures
  15629. }
  15630. if (wantPrematureMethodInstance)
  15631. {
  15632. // Return a premature methodInstance -- since we are partway through determining the capture of a local method, we can't rely on its
  15633. // capture information. This returned method instance can only be used for method matching, but we will visit it later to create
  15634. // its true method instance
  15635. //auto moduleMethodInstance = _CheckReturnedMethod(methodInstance);
  15636. //BF_ASSERT(moduleMethodInstance);
  15637. return BfModuleMethodInstance(methodInstance);
  15638. }
  15639. auto checkInsertBlock = mBfIRBuilder->GetInsertBlock();
  15640. BF_ASSERT(methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState == NULL);
  15641. closureState.mCaptureStartAccessId = mCurMethodState->GetRootMethodState()->mCurAccessId;
  15642. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState = &closureState;
  15643. closureState.mClosureMethodDef = methodDef;
  15644. bool wantsVisitBody = true;
  15645. if ((methodDef->mMethodType == BfMethodType_Mixin) && (!methodGenericArguments.IsEmpty()))
  15646. wantsVisitBody = false;
  15647. if (methodInstance->mIsUnspecializedVariation)
  15648. wantsVisitBody = false;
  15649. if (wantsVisitBody)
  15650. {
  15651. BP_ZONE("VisitLambdaBody");
  15652. // For generic methods, we capture for each specialization, so make sure mIsStatic is set to 'true' for
  15653. // this capture stage for each of those times
  15654. SetAndRestoreValue<bool> prevWasStatis(methodDef->mIsStatic, true);
  15655. /*
  15656. // Only generate errors once. Also there are some errors that will occur during this scanning phase
  15657. // that will not occur during the actual lambda method generation, for example: returning a value
  15658. // when our current method is a 'void' method. This shouldn't affect capture scanning since all
  15659. // our AST nodes will still be visited
  15660. SetAndRestoreValue<bool> ignoreError(mIgnoreErrors, true);
  15661. */
  15662. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  15663. //SetAndRestoreValue<bool> wantsIgnoreWrites(mWantsISIgnoreWrites, true);
  15664. mBfIRBuilder->SaveDebugLocation();
  15665. closureState.mCaptureVisitingBody = true;
  15666. BF_ASSERT(methodInstance->mMethodInfoEx != NULL);
  15667. methodState.mGenericTypeBindings = &methodInstance->mMethodInfoEx->mGenericTypeBindings;
  15668. NewScopeState();
  15669. ProcessMethod_SetupParams(methodInstance, NULL, false, NULL);
  15670. if (methodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)
  15671. {
  15672. // Allow assigning to arguments when we're capturing - which may or may not be legal at the injection site (we throw error there)
  15673. for (auto localDef : methodState.mLocals)
  15674. {
  15675. if (localDef->mResolvedType->IsVar())
  15676. continue;
  15677. localDef->mAddr = CreateAlloca(localDef->mResolvedType);
  15678. }
  15679. }
  15680. _VisitLambdaBody();
  15681. RestoreScopeState();
  15682. //ProcessMethod(methodInstance);
  15683. closureState.mCaptureVisitingBody = false;
  15684. mBfIRBuilder->RestoreDebugLocation();
  15685. }
  15686. // If we ended up being called by a method with a lower captureStartAccessId, propagate that to whoever is calling us, too...
  15687. if ((methodState.mPrevMethodState->mClosureState != NULL) && (methodState.mPrevMethodState->mClosureState->mCapturing))
  15688. {
  15689. auto prevClosureState = methodState.mPrevMethodState->mClosureState;
  15690. if (closureState.mCaptureStartAccessId < prevClosureState->mCaptureStartAccessId)
  15691. prevClosureState->mCaptureStartAccessId = closureState.mCaptureStartAccessId;
  15692. }
  15693. //RestoreScopeState();
  15694. // Actually get the referenced local methods. It's important we wait until after visiting the body, because then our own capture information
  15695. // can be used by these methods (which will be necessary if any of these methods call us directly or indirectly)
  15696. closureState.mClosureMethodDef = NULL;
  15697. for (auto methodInstance : closureState.mLocalMethodRefs)
  15698. {
  15699. GetLocalMethodInstance(methodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod, BfTypeVector(), methodInstance);
  15700. }
  15701. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState = NULL;
  15702. prevIgnoreWrites.Restore();
  15703. std::multiset<BfClosureCapturedEntry> capturedEntries;
  15704. //
  15705. {
  15706. auto varMethodState = declMethodState;
  15707. while (varMethodState != NULL)
  15708. {
  15709. if ((varMethodState->mMixinState != NULL) && (varMethodState->mMixinState->mLastTargetAccessId >= closureState.mCaptureStartAccessId))
  15710. {
  15711. BF_ASSERT(methodInstance->GetOwner() == varMethodState->mMixinState->mTarget.mType);
  15712. methodDef->mIsStatic = false;
  15713. if (rootMethodState->mMethodInstance->mMethodDef->mIsMutating)
  15714. methodDef->mIsMutating = true;
  15715. }
  15716. bool copyOuterCaptures = false;
  15717. for (int localIdx = 0; localIdx < varMethodState->mLocals.size(); localIdx++)
  15718. {
  15719. auto localVar = varMethodState->mLocals[localIdx];
  15720. if ((localVar->mReadFromId >= closureState.mCaptureStartAccessId) || (localVar->mWrittenToId >= closureState.mCaptureStartAccessId))
  15721. {
  15722. if (localVar->mIsThis)
  15723. {
  15724. // We can only set mutating if our owning type is mutating
  15725. if (localVar->mWrittenToId >= closureState.mCaptureStartAccessId)
  15726. {
  15727. if (mCurTypeInstance->IsValueType())
  15728. {
  15729. if (rootMethodState->mMethodInstance->mMethodDef->mIsMutating)
  15730. methodDef->mIsMutating = true;
  15731. }
  15732. }
  15733. methodDef->mIsStatic = false;
  15734. continue;
  15735. }
  15736. if ((localVar->mIsThis) && (outerClosure != NULL))
  15737. {
  15738. continue;
  15739. }
  15740. if ((localVar->mConstValue) || (localVar->mResolvedType->IsValuelessType()))
  15741. {
  15742. closureState.mConstLocals.push_back(*localVar);
  15743. continue;
  15744. }
  15745. BfClosureCapturedEntry capturedEntry;
  15746. auto capturedType = localVar->mResolvedType;
  15747. bool captureByRef = false;
  15748. if (!capturedType->IsRef())
  15749. {
  15750. if (localVar->mIsThis)
  15751. {
  15752. if ((localVar->mResolvedType->IsValueType()) && (mCurMethodInstance->mMethodDef->HasNoThisSplat()))
  15753. captureByRef = true;
  15754. }
  15755. else if ((!localVar->mIsReadOnly) && (localVar->mWrittenToId >= closureState.mCaptureStartAccessId))
  15756. captureByRef = true;
  15757. }
  15758. else
  15759. {
  15760. if (localVar->mWrittenToId < closureState.mCaptureStartAccessId)
  15761. {
  15762. capturedType = ((BfRefType*)capturedType)->mElementType;
  15763. }
  15764. }
  15765. if (captureByRef)
  15766. {
  15767. //capturedEntry.mIsByReference = true;
  15768. capturedType = CreateRefType(capturedType);
  15769. }
  15770. else
  15771. {
  15772. //capturedEntry.mIsByReference = false;
  15773. }
  15774. capturedEntry.mNameNode = localVar->mNameNode;
  15775. capturedEntry.mType = capturedType;
  15776. capturedEntry.mName = localVar->mName;
  15777. //capturedEntry.mLocalVarDef = localVar;
  15778. capturedEntries.insert(capturedEntry);
  15779. }
  15780. }
  15781. varMethodState = varMethodState->mPrevMethodState;
  15782. if ((varMethodState == NULL) ||
  15783. (varMethodState->mMixinState != NULL) ||
  15784. ((varMethodState->mClosureState != NULL) && (!varMethodState->mClosureState->mCapturing)))
  15785. break;
  15786. }
  15787. }
  15788. for (auto& copyField : closureState.mReferencedOuterClosureMembers)
  15789. {
  15790. auto fieldDef = copyField->GetFieldDef();
  15791. BfClosureCapturedEntry capturedEntry;
  15792. capturedEntry.mName = copyField->GetFieldDef()->mName;
  15793. capturedEntry.mType = copyField->mResolvedType;
  15794. if (capturedEntry.mType->IsRef())
  15795. {
  15796. // Keep by ref
  15797. }
  15798. else if (!fieldDef->mIsReadOnly)
  15799. {
  15800. capturedEntry.mType = CreateRefType(capturedEntry.mType);
  15801. }
  15802. capturedEntries.insert(capturedEntry);
  15803. }
  15804. int captureIdx = 0;
  15805. for (auto& capturedEntry : capturedEntries)
  15806. {
  15807. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries.Add(capturedEntry);
  15808. }
  15809. /*if (isDefaultPass)
  15810. {
  15811. // Insert captured members a params at the start. If we added at the end then it would screw up varargs methods
  15812. int captureIdx = 0;
  15813. for (auto& capturedEntry : capturedEntries)
  15814. {
  15815. methodInstance->mClosureInstanceInfo->mCaptureNodes.Add(BfNodeDynCast<BfIdentifierNode>(capturedEntry.mNameNode));
  15816. BfParameterDef* paramDef = new BfParameterDef();
  15817. paramDef->mName = capturedEntry.mName;
  15818. BfDirectTypeReference* directTypeRef = new BfDirectTypeReference();
  15819. directTypeRef->mType = capturedEntry.mType;
  15820. typeInst->mTypeDef->mDirectAllocNodes.push_back(directTypeRef);
  15821. paramDef->mTypeRef = directTypeRef;
  15822. paramDef->mParamKind = BfParamKind_ImplicitCapture;
  15823. methodDef->mParams.Insert(captureIdx, paramDef);
  15824. captureIdx++;
  15825. }
  15826. }
  15827. else
  15828. {
  15829. auto defaultMethodInstance = methodInstGroup->mDefault;
  15830. methodInstance->mClosureInstanceInfo->mCaptureNodes = defaultMethodInstance->mClosureInstanceInfo->mCaptureNodes;
  15831. }*/
  15832. methodState.Reset();
  15833. closureState.mCapturing = false;
  15834. //////////////////////////////////////////////////////////////////////////
  15835. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, false);
  15836. if (methodInstance->mReturnType != NULL)
  15837. {
  15838. BF_ASSERT(methodInstance->mDisallowCalling);
  15839. // We did a premature declaration (without captures)
  15840. methodInstance->UndoDeclaration();
  15841. methodInstance->mDisallowCalling = false;
  15842. BfLogSysM("LocalMethod %p UndoingDeclaration %p\n", localMethod, methodInstance);
  15843. }
  15844. auto declareModule = this;
  15845. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  15846. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  15847. BF_ASSERT(declareModule != NULL);
  15848. methodInstance->mDeclModule = declareModule;
  15849. _SetupMethodInstance();
  15850. BfLogSysM("LocalMethod %p DoMethodDeclaration %p\n", localMethod, methodInstance);
  15851. declareModule->DoMethodDeclaration(localMethod->mMethodDef->GetMethodDeclaration(), false, false);
  15852. closureState.mReturnType = methodInstance->mReturnType;
  15853. mCompiler->mStats.mMethodsQueued++;
  15854. mCompiler->UpdateCompletion();
  15855. declareModule->mIncompleteMethodCount++;
  15856. mCompiler->mStats.mMethodsProcessed++;
  15857. if (!methodInstance->mIsReified)
  15858. mCompiler->mStats.mUnreifiedMethodsProcessed++;
  15859. auto deferMethodState = rootMethodState;
  15860. // 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)
  15861. if ((!localMethod->mDeclOnly) && (!methodInstance->mIsUnspecializedVariation) &&
  15862. (!mWantsIRIgnoreWrites) && (methodDef->mMethodType != BfMethodType_Mixin))
  15863. {
  15864. BP_ZONE("BfDeferredLocalMethod:create");
  15865. BfDeferredLocalMethod* deferredLocalMethod = new BfDeferredLocalMethod();
  15866. deferredLocalMethod->mLocalMethod = localMethod;
  15867. deferredLocalMethod->mConstLocals = closureState.mConstLocals;
  15868. deferredLocalMethod->mMethodInstance = methodInstance;
  15869. auto checkMethodState = declMethodState;
  15870. while (checkMethodState != NULL)
  15871. {
  15872. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mActiveDeferredLocalMethod != NULL))
  15873. {
  15874. for (auto& mixinRecord : checkMethodState->mClosureState->mActiveDeferredLocalMethod->mMixinStateRecords)
  15875. deferredLocalMethod->mMixinStateRecords.Add(mixinRecord);
  15876. }
  15877. if (checkMethodState->mMixinState != NULL)
  15878. {
  15879. BfMixinRecord mixinRecord;
  15880. mixinRecord.mSource = checkMethodState->mMixinState->mSource;
  15881. deferredLocalMethod->mMixinStateRecords.Add(mixinRecord);
  15882. }
  15883. checkMethodState = checkMethodState->mPrevMethodState;
  15884. }
  15885. rootMethodState->mDeferredLocalMethods.Add(deferredLocalMethod);
  15886. }
  15887. mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  15888. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  15889. mBfIRBuilder->RestoreDebugLocation();
  15890. if (methodInstance == localMethod->mMethodInstanceGroup->mDefault)
  15891. {
  15892. auto checkMethodState = mCurMethodState;
  15893. while (checkMethodState != NULL)
  15894. {
  15895. BfLocalMethod* nextLocalMethod = NULL;
  15896. if (checkMethodState->mLocalMethodMap.TryGetValue(localMethod->mMethodName, &nextLocalMethod))
  15897. {
  15898. while (nextLocalMethod != NULL)
  15899. {
  15900. auto checkLocalMethod = nextLocalMethod;
  15901. nextLocalMethod = nextLocalMethod->mNextWithSameName;
  15902. if (checkLocalMethod == localMethod)
  15903. continue;
  15904. if (checkLocalMethod->mMethodInstanceGroup == NULL)
  15905. continue;
  15906. auto checkMethodInstance = checkLocalMethod->mMethodInstanceGroup->mDefault;
  15907. if (checkMethodInstance == NULL)
  15908. continue; // Not generated yet
  15909. if (CompareMethodSignatures(localMethod->mMethodInstanceGroup->mDefault, checkMethodInstance))
  15910. {
  15911. auto bfError = Fail("Method already declared with the same parameter types", methodInstance->mMethodDef->GetRefNode(), true);
  15912. if (bfError != NULL)
  15913. mCompiler->mPassInstance->MoreInfo("First declaration", checkMethodInstance->mMethodDef->GetRefNode());
  15914. }
  15915. }
  15916. }
  15917. checkMethodState = checkMethodState->mPrevMethodState;
  15918. }
  15919. }
  15920. return BfModuleMethodInstance(methodInstance);
  15921. }
  15922. int BfModule::GetLocalInferrableGenericArgCount(BfMethodDef* methodDef)
  15923. {
  15924. if ((!methodDef->mIsLocalMethod) || (methodDef->mGenericParams.size() == 0))
  15925. return 0;
  15926. auto rootMethodState = mCurMethodState->GetRootMethodState();
  15927. int rootMethodGenericParamCount = 0;
  15928. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  15929. rootMethodGenericParamCount = (int)rootMethodState->mMethodInstance->mMethodInfoEx->mGenericParams.size();
  15930. if (mCurMethodInstance == NULL)
  15931. return rootMethodGenericParamCount;
  15932. if ((mCurMethodInstance->mMethodInfoEx == NULL) || (mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo == NULL))
  15933. return rootMethodGenericParamCount;
  15934. BfLocalMethod* callerLocalMethod = mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod;
  15935. if (callerLocalMethod == NULL)
  15936. return rootMethodGenericParamCount;
  15937. BfLocalMethod* calledLocalMethod = NULL;
  15938. rootMethodState->mLocalMethodCache.TryGetValue(methodDef->mName, &calledLocalMethod);
  15939. while ((calledLocalMethod != NULL) && (callerLocalMethod != NULL))
  15940. {
  15941. if (calledLocalMethod->mOuterLocalMethod == callerLocalMethod)
  15942. return (int)callerLocalMethod->mMethodDef->mGenericParams.size();
  15943. callerLocalMethod = calledLocalMethod->mOuterLocalMethod;
  15944. }
  15945. return rootMethodGenericParamCount;
  15946. }
  15947. void BfModule::GetMethodCustomAttributes(BfMethodInstance* methodInstance)
  15948. {
  15949. auto methodDef = methodInstance->mMethodDef;
  15950. if (methodInstance->GetCustomAttributes() != NULL)
  15951. return;
  15952. auto methodDeclaration = methodDef->GetMethodDeclaration();
  15953. auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration();
  15954. auto typeInstance = methodInstance->GetOwner();
  15955. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  15956. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  15957. if ((methodDeclaration != NULL) && (methodDeclaration->mAttributes != NULL))
  15958. {
  15959. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes == NULL)
  15960. methodInstance->mMethodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  15961. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes = GetCustomAttributes(methodDeclaration->mAttributes,
  15962. ((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend)) ? BfAttributeTargets_Constructor : BfAttributeTargets_Method);
  15963. }
  15964. else if ((propertyMethodDeclaration != NULL) && (propertyMethodDeclaration->mAttributes != NULL))
  15965. {
  15966. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes == NULL)
  15967. methodInstance->mMethodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  15968. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes = GetCustomAttributes(propertyMethodDeclaration->mAttributes, BfAttributeTargets_Method);
  15969. }
  15970. }
  15971. void BfModule::SetupIRFunction(BfMethodInstance* methodInstance, StringImpl& mangledName, bool isTemporaryFunc, bool* outIsIntrinsic)
  15972. {
  15973. if (methodInstance->GetImportCallKind() == BfImportCallKind_GlobalVar)
  15974. {
  15975. // Don't create a func
  15976. return;
  15977. }
  15978. auto typeInstance = methodInstance->GetOwner();
  15979. auto methodDef = methodInstance->mMethodDef;
  15980. BfIRFunctionType funcType = mBfIRBuilder->MapMethod(methodInstance);
  15981. // Don't set these pointers during resolve pass because they may become invalid if it's just a temporary autocomplete method
  15982. if (mCompiler->mResolvePassData == NULL)
  15983. {
  15984. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mIsStatic))
  15985. {
  15986. typeInstance->mHasStaticInitMethod = true;
  15987. }
  15988. if ((methodDef->mMethodType == BfMethodType_Dtor) && (methodDef->mIsStatic))
  15989. {
  15990. typeInstance->mHasStaticDtorMethod = true;
  15991. }
  15992. if ((methodDef->mMethodType == BfMethodType_Normal) && (methodDef->mIsStatic) && (methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC))
  15993. {
  15994. typeInstance->mHasStaticMarkMethod = true;
  15995. }
  15996. if ((methodDef->mMethodType == BfMethodType_Normal) && (methodDef->mIsStatic) && (methodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS))
  15997. {
  15998. typeInstance->mHasTLSFindMethod = true;
  15999. }
  16000. }
  16001. if (isTemporaryFunc)
  16002. {
  16003. BF_ASSERT((mCompiler->mIsResolveOnly) && (mCompiler->mResolvePassData->mAutoComplete != NULL));
  16004. mangledName = "autocomplete_tmp";
  16005. }
  16006. if (!mBfIRBuilder->mIgnoreWrites)
  16007. {
  16008. BfIRFunction prevFunc;
  16009. // Remove old version (if we have one)
  16010. prevFunc = mBfIRBuilder->GetFunction(mangledName);
  16011. if (prevFunc)
  16012. {
  16013. if (methodDef->mIsExtern)
  16014. {
  16015. // Allow this
  16016. BfLogSysM("Function collision allowed multiple extern functions for %p: %d\n", methodInstance, prevFunc.mId);
  16017. }
  16018. else if (typeInstance->IsIRFuncUsed(prevFunc))
  16019. {
  16020. // We can have a collision of names when we have generic methods that differ only in
  16021. // their constraints, but they should only collide in their unspecialized form
  16022. // since only one will be chosen for a given concrete type
  16023. mCurMethodInstance->mMangleWithIdx = true;
  16024. mangledName.Clear();
  16025. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  16026. prevFunc = mBfIRBuilder->GetFunction(mangledName);
  16027. BfLogSysM("Function collision forced mangleWithIdx for %p: %d\n", methodInstance, prevFunc.mId);
  16028. }
  16029. else
  16030. {
  16031. BfLogSysM("Function collision erased prevFunc %p: %d\n", methodInstance, prevFunc.mId);
  16032. mBfIRBuilder->Func_EraseFromParent(prevFunc);
  16033. }
  16034. }
  16035. }
  16036. if (typeInstance != mContext->mBfObjectType)
  16037. {
  16038. // Only allow attributes on System.Object methods that can be handled inside the DefBuilder
  16039. GetMethodCustomAttributes(methodInstance);
  16040. }
  16041. // if (prevFunc)
  16042. // {
  16043. // if (methodDef->mIsExtern)
  16044. // {
  16045. // BfLogSysM("Reusing function for %p: %d\n", methodInstance, prevFunc.mId);
  16046. // methodInstance->mIRFunction = prevFunc;
  16047. // }
  16048. // else
  16049. // {
  16050. // if ((methodInstance->IsSpecializedByAutoCompleteMethod()) ||
  16051. // ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mResolveType >= BfResolveType_GoToDefinition)))
  16052. // {
  16053. // // If we're doing re-pass over the methods for something like BfResolveType_ShowFileSymbolReferences, then allow this collision
  16054. // BfLogSysM("Ignoring function name collision\n");
  16055. // }
  16056. // else
  16057. // {
  16058. // if (methodDef->mMethodDeclaration == NULL)
  16059. // {
  16060. // AssertErrorState();
  16061. // }
  16062. // else
  16063. // {
  16064. // BF_ASSERT(mIsSpecialModule);
  16065. // if ((mCompiler->mRevision == 1) && (HasCompiledOutput()))
  16066. // {
  16067. // // We shouldn't have name collisions on the first run!
  16068. // AssertErrorState();
  16069. // }
  16070. // }
  16071. // }
  16072. // BfLogSysM("Before erase\n");
  16073. // mBfIRBuilder->Func_EraseFromParent(prevFunc);
  16074. // }
  16075. // }
  16076. bool isIntrinsic = false;
  16077. if (!methodInstance->mIRFunction)
  16078. {
  16079. BfIRFunction func;
  16080. bool wantsLLVMFunc = ((!typeInstance->IsUnspecializedType()) && (!methodDef->IsEmptyPartial())) && (funcType);
  16081. /*if (mCurTypeInstance->mTypeDef->mName->ToString() == "ClassA")
  16082. {
  16083. if (!mIsReified)
  16084. wantsLLVMFunc = false;
  16085. }*/
  16086. if (wantsLLVMFunc)
  16087. {
  16088. func = GetIntrinsic(methodInstance, true);
  16089. if (func)
  16090. {
  16091. isIntrinsic = true;
  16092. }
  16093. else
  16094. {
  16095. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, mangledName);
  16096. BfLogSysM("Creating FuncId:%d %s in module %p\n", func.mId, mangledName.c_str(), this);
  16097. if (methodInstance->mAlwaysInline)
  16098. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_AlwaysInline);
  16099. // if (prevFunc)
  16100. // BfLogSysM("Removing Func %d, replacing with %d\n", prevFunc.mId, func.mId);
  16101. }
  16102. methodInstance->mIRFunction = func;
  16103. //if (!ignoreWrites)
  16104. //BF_ASSERT(!func.IsFake());
  16105. }
  16106. }
  16107. if (outIsIntrinsic != NULL)
  16108. *outIsIntrinsic = isIntrinsic;
  16109. if (!isIntrinsic)
  16110. SetupIRMethod(methodInstance, methodInstance->mIRFunction, methodInstance->mAlwaysInline);
  16111. }
  16112. void BfModule::CheckHotMethod(BfMethodInstance* methodInstance, const StringImpl& inMangledName)
  16113. {
  16114. if (methodInstance->mHotMethod != NULL)
  16115. return;
  16116. if ((mCompiler->mOptions.mAllowHotSwapping) && (!methodInstance->mIsUnspecialized))
  16117. {
  16118. auto srcTypeInst = methodInstance->GetOwner();
  16119. StringT<128> mangledName = inMangledName;
  16120. if (mangledName.IsEmpty())
  16121. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  16122. // We always keep the current primary method at the same address
  16123. BfHotMethod* hotMethod;
  16124. BfHotMethod** hotMethodPtr;
  16125. if (mCompiler->mHotData->mMethodMap.TryAdd(mangledName, NULL, &hotMethodPtr))
  16126. {
  16127. hotMethod = new BfHotMethod();
  16128. *hotMethodPtr = hotMethod;
  16129. hotMethod->mRefCount = 1;
  16130. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  16131. #ifdef BF_DBG_HOTMETHOD_IDX
  16132. static int sMethodIdx = 0;
  16133. hotMethod->mMethodIdx = sMethodIdx++;
  16134. #endif
  16135. BfLogSysM("HotMethodData %p created for method %p %s - %s\n", hotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  16136. }
  16137. else
  16138. {
  16139. hotMethod = *hotMethodPtr;
  16140. if ((hotMethod->mFlags & BfHotDepDataFlag_IsBound) != 0)
  16141. {
  16142. // This is a duplicate mangled name - we link to this new entry via a 'BfHotDupMethod'
  16143. auto prevHotMethod = *hotMethodPtr;
  16144. hotMethod = new BfHotMethod();
  16145. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  16146. BfHotDupMethod* hotDupMethod = new BfHotDupMethod(hotMethod);
  16147. hotDupMethod->mRefCount++;
  16148. prevHotMethod->mReferences.Add(hotDupMethod);
  16149. prevHotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_HasDup);
  16150. BfLogSysM("HotMethodData %p (duplicate of %p) created for method %p %s - %s\n", hotMethod, prevHotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  16151. }
  16152. else if (mCompiler->IsHotCompile())
  16153. {
  16154. // Link the previous version into the mPrevVersion
  16155. BfHotMethod* prevMethod = new BfHotMethod();
  16156. prevMethod->mRefCount = 1;
  16157. prevMethod->mPrevVersion = hotMethod->mPrevVersion;
  16158. hotMethod->mPrevVersion = prevMethod;
  16159. prevMethod->mSrcTypeVersion = hotMethod->mSrcTypeVersion;
  16160. hotMethod->mSrcTypeVersion = NULL;
  16161. prevMethod->mFlags = hotMethod->mFlags;
  16162. hotMethod->mFlags = BfHotDepDataFlag_IsBound;
  16163. hotMethod->mReferences.MoveTo(prevMethod->mReferences);
  16164. #ifdef BF_DBG_HOTMETHOD_NAME
  16165. prevMethod->mMangledName = hotMethod->mMangledName;
  16166. #endif
  16167. BfLogSysM("HotMethodData %p created for prevmethod of %p for method %p %s\n", prevMethod, hotMethod, methodInstance, MethodToString(methodInstance).c_str());
  16168. }
  16169. else
  16170. {
  16171. BfLogSysM("HotMethodData %p used for method %p %s - %s\n", hotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  16172. hotMethod->Clear(true);
  16173. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  16174. }
  16175. }
  16176. if (methodInstance->mIsClosure)
  16177. {
  16178. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_RetainMethodWithoutBinding);
  16179. }
  16180. hotMethod->mSrcTypeVersion = srcTypeInst->mHotTypeData->GetLatestVersion();
  16181. hotMethod->mSrcTypeVersion->mRefCount++;
  16182. hotMethod->mRefCount++;
  16183. #ifdef BF_DBG_HOTMETHOD_NAME
  16184. hotMethod->mMangledName = mangledName;
  16185. #endif
  16186. methodInstance->mHotMethod = hotMethod;
  16187. }
  16188. }
  16189. // methodDeclaration is NULL for default constructors
  16190. void BfModule::DoMethodDeclaration(BfMethodDeclaration* methodDeclaration, bool isTemporaryFunc, bool addToWorkList)
  16191. {
  16192. BP_ZONE("BfModule::BfMethodDeclaration");
  16193. // We could trigger a DoMethodDeclaration from a const resolver or other location, so we reset it here
  16194. // to effectively make mIgnoreWrites method-scoped
  16195. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mWantsIRIgnoreWrites || mCurMethodInstance->mIsUnspecialized);
  16196. SetAndRestoreValue<bool> prevIsCapturingMethodMatchInfo;
  16197. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, NULL);
  16198. if (mCompiler->IsAutocomplete())
  16199. prevIsCapturingMethodMatchInfo.Init(mCompiler->mResolvePassData->mAutoComplete->mIsCapturingMethodMatchInfo, false);
  16200. if (mCurMethodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference)
  16201. mCurMethodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingReference;
  16202. bool ignoreWrites = mBfIRBuilder->mIgnoreWrites;
  16203. if (mAwaitingInitFinish)
  16204. FinishInit();
  16205. auto typeInstance = mCurTypeInstance;
  16206. auto typeDef = typeInstance->mTypeDef;
  16207. auto methodDef = mCurMethodInstance->mMethodDef;
  16208. BF_ASSERT(methodDef->mName != "__ASSERTNAME");
  16209. if (typeInstance->IsClosure())
  16210. {
  16211. if (methodDef->mName == "Invoke")
  16212. return;
  16213. }
  16214. auto methodInstance = mCurMethodInstance;
  16215. if ((methodInstance->IsSpecializedByAutoCompleteMethod()) || (mCurTypeInstance->IsFunction()))
  16216. addToWorkList = false;
  16217. bool hasNonGenericParams = false;
  16218. bool hasGenericParams = false;
  16219. int dependentGenericStartIdx = 0;
  16220. if (methodDef->mIsLocalMethod)
  16221. {
  16222. // If we're a local generic method inside an outer generic method, we can still be considered unspecialized
  16223. // if our outer method's generic args are specialized but ours are unspecialized. This is because locals get
  16224. // instantiated uniquely for each specialized or unspecialized pass through the outer method, but the local
  16225. // method still 'inherits' the outer's generic arguments -- but we still need to make an unspecialized pass
  16226. // over the local method each time
  16227. auto rootMethodInstance = prevMethodState.mPrevVal->GetRootMethodState()->mMethodInstance;
  16228. dependentGenericStartIdx = 0;
  16229. if (rootMethodInstance->mMethodInfoEx != NULL)
  16230. dependentGenericStartIdx = (int)rootMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  16231. methodInstance->mIsUnspecialized = rootMethodInstance->mIsUnspecialized;
  16232. methodInstance->mIsUnspecializedVariation = rootMethodInstance->mIsUnspecializedVariation;
  16233. }
  16234. for (int genericArgIdx = dependentGenericStartIdx; genericArgIdx < (int) methodInstance->GetNumGenericArguments(); genericArgIdx++)
  16235. {
  16236. auto genericArgType = methodInstance->mMethodInfoEx->mMethodGenericArguments[genericArgIdx];
  16237. if (genericArgType->IsGenericParam())
  16238. {
  16239. hasGenericParams = true;
  16240. auto genericParam = (BfGenericParamType*)genericArgType;
  16241. methodInstance->mIsUnspecialized = true;
  16242. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  16243. methodInstance->mIsUnspecializedVariation = true;
  16244. }
  16245. else
  16246. {
  16247. hasNonGenericParams = true;
  16248. if (genericArgType->IsUnspecializedType())
  16249. {
  16250. methodInstance->mIsUnspecialized = true;
  16251. methodInstance->mIsUnspecializedVariation = true;
  16252. }
  16253. }
  16254. }
  16255. if ((hasGenericParams) && (hasNonGenericParams))
  16256. {
  16257. methodInstance->mIsUnspecializedVariation = true;
  16258. }
  16259. if (typeInstance->IsUnspecializedType())
  16260. {
  16261. // A specialized method within an unspecialized type is considered an unspecialized variation -- in the sense that we don't
  16262. // actually want to do method processing on it
  16263. if ((!methodInstance->mIsUnspecialized) && (methodInstance->GetNumGenericArguments() != 0))
  16264. methodInstance->mIsUnspecializedVariation = true;
  16265. methodInstance->mIsUnspecialized = true;
  16266. }
  16267. methodInstance->mIsUnspecializedVariation |= typeInstance->IsUnspecializedTypeVariation();
  16268. for (auto genericParamDef : methodDef->mGenericParams)
  16269. {
  16270. if (mCompiler->IsAutocomplete())
  16271. {
  16272. auto autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  16273. //autoComplete->CheckTypeRef()
  16274. }
  16275. }
  16276. if (methodInstance->mIsUnspecializedVariation)
  16277. {
  16278. }
  16279. if (methodInstance->mIsUnspecializedVariation)
  16280. BF_ASSERT(methodInstance->mIsUnspecialized);
  16281. if (methodDef->mMethodType == BfMethodType_Mixin)
  16282. methodInstance->mIsUnspecialized = true;
  16283. BfAutoComplete* bfAutocomplete = NULL;
  16284. if (mCompiler->mResolvePassData != NULL)
  16285. bfAutocomplete = mCompiler->mResolvePassData->mAutoComplete;
  16286. if (methodInstance->mMethodInfoEx != NULL)
  16287. {
  16288. for (int genericParamIdx = 0; genericParamIdx < (int)methodInstance->mMethodInfoEx->mGenericParams.size(); genericParamIdx++)
  16289. {
  16290. auto genericParam = methodInstance->mMethodInfoEx->mGenericParams[genericParamIdx];
  16291. if (genericParamIdx < (int)methodDef->mGenericParams.size())
  16292. {
  16293. genericParam->mExternType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  16294. }
  16295. else
  16296. {
  16297. auto externConstraintDef = genericParam->GetExternConstraintDef();
  16298. genericParam->mExternType = ResolveTypeRef(externConstraintDef->mTypeRef);
  16299. auto autoComplete = mCompiler->GetAutoComplete();
  16300. if (autoComplete != NULL)
  16301. autoComplete->CheckTypeRef(externConstraintDef->mTypeRef, false);
  16302. if (genericParam->mExternType != NULL)
  16303. {
  16304. //
  16305. }
  16306. else
  16307. genericParam->mExternType = GetPrimitiveType(BfTypeCode_Var);
  16308. }
  16309. ResolveGenericParamConstraints(genericParam, methodInstance->mIsUnspecialized);
  16310. if (genericParamIdx < (int)methodDef->mGenericParams.size())
  16311. {
  16312. auto genericParamDef = methodDef->mGenericParams[genericParamIdx];
  16313. if (bfAutocomplete != NULL)
  16314. {
  16315. for (auto nameNode : genericParamDef->mNameNodes)
  16316. {
  16317. HandleMethodGenericParamRef(nameNode, typeDef, methodDef, genericParamIdx);
  16318. }
  16319. }
  16320. }
  16321. }
  16322. for (auto genericParam : methodInstance->mMethodInfoEx->mGenericParams)
  16323. {
  16324. for (auto constraintTypeInst : genericParam->mInterfaceConstraints)
  16325. AddDependency(constraintTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  16326. if (genericParam->mTypeConstraint != NULL)
  16327. AddDependency(genericParam->mTypeConstraint, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  16328. }
  16329. }
  16330. if ((methodInstance->mIsAutocompleteMethod) && (methodDeclaration != NULL) && (!methodInstance->IsSpecializedGenericMethod()) && (methodDef->mIdx >= 0))
  16331. {
  16332. auto autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  16333. BfAstNode* nameNode = methodDeclaration->mNameNode;
  16334. if (nameNode == NULL)
  16335. {
  16336. if (auto ctorDeclaration = BfNodeDynCast<BfConstructorDeclaration>(methodDeclaration))
  16337. nameNode = ctorDeclaration->mThisToken;
  16338. }
  16339. if (autoComplete->IsAutocompleteNode(nameNode))
  16340. {
  16341. autoComplete->mInsertStartIdx = nameNode->GetSrcStart();
  16342. autoComplete->mInsertEndIdx = nameNode->GetSrcEnd();
  16343. autoComplete->mDefType = typeDef;
  16344. autoComplete->mDefMethod = methodDef;
  16345. autoComplete->SetDefinitionLocation(nameNode);
  16346. if (methodDef->mIsOverride)
  16347. {
  16348. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  16349. {
  16350. auto& ventry = typeInstance->mVirtualMethodTable[virtIdx];
  16351. if (ventry.mDeclaringMethod.mMethodNum == -1)
  16352. continue;
  16353. BfMethodInstance* virtMethod = ventry.mImplementingMethod;
  16354. if (virtMethod != NULL)
  16355. {
  16356. auto virtMethodDeclaration = virtMethod->mMethodDef->GetMethodDeclaration();
  16357. if ((virtMethod->GetOwner() == typeInstance) && (virtMethodDeclaration != NULL) &&
  16358. (virtMethodDeclaration->GetSrcStart() == methodDeclaration->GetSrcStart()))
  16359. {
  16360. // Is matching method
  16361. if (virtIdx < (int)typeInstance->mBaseType->mVirtualMethodTable.size())
  16362. {
  16363. auto baseType = typeInstance->mBaseType;
  16364. if (baseType != NULL)
  16365. {
  16366. while ((baseType->mBaseType != NULL) && (virtIdx < baseType->mBaseType->mVirtualMethodTableSize))
  16367. baseType = baseType->mBaseType;
  16368. BfMethodInstance* baseVirtMethod = baseType->mVirtualMethodTable[virtIdx].mImplementingMethod;
  16369. autoComplete->SetDefinitionLocation(baseVirtMethod->mMethodDef->GetRefNode(), true);
  16370. autoComplete->mDefType = baseType->mTypeDef;
  16371. autoComplete->mDefMethod = baseVirtMethod->mMethodDef;
  16372. }
  16373. }
  16374. break;
  16375. }
  16376. }
  16377. }
  16378. }
  16379. }
  16380. }
  16381. bool reportErrors = true;
  16382. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  16383. reportErrors = true;
  16384. // Only the defining contexts needs to report errors here
  16385. SetAndRestoreValue<bool> prevReporErrors(mReportErrors, reportErrors);
  16386. if (methodDef->mMethodType == BfMethodType_Dtor)
  16387. {
  16388. if (methodDef->mIsStatic)
  16389. {
  16390. }
  16391. else
  16392. {
  16393. if ((typeInstance->IsStruct()) || (typeInstance->IsTypedPrimitive()))
  16394. {
  16395. BfAstNode* refNode = methodDeclaration;
  16396. if (refNode == NULL)
  16397. {
  16398. // Whatever caused this ctor to be generated should have caused another failure
  16399. // But that failure might not be generated until the ctor is generated
  16400. }
  16401. else
  16402. {
  16403. auto dtorDecl = BfNodeDynCast<BfDestructorDeclaration>(methodDeclaration);
  16404. if (dtorDecl != NULL)
  16405. refNode = dtorDecl->mThisToken;
  16406. Fail("Structs cannot have destructors", refNode);
  16407. }
  16408. }
  16409. auto methodDeclaration = methodDef->GetMethodDeclaration();
  16410. if ((methodDeclaration != NULL) && (methodDeclaration->mVirtualSpecifier != NULL) &&
  16411. (mCurTypeInstance != mContext->mBfObjectType))
  16412. {
  16413. Fail("Virtual specifier is not required, all destructors are implicitly virtual.", methodDeclaration->mVirtualSpecifier);
  16414. }
  16415. }
  16416. }
  16417. BfType* resolvedReturnType = NULL;
  16418. if (((methodDef->mMethodType == BfMethodType_Normal) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend) || (methodDef->mMethodType == BfMethodType_PropertyGetter) || (methodDef->mMethodType == BfMethodType_Operator)) &&
  16419. (methodDef->mReturnTypeRef != NULL))
  16420. {
  16421. SetAndRestoreValue<bool> prevIngoreErrors(mIgnoreErrors, mIgnoreErrors || (methodDef->GetPropertyDeclaration() != NULL));
  16422. resolvedReturnType = ResolveTypeRef(methodDef->mReturnTypeRef, BfPopulateType_Declaration,
  16423. (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_AllowRef | BfResolveTypeRefFlag_AllowRefGeneric));
  16424. if ((resolvedReturnType != NULL) && (resolvedReturnType->IsVar()) && (methodDef->mMethodType != BfMethodType_Mixin))
  16425. {
  16426. Fail("Cannot declare var return types", methodDef->mReturnTypeRef);
  16427. resolvedReturnType = GetPrimitiveType(BfTypeCode_Var);
  16428. }
  16429. if (resolvedReturnType == NULL)
  16430. resolvedReturnType = GetPrimitiveType(BfTypeCode_Var);
  16431. }
  16432. else
  16433. {
  16434. resolvedReturnType = ResolveTypeDef(mSystem->mTypeVoid);
  16435. }
  16436. BF_ASSERT(resolvedReturnType != NULL);
  16437. mCurMethodInstance->mReturnType = resolvedReturnType;
  16438. //TODO: We used to NOT add the return value dependency for specialized methods, but when we have types that are
  16439. // specialized based on the method's generic param then they can get deleted if no one else has referred to them (yet)
  16440. //if (!methodInstance->IsSpecializedGenericMethod())
  16441. AddDependency(resolvedReturnType, typeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  16442. if (methodDef->mExplicitInterface != NULL)
  16443. {
  16444. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  16445. mCompiler->mResolvePassData->mAutoComplete->CheckTypeRef(methodDef->mExplicitInterface, false);
  16446. auto explicitInterface = ResolveTypeRef(methodDef->mExplicitInterface, BfPopulateType_Declaration);
  16447. if (explicitInterface != NULL)
  16448. mCurMethodInstance->GetMethodInfoEx()->mExplicitInterface = explicitInterface->ToTypeInstance();
  16449. if ((mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mExplicitInterface != NULL))
  16450. {
  16451. bool interfaceFound = false;
  16452. for (auto ifaceInst : typeInstance->mInterfaces)
  16453. interfaceFound |= ifaceInst.mInterfaceType == mCurMethodInstance->mMethodInfoEx->mExplicitInterface;
  16454. if (!interfaceFound)
  16455. {
  16456. if (methodDef->mMethodDeclaration != NULL)
  16457. Fail("Containing class has not declared to implement this interface", methodDef->mMethodDeclaration);
  16458. else
  16459. {
  16460. // For property decls, we should have already given the error during type population
  16461. if (mCompiler->mRevision == 1)
  16462. AssertErrorState();
  16463. }
  16464. }
  16465. }
  16466. }
  16467. bool isThisStruct = mCurTypeInstance->IsStruct();
  16468. BfType* thisType = NULL;
  16469. if ((!methodDef->mIsStatic) && (!mCurTypeInstance->IsValuelessType()))
  16470. {
  16471. if ((isThisStruct) || (mCurTypeInstance->IsTypedPrimitive()))
  16472. {
  16473. thisType = mCurTypeInstance;
  16474. if (thisType == NULL)
  16475. return;
  16476. if ((thisType->IsSplattable()) && (!methodDef->HasNoThisSplat()))
  16477. {
  16478. BfTypeUtils::SplatIterate([&](BfType* checkType)
  16479. {
  16480. PopulateType(checkType, BfPopulateType_Data);
  16481. }, thisType);
  16482. }
  16483. }
  16484. else
  16485. {
  16486. thisType = mCurTypeInstance;
  16487. PopulateType(thisType, BfPopulateType_Declaration);
  16488. }
  16489. }
  16490. int implicitParamCount = 0;
  16491. if ((mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo != NULL))
  16492. implicitParamCount = (int)methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries.size();
  16493. methodInstance->mMethodDef->mParams.Reserve((int)methodDef->mParams.size());
  16494. bool hadDelegateParams = false;
  16495. bool hadParams = false;
  16496. for (int paramIdx = 0; paramIdx < (int)methodDef->mParams.size() + implicitParamCount; paramIdx++)
  16497. {
  16498. BfClosureCapturedEntry* closureCaptureEntry = NULL;
  16499. BfParameterDef* paramDef = NULL;
  16500. int paramDefIdx = -1;
  16501. if (paramIdx < implicitParamCount)
  16502. closureCaptureEntry = &methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries[paramIdx];
  16503. else
  16504. {
  16505. paramDefIdx = paramIdx - implicitParamCount;
  16506. paramDef = methodDef->mParams[paramDefIdx];
  16507. }
  16508. if (hadParams)
  16509. break;
  16510. if ((paramDef != NULL) && (mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL) &&
  16511. (paramDef->mParamKind != BfParamKind_AppendIdx))
  16512. mCompiler->mResolvePassData->mAutoComplete->CheckTypeRef(paramDef->mTypeRef, false);
  16513. if ((paramDef != NULL) && (paramDef->mParamDeclaration != NULL) && (paramDef->mParamDeclaration->mAttributes != NULL))
  16514. {
  16515. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes == NULL)
  16516. methodInstance->mMethodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  16517. while ((int)methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.size() < paramIdx)
  16518. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.push_back(NULL);
  16519. auto customAttributes = GetCustomAttributes(paramDef->mParamDeclaration->mAttributes, BfAttributeTargets_Parameter);
  16520. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.push_back(customAttributes);
  16521. }
  16522. BfType* resolvedParamType = NULL;
  16523. if (closureCaptureEntry != NULL)
  16524. resolvedParamType = closureCaptureEntry->mType;
  16525. else if (paramDef->mTypeRef->IsA<BfLetTypeReference>())
  16526. {
  16527. Fail("Cannot declare 'let' parameters", paramDef->mTypeRef);
  16528. resolvedParamType = mContext->mBfObjectType;
  16529. }
  16530. else if (paramDef->mTypeRef->IsA<BfVarTypeReference>())
  16531. {
  16532. if (methodDef->mMethodType != BfMethodType_Mixin)
  16533. {
  16534. Fail("Cannot declare var parameters", paramDef->mTypeRef);
  16535. resolvedParamType = mContext->mBfObjectType;
  16536. }
  16537. else
  16538. resolvedParamType = GetPrimitiveType(BfTypeCode_Var);
  16539. }
  16540. BfType* unresolvedParamType = resolvedParamType;
  16541. bool wasGenericParam = false;
  16542. if (resolvedParamType == NULL)
  16543. {
  16544. SetAndRestoreValue<bool> prevIngoreErrors(mIgnoreErrors, mIgnoreErrors || (methodDef->GetPropertyDeclaration() != NULL));
  16545. resolvedParamType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration,
  16546. (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_AllowRef | BfResolveTypeRefFlag_AllowRefGeneric | BfResolveTypeRefFlag_AllowGenericMethodParamConstValue));
  16547. }
  16548. if (resolvedParamType == NULL)
  16549. {
  16550. resolvedParamType = GetPrimitiveType(BfTypeCode_Var);
  16551. unresolvedParamType = resolvedParamType;
  16552. if (mCurTypeInstance->IsBoxed())
  16553. {
  16554. auto boxedType = (BfBoxedType*)mCurTypeInstance;
  16555. // If we failed a lookup here then we better have also failed it in the original type
  16556. BF_ASSERT(boxedType->mElementType->mModule->mHadBuildError || mContext->mFailTypes.Contains(boxedType->mElementType));
  16557. }
  16558. }
  16559. if (!methodInstance->IsSpecializedGenericMethod())
  16560. AddDependency(resolvedParamType, typeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  16561. PopulateType(resolvedParamType, BfPopulateType_Declaration);
  16562. AddDependency(resolvedParamType, mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
  16563. if ((paramDef != NULL) && (paramDef->mParamDeclaration != NULL) && (paramDef->mParamDeclaration->mInitializer != NULL) &&
  16564. (!paramDef->mParamDeclaration->mInitializer->IsA<BfBlock>()))
  16565. {
  16566. BfMethodState methodState;
  16567. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  16568. methodState.mTempKind = BfMethodState::TempKind_Static;
  16569. BfTypedValue defaultValue;
  16570. if (resolvedParamType->IsConstExprValue())
  16571. {
  16572. auto constExprType = (BfConstExprValueType*)resolvedParamType;
  16573. BfExprEvaluator exprEvaluator(this);
  16574. exprEvaluator.mExpectingType = constExprType->mType;
  16575. exprEvaluator.GetLiteral(NULL, constExprType->mValue);
  16576. defaultValue = exprEvaluator.GetResult();
  16577. }
  16578. else
  16579. {
  16580. BfConstResolver constResolver(this);
  16581. defaultValue = constResolver.Resolve(paramDef->mParamDeclaration->mInitializer, resolvedParamType, BfConstResolveFlag_NoCast);
  16582. if ((defaultValue) && (defaultValue.mType != resolvedParamType))
  16583. {
  16584. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  16585. auto castedDefaultValue = Cast(paramDef->mParamDeclaration->mInitializer, defaultValue, resolvedParamType, (BfCastFlags)(BfCastFlags_SilentFail | BfCastFlags_NoConversionOperator));
  16586. if ((castedDefaultValue) && (castedDefaultValue.mValue.IsConst()))
  16587. {
  16588. defaultValue = castedDefaultValue; // Good!
  16589. }
  16590. else if (!CanImplicitlyCast(defaultValue, resolvedParamType))
  16591. {
  16592. // We only care that we get a constant value that can be implicitly casted at the callsite- even if that requires
  16593. // a conversion operator.
  16594. // This should throw an error
  16595. defaultValue = Cast(paramDef->mParamDeclaration->mInitializer, defaultValue, resolvedParamType);
  16596. AssertErrorState();
  16597. if (!defaultValue.mValue.IsConst())
  16598. defaultValue = BfTypedValue();
  16599. }
  16600. }
  16601. }
  16602. if (!defaultValue)
  16603. {
  16604. defaultValue = GetDefaultTypedValue(resolvedParamType);
  16605. if (!defaultValue.mValue.IsConst())
  16606. defaultValue = BfTypedValue();
  16607. }
  16608. if (defaultValue)
  16609. {
  16610. BF_ASSERT(defaultValue.mValue.IsConst());
  16611. while ((int)mCurMethodInstance->mDefaultValues.size() < paramDefIdx)
  16612. mCurMethodInstance->mDefaultValues.Add(BfIRValue());
  16613. CurrentAddToConstHolder(defaultValue.mValue);
  16614. mCurMethodInstance->mDefaultValues.Add(defaultValue.mValue);
  16615. }
  16616. }
  16617. if ((paramDef != NULL) && (paramDef->mParamKind == BfParamKind_Params))
  16618. {
  16619. bool addParams = true;
  16620. bool isValid = false;
  16621. auto resolvedParamTypeInst = resolvedParamType->ToTypeInstance();
  16622. if ((resolvedParamTypeInst != NULL) && (resolvedParamTypeInst->mTypeDef == mCompiler->mSpanTypeDef))
  16623. {
  16624. // Span<T>
  16625. isValid = true;
  16626. }
  16627. else if (resolvedParamType->IsArray())
  16628. {
  16629. // Array is the 'normal' params type
  16630. isValid = true;
  16631. }
  16632. else if ((resolvedParamType->IsDelegate()) || (resolvedParamType->IsFunction()))
  16633. {
  16634. hadDelegateParams = true;
  16635. // This means we copy the params from a delegate
  16636. BfMethodParam methodParam;
  16637. methodParam.mResolvedType = resolvedParamType;
  16638. methodParam.mParamDefIdx = paramDefIdx;
  16639. methodParam.mDelegateParamIdx = 0;
  16640. auto invokeMethodInstance = methodParam.GetDelegateParamInvoke();
  16641. for (int delegateParamIdx = 0; delegateParamIdx < invokeMethodInstance->GetParamCount(); delegateParamIdx++)
  16642. {
  16643. methodParam.mDelegateParamIdx = delegateParamIdx;
  16644. mCurMethodInstance->mParams.Add(methodParam);
  16645. auto paramType = invokeMethodInstance->GetParamType(delegateParamIdx);
  16646. if (!methodInstance->IsSpecializedGenericMethod())
  16647. AddDependency(paramType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  16648. }
  16649. isValid = true;
  16650. addParams = false;
  16651. }
  16652. else if (resolvedParamType->IsGenericParam())
  16653. {
  16654. auto genericParamInstance = GetGenericParamInstance((BfGenericParamType*)resolvedParamType);
  16655. if (genericParamInstance->mTypeConstraint != NULL)
  16656. {
  16657. auto typeInstConstraint = genericParamInstance->mTypeConstraint->ToTypeInstance();
  16658. if (genericParamInstance->mTypeConstraint->IsArray())
  16659. {
  16660. BfMethodParam methodParam;
  16661. methodParam.mResolvedType = resolvedParamType;
  16662. methodParam.mParamDefIdx = paramDefIdx;
  16663. mCurMethodInstance->mParams.Add(methodParam);
  16664. isValid = true;
  16665. }
  16666. else if ((genericParamInstance->mTypeConstraint->IsDelegate()) || (genericParamInstance->mTypeConstraint->IsFunction()) ||
  16667. ((genericParamInstance != NULL) && (typeInstConstraint != NULL) &&
  16668. ((typeInstConstraint->mTypeDef == mCompiler->mDelegateTypeDef) || (typeInstConstraint->mTypeDef == mCompiler->mFunctionTypeDef))))
  16669. {
  16670. mCurMethodInstance->mHadGenericDelegateParams = true;
  16671. isValid = true;
  16672. addParams = false;
  16673. }
  16674. }
  16675. }
  16676. else
  16677. {
  16678. auto paramTypeInst = resolvedParamType->ToTypeInstance();
  16679. if ((paramTypeInst != NULL) &&
  16680. ((paramTypeInst->mTypeDef == mCompiler->mDelegateTypeDef) || (paramTypeInst->mTypeDef == mCompiler->mFunctionTypeDef)))
  16681. {
  16682. // If we have a 'params T' and 'T' gets specialized with actually 'Delegate' or 'Function' then just ignore it
  16683. isValid = true;
  16684. addParams = false;
  16685. }
  16686. }
  16687. if (!isValid)
  16688. {
  16689. Fail("Parameters with 'params' specifiers can only be used for array, span, delegate, or function types", paramDef->mParamDeclaration->mModToken);
  16690. // Failure case, make it an Object[]
  16691. resolvedParamType = CreateArrayType(mContext->mBfObjectType, 1);
  16692. }
  16693. if (addParams)
  16694. {
  16695. BfMethodParam methodParam;
  16696. methodParam.mResolvedType = resolvedParamType;
  16697. methodParam.mParamDefIdx = paramDefIdx;
  16698. mCurMethodInstance->mParams.push_back(methodParam);
  16699. }
  16700. if (paramDefIdx < (int)methodDef->mParams.size() - 1)
  16701. {
  16702. Fail("Only the last parameter can specify 'params'", paramDef->mParamDeclaration->mModToken);
  16703. }
  16704. }
  16705. else
  16706. {
  16707. BfMethodParam methodParam;
  16708. methodParam.mResolvedType = resolvedParamType;
  16709. methodParam.mParamDefIdx = paramDefIdx;
  16710. mCurMethodInstance->mParams.Add(methodParam);
  16711. }
  16712. }
  16713. if (hadDelegateParams)
  16714. {
  16715. HashSet<String> usedNames;
  16716. Dictionary<int, int> usedParamDefIdx;
  16717. for (auto methodParam : methodDef->mParams)
  16718. {
  16719. usedNames.Add(methodParam->mName);
  16720. }
  16721. for (auto& methodParam : mCurMethodInstance->mParams)
  16722. {
  16723. if ((methodParam.mParamDefIdx != -1) && (methodParam.mDelegateParamIdx == 0))
  16724. {
  16725. int* refCount = NULL;
  16726. usedParamDefIdx.TryAdd(methodParam.mParamDefIdx, NULL, &refCount);
  16727. (*refCount)++;
  16728. }
  16729. }
  16730. for (auto& methodParam : mCurMethodInstance->mParams)
  16731. {
  16732. if (methodParam.mDelegateParamIdx != -1)
  16733. {
  16734. if (usedParamDefIdx[methodParam.mParamDefIdx] > 1)
  16735. methodParam.mDelegateParamNameCombine = true;
  16736. BfMethodInstance* invokeMethodInstance = methodParam.GetDelegateParamInvoke();
  16737. String paramName = invokeMethodInstance->GetParamName(methodParam.mDelegateParamIdx);
  16738. if (usedNames.Contains(paramName))
  16739. methodParam.mDelegateParamNameCombine = true;
  16740. }
  16741. }
  16742. }
  16743. int argIdx = 0;
  16744. PopulateType(methodInstance->mReturnType, BfPopulateType_Data);
  16745. if (methodInstance->HasStructRet())
  16746. argIdx++;
  16747. if (!methodDef->mIsStatic)
  16748. {
  16749. if (methodInstance->GetParamIsSplat(-1))
  16750. argIdx += methodInstance->GetParamType(-1)->GetSplatCount();
  16751. else if (!methodInstance->GetOwner()->IsValuelessType())
  16752. argIdx++;
  16753. }
  16754. for (auto& methodParam : mCurMethodInstance->mParams)
  16755. {
  16756. if (methodParam.mResolvedType->IsMethodRef())
  16757. {
  16758. methodParam.mIsSplat = true;
  16759. }
  16760. else if (methodParam.mResolvedType->IsComposite())
  16761. {
  16762. PopulateType(methodParam.mResolvedType, BfPopulateType_Data);
  16763. if (methodParam.mResolvedType->IsSplattable())
  16764. {
  16765. int splatCount = methodParam.mResolvedType->GetSplatCount();
  16766. if (argIdx + splatCount <= mCompiler->mOptions.mMaxSplatRegs)
  16767. {
  16768. methodParam.mIsSplat = true;
  16769. argIdx += splatCount;
  16770. continue;
  16771. }
  16772. }
  16773. }
  16774. argIdx++;
  16775. }
  16776. bool hasExternSpecifier = (methodDeclaration != NULL) && (methodDeclaration->mExternSpecifier != NULL);
  16777. if ((hasExternSpecifier) && (methodDeclaration->mBody != NULL))
  16778. {
  16779. Fail("Cannot 'extern' and declare a body", methodDeclaration->mExternSpecifier);
  16780. }
  16781. else if ((methodDeclaration != NULL) && (methodDeclaration->mBody == NULL) && (!hasExternSpecifier) &&
  16782. (!typeInstance->IsInterface()) && (!mCurTypeInstance->IsDelegate()) && (!mCurTypeInstance->IsFunction()) &&
  16783. (!methodDef->mIsPartial) && (!methodDef->mIsAbstract) &&
  16784. (!methodDef->mIsSkipCall))
  16785. {
  16786. if (methodDeclaration->mEndSemicolon == NULL)
  16787. {
  16788. AssertParseErrorState();
  16789. }
  16790. else
  16791. {
  16792. bool isError = true;
  16793. if (typeInstance->IsTypedPrimitive())
  16794. {
  16795. if (auto operatorDeclaration = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  16796. {
  16797. if ((operatorDeclaration->mIsConvOperator) && (methodInstance->mParams.size() == 1))
  16798. {
  16799. if (((methodInstance->mReturnType == typeInstance) && (methodInstance->GetParamType(0) == typeInstance->GetUnderlyingType())) ||
  16800. ((methodInstance->mReturnType == typeInstance->GetUnderlyingType()) && (methodInstance->GetParamType(0) == typeInstance)))
  16801. {
  16802. isError = false;
  16803. }
  16804. }
  16805. }
  16806. }
  16807. if (isError)
  16808. {
  16809. Fail(StrFormat("'%s' must declare a body because it is not marked abstract, extern, or partial",
  16810. MethodToString(methodInstance).c_str()),
  16811. methodDef->GetRefNode());
  16812. }
  16813. }
  16814. }
  16815. if (methodDef->IsEmptyPartial())
  16816. hasExternSpecifier = true;
  16817. if (!methodInstance->IsAutocompleteMethod())
  16818. {
  16819. auto defaultMethodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  16820. int implicitParamCount = methodInstance->GetImplicitParamCount();
  16821. int defaultImplicitParamCount = defaultMethodInstance->GetImplicitParamCount();
  16822. int actualParamCount = (int)methodInstance->mParams.size() - implicitParamCount;
  16823. BF_ASSERT((actualParamCount == defaultMethodInstance->mParams.size() - defaultImplicitParamCount) || (defaultMethodInstance->mHadGenericDelegateParams));
  16824. mCurMethodInstance->mHadGenericDelegateParams = defaultMethodInstance->mHadGenericDelegateParams;
  16825. int paramIdx = 0;
  16826. int defaultParamIdx = 0;
  16827. while (true)
  16828. {
  16829. bool isDone = paramIdx + implicitParamCount >= (int)methodInstance->mParams.size();
  16830. bool isDefaultDone = defaultParamIdx + defaultImplicitParamCount >= (int)defaultMethodInstance->mParams.size();
  16831. if ((!isDone) && (methodInstance->mParams[paramIdx + implicitParamCount].mDelegateParamIdx >= 0))
  16832. {
  16833. paramIdx++;
  16834. continue;
  16835. }
  16836. if ((!isDefaultDone) && (defaultMethodInstance->mParams[defaultParamIdx + defaultImplicitParamCount].mDelegateParamIdx >= 0))
  16837. {
  16838. defaultParamIdx++;
  16839. continue;
  16840. }
  16841. if ((isDone) || (isDefaultDone))
  16842. {
  16843. // 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
  16844. // to cause us to throw an assertion in the declaration here
  16845. if (!defaultMethodInstance->mHadGenericDelegateParams)
  16846. BF_ASSERT((isDone) && (isDefaultDone));
  16847. break;
  16848. }
  16849. methodInstance->mParams[paramIdx + implicitParamCount].mWasGenericParam = defaultMethodInstance->mParams[defaultParamIdx + defaultImplicitParamCount].mResolvedType->IsGenericParam();
  16850. paramIdx++;
  16851. defaultParamIdx++;
  16852. }
  16853. }
  16854. StringT<128> mangledName;
  16855. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  16856. for (int paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  16857. {
  16858. auto paramType = methodInstance->GetParamType(paramIdx);
  16859. if (paramType->IsComposite())
  16860. PopulateType(paramType, BfPopulateType_Data);
  16861. if (!methodInstance->IsParamSkipped(paramIdx))
  16862. {
  16863. if (paramType->IsStruct())
  16864. {
  16865. //
  16866. }
  16867. else
  16868. {
  16869. PopulateType(paramType, BfPopulateType_Declaration);
  16870. }
  16871. }
  16872. }
  16873. // Only process method in default unspecialized mode, not in variations
  16874. if (methodInstance->mIsUnspecializedVariation)
  16875. return;
  16876. PopulateType(resolvedReturnType, BfPopulateType_Data);
  16877. auto retLLVMType = mBfIRBuilder->MapType(resolvedReturnType);
  16878. if (resolvedReturnType->IsValuelessType())
  16879. retLLVMType = mBfIRBuilder->GetPrimitiveType(BfTypeCode_None);
  16880. if (!mBfIRBuilder->mIgnoreWrites)
  16881. {
  16882. bool isIntrinsic = false;
  16883. if (!methodInstance->mIRFunction)
  16884. SetupIRFunction(methodInstance, mangledName, isTemporaryFunc, &isIntrinsic);
  16885. if (isIntrinsic)
  16886. {
  16887. addToWorkList = false;
  16888. }
  16889. }
  16890. auto func = methodInstance->mIRFunction;
  16891. // if (methodInstance->mIsReified)
  16892. // CheckHotMethod(methodInstance, mangledName);
  16893. 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);
  16894. SizedArray<BfIRMDNode, 8> diParams;
  16895. diParams.push_back(mBfIRBuilder->DbgGetType(resolvedReturnType));
  16896. if ((!methodDef->mIsStatic) && (typeDef->mIsStatic) && (methodDef->mMethodDeclaration != NULL))
  16897. {
  16898. //CS0708
  16899. Fail("Cannot declare instance members in a static class", methodDef->GetRefNode());
  16900. }
  16901. if ((methodDef->mIsVirtual) && (methodDef->mGenericParams.size() != 0))
  16902. {
  16903. Fail("Virtual generic methods not supported", methodDeclaration->mVirtualSpecifier);
  16904. methodDef->mIsVirtual = false;
  16905. }
  16906. if ((methodDeclaration != NULL) && (methodDeclaration->mMutSpecifier != NULL) && (!mCurTypeInstance->IsBoxed()) && (!methodInstance->mIsForeignMethodDef))
  16907. {
  16908. if (methodDef->mIsStatic)
  16909. Warn(0, "Unnecessary 'mut' specifier, static methods have no implicit 'this' target to mutate", methodDeclaration->mMutSpecifier);
  16910. else if ((!mCurTypeInstance->IsValueType()) && (!mCurTypeInstance->IsInterface()))
  16911. Warn(0, "Unnecessary 'mut' specifier, methods of reference types are implicitly mutating", methodDeclaration->mMutSpecifier);
  16912. else if (methodDef->mMethodType == BfMethodType_Ctor)
  16913. Warn(0, "Unnecessary 'mut' specifier, constructors are implicitly mutating", methodDeclaration->mMutSpecifier);
  16914. else if (methodDef->mMethodType == BfMethodType_Dtor)
  16915. Warn(0, "Unnecessary 'mut' specifier, destructors are implicitly mutating", methodDeclaration->mMutSpecifier);
  16916. }
  16917. if (isTemporaryFunc)
  16918. {
  16919. // This handles temporary methods for autocomplete types
  16920. BF_ASSERT(mIsScratchModule);
  16921. BF_ASSERT(mCompiler->IsAutocomplete());
  16922. BfLogSysM("DoMethodDeclaration autocomplete bailout\n");
  16923. return; // Bail out early for autocomplete pass
  16924. }
  16925. //TODO: We used to have this (this != mContext->mExternalFuncModule) check, but it caused us to keep around
  16926. // an invalid mFuncRefernce (which came from GetMethodInstanceAtIdx) which later got remapped by the
  16927. // autocompleter. Why did we have this check anyway?
  16928. /*if ((typeInstance->mContext != mContext) && (!methodDef->IsEmptyPartial()))
  16929. {
  16930. AddMethodReference(methodInstance);
  16931. mFuncReferences[methodInstance] = func;
  16932. BfLogSysM("Adding func reference (DoMethodDeclaration). Module:%p MethodInst:%p LLVMFunc:%p\n", this, methodInstance, func);
  16933. }*/
  16934. if (mParentModule != NULL)
  16935. {
  16936. // For extension modules we need to keep track of our own methods so we can know which methods
  16937. // we have defined ourselves and which are from the parent module or other extensions
  16938. if (!func.IsFake())
  16939. mFuncReferences[methodInstance] = func;
  16940. }
  16941. if (addToWorkList)
  16942. {
  16943. bool wasAwaitingDecl = methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl;
  16944. if (wasAwaitingDecl)
  16945. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingReference;
  16946. if ((!methodDef->mIsAbstract) && (!methodInstance->mIgnoreBody))
  16947. {
  16948. if (!wasAwaitingDecl)
  16949. AddMethodToWorkList(methodInstance);
  16950. }
  16951. else
  16952. {
  16953. BfLogSysM("DoMethodDeclaration ignoring method body %d %d %d\n", hasExternSpecifier, methodDef->mIsAbstract, methodInstance->mIgnoreBody);
  16954. methodInstance->mIgnoreBody = true;
  16955. if (typeInstance->IsUnspecializedType())
  16956. {
  16957. // Don't hold on to actual Function for unspecialized types
  16958. methodInstance->mIRFunction = BfIRFunction();
  16959. }
  16960. }
  16961. }
  16962. if ((!methodInstance->IsSpecializedGenericMethodOrType()) && (!mCurTypeInstance->IsBoxed()) &&
  16963. (!methodDef->mIsLocalMethod) &&
  16964. (!CheckDefineMemberProtection(methodDef->mProtection, methodInstance->mReturnType)))
  16965. {
  16966. if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  16967. {
  16968. //TODO:
  16969. //CS0053
  16970. Fail(StrFormat("Inconsistent accessibility: property type '%s' is less accessible than property '%s'",
  16971. TypeToString(methodInstance->mReturnType).c_str(), MethodToString(methodInstance).c_str()),
  16972. methodDef->mReturnTypeRef, true);
  16973. }
  16974. else
  16975. {
  16976. //CS0050
  16977. Fail(StrFormat("Inconsistent accessibility: return type '%s' is less accessible than method '%s'",
  16978. TypeToString(methodInstance->mReturnType).c_str(), MethodToString(methodInstance).c_str()),
  16979. methodDef->mReturnTypeRef, true);
  16980. }
  16981. }
  16982. if ((typeInstance->IsInterface()) && (methodDef->mMethodType == BfMethodType_Ctor))
  16983. {
  16984. Fail("Interfaces cannot contain constructors", methodDeclaration);
  16985. }
  16986. // Don't compare specialized generic methods against normal methods
  16987. if ((((mCurMethodInstance->mIsUnspecialized) || (mCurMethodInstance->mMethodDef->mGenericParams.size() == 0))) &&
  16988. (!methodDef->mIsLocalMethod))
  16989. {
  16990. if (!methodInstance->mIsForeignMethodDef)
  16991. {
  16992. typeDef->PopulateMemberSets();
  16993. BfMethodDef* nextMethod = NULL;
  16994. BfMemberSetEntry* entry = NULL;
  16995. if (typeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  16996. nextMethod = (BfMethodDef*)entry->mMemberDef;
  16997. while (nextMethod != NULL)
  16998. {
  16999. auto checkMethod = nextMethod;
  17000. nextMethod = nextMethod->mNextWithSameName;
  17001. if ((checkMethod != methodDef) && (typeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault != NULL))
  17002. {
  17003. auto checkMethodInstance = typeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  17004. if (((checkMethodInstance->mChainType == BfMethodChainType_None) || (checkMethodInstance->mChainType == BfMethodChainType_ChainHead)) &&
  17005. (checkMethodInstance->GetExplicitInterface() == methodInstance->GetExplicitInterface()) &&
  17006. (CompareMethodSignatures(checkMethodInstance, mCurMethodInstance)))
  17007. {
  17008. bool canChain = false;
  17009. if ((methodDef->mParams.empty()) &&
  17010. (checkMethodInstance->mMethodDef->mIsStatic == methodInstance->mMethodDef->mIsStatic))
  17011. {
  17012. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) || (methodDef->mMethodType == BfMethodType_Dtor))
  17013. canChain = true;
  17014. else if (methodDef->mMethodType == BfMethodType_Normal)
  17015. {
  17016. if ((methodDef->mName == BF_METHODNAME_MARKMEMBERS) ||
  17017. (methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC) ||
  17018. (methodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS))
  17019. canChain = true;
  17020. }
  17021. }
  17022. if (canChain)
  17023. {
  17024. bool isBetter;
  17025. bool isWorse;
  17026. CompareDeclTypes(checkMethodInstance->mMethodDef->mDeclaringType, methodInstance->mMethodDef->mDeclaringType, isBetter, isWorse);
  17027. if (isBetter && !isWorse)
  17028. {
  17029. methodInstance->mChainType = BfMethodChainType_ChainHead;
  17030. checkMethodInstance->mChainType = BfMethodChainType_ChainMember;
  17031. }
  17032. else
  17033. {
  17034. checkMethodInstance->mChainType = BfMethodChainType_ChainHead;
  17035. methodInstance->mChainType = BfMethodChainType_ChainMember;
  17036. }
  17037. }
  17038. else if ((checkMethod->mBody == NULL) && (methodDef->mBody != NULL) &&
  17039. (checkMethod->mDeclaringType != methodDef->mDeclaringType))
  17040. {
  17041. // We're allowed to override an empty-bodied method
  17042. checkMethodInstance->mChainType = BfMethodChainType_ChainSkip;
  17043. }
  17044. else
  17045. {
  17046. if (!typeInstance->IsTypeMemberAccessible(checkMethod->mDeclaringType, methodDef->mDeclaringType))
  17047. continue;
  17048. bool silentlyAllow = false;
  17049. if (checkMethod->mDeclaringType != methodDef->mDeclaringType)
  17050. {
  17051. if (typeInstance->IsInterface())
  17052. {
  17053. if (methodDef->mIsOverride)
  17054. silentlyAllow = true;
  17055. }
  17056. else
  17057. silentlyAllow = true;
  17058. }
  17059. if ((checkMethod->mCommutableKind == BfCommutableKind_Reverse) || (methodDef->mCommutableKind == BfCommutableKind_Reverse))
  17060. silentlyAllow = true;
  17061. if (!silentlyAllow)
  17062. {
  17063. if ((!methodDef->mName.IsEmpty()) || (checkMethodInstance->mMethodDef->mIsOperator))
  17064. {
  17065. auto refNode = methodDef->GetRefNode();
  17066. auto bfError = Fail("Method already declared with the same parameter types", refNode, true);
  17067. if (bfError != NULL)
  17068. mCompiler->mPassInstance->MoreInfo("First declaration", checkMethod->GetRefNode());
  17069. }
  17070. }
  17071. }
  17072. }
  17073. }
  17074. }
  17075. }
  17076. // Virtual methods give their error while slotting
  17077. if ((!typeInstance->IsBoxed()) && (!methodDef->mIsVirtual) && (methodDef->mProtection != BfProtection_Private) &&
  17078. (!methodDef->mIsLocalMethod) &&
  17079. (!methodInstance->mIsForeignMethodDef) && (typeInstance->mBaseType != NULL) &&
  17080. (methodDef->mMethodType == BfMethodType_Normal) && (methodDef->mMethodDeclaration != NULL))
  17081. {
  17082. bool foundHiddenMethod = false;
  17083. auto baseType = typeInstance->mBaseType;
  17084. while (baseType != NULL)
  17085. {
  17086. //for (int checkMethodIdx = 0; checkMethodIdx < (int) baseType->mTypeDef->mMethods.size(); checkMethodIdx++)
  17087. auto baseTypeDef = baseType->mTypeDef;
  17088. baseTypeDef->PopulateMemberSets();
  17089. BfMethodDef* checkMethod = NULL;
  17090. BfMemberSetEntry* entry = NULL;
  17091. if (baseTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  17092. checkMethod = (BfMethodDef*)entry->mMemberDef;
  17093. while (checkMethod != NULL)
  17094. {
  17095. if (checkMethod->mMethodDeclaration == NULL)
  17096. continue;
  17097. if (baseType->mMethodInstanceGroups.size() == 0)
  17098. {
  17099. BF_ASSERT(baseType->IsIncomplete() && mCompiler->IsAutocomplete());
  17100. break;
  17101. }
  17102. if (checkMethod == methodDef)
  17103. continue;
  17104. if (checkMethod->mName != methodDef->mName)
  17105. continue;
  17106. auto checkMethodInstance = GetRawMethodInstanceAtIdx(baseType, checkMethod->mIdx);
  17107. if (checkMethodInstance != NULL)
  17108. {
  17109. if ((checkMethodInstance->GetExplicitInterface() == methodInstance->GetExplicitInterface()) &&
  17110. (checkMethod->mProtection != BfProtection_Private) &&
  17111. (CompareMethodSignatures(checkMethodInstance, mCurMethodInstance)))
  17112. {
  17113. if (!methodDef->mIsNew)
  17114. {
  17115. BfAstNode* refNode = methodInstance->mMethodDef->GetRefNode();
  17116. if (refNode != NULL)
  17117. {
  17118. 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?
  17119. if (bfError != NULL)
  17120. bfError->mIsPersistent = true;
  17121. }
  17122. }
  17123. foundHiddenMethod = true;
  17124. break;
  17125. }
  17126. }
  17127. checkMethod = checkMethod->mNextWithSameName;
  17128. }
  17129. if (foundHiddenMethod)
  17130. break;
  17131. baseType = baseType->mBaseType;
  17132. }
  17133. if ((methodDef->mIsNew) && (!foundHiddenMethod))
  17134. {
  17135. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  17136. auto tokenNode = (propertyDeclaration != NULL) ? propertyDeclaration->mNewSpecifier :
  17137. methodDeclaration->mNewSpecifier;
  17138. Fail("Method does not hide an inherited member. The 'new' keyword is not required", tokenNode, true);
  17139. }
  17140. }
  17141. }
  17142. mCompiler->mStats.mMethodDeclarations++;
  17143. mCompiler->UpdateCompletion();
  17144. }
  17145. void BfModule::UniqueSlotVirtualMethod(BfMethodInstance* methodInstance)
  17146. {
  17147. BF_ASSERT(methodInstance->GetOwner() == mCurTypeInstance);
  17148. auto typeInstance = mCurTypeInstance;
  17149. auto methodDef = methodInstance->mMethodDef;
  17150. int virtualMethodMatchIdx = -1;
  17151. if (typeInstance->mHotTypeData != NULL)
  17152. {
  17153. if (typeInstance->mHotTypeData->mVTableOrigLength != -1)
  17154. {
  17155. BF_ASSERT(mCompiler->IsHotCompile());
  17156. // In the 'normal' case we'd assert that mIsOverride is false, but if we can't find the declaring method then we
  17157. // may slot this override anyway (?)
  17158. int vTableStart = 0;
  17159. if (typeInstance->mBaseType != NULL)
  17160. vTableStart = typeInstance->mBaseType->mVirtualMethodTableSize;
  17161. StringT<128> mangledName;
  17162. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  17163. for (int checkIdxOfs = 0; checkIdxOfs < (int)typeInstance->mHotTypeData->mVTableEntries.size(); checkIdxOfs++)
  17164. {
  17165. // O(1) checking when virtual methods haven't changed
  17166. int checkIdx = (typeInstance->mVirtualMethodTableSize - vTableStart + checkIdxOfs) % (int)typeInstance->mHotTypeData->mVTableEntries.size();
  17167. auto& entry = typeInstance->mHotTypeData->mVTableEntries[checkIdx];
  17168. if (mangledName == entry.mFuncName)
  17169. {
  17170. virtualMethodMatchIdx = vTableStart + checkIdx;
  17171. break;
  17172. }
  17173. }
  17174. if (virtualMethodMatchIdx != -1)
  17175. {
  17176. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  17177. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod = methodInstance;
  17178. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod = methodInstance;
  17179. }
  17180. typeInstance->mVirtualMethodTableSize = (int)typeInstance->mVirtualMethodTable.size();
  17181. }
  17182. }
  17183. if (virtualMethodMatchIdx == -1)
  17184. {
  17185. methodInstance->mVirtualTableIdx = typeInstance->mVirtualMethodTableSize++;
  17186. BfVirtualMethodEntry entry = { methodInstance, methodInstance };
  17187. typeInstance->mVirtualMethodTable.push_back(entry);
  17188. }
  17189. }
  17190. void BfModule::CompareDeclTypes(BfTypeDef* newDeclType, BfTypeDef* prevDeclType, bool& isBetter, bool& isWorse)
  17191. {
  17192. if ((!prevDeclType->IsExtension()) && (newDeclType->IsExtension()))
  17193. {
  17194. // When we provide an extension override in the same project a root type override
  17195. isBetter = true;
  17196. isWorse = false;
  17197. }
  17198. else
  17199. {
  17200. isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  17201. isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  17202. }
  17203. }
  17204. bool BfModule::SlotVirtualMethod(BfMethodInstance* methodInstance, BfAmbiguityContext* ambiguityContext)
  17205. {
  17206. BP_ZONE("BfModule::SlotVirtualMethod");
  17207. if (mCurTypeInstance->IsUnspecializedTypeVariation())
  17208. return false;
  17209. auto _AddVirtualDecl = [&](BfMethodInstance* declMethodInstance)
  17210. {
  17211. if (!mCompiler->mOptions.mAllowHotSwapping)
  17212. return;
  17213. if ((!methodInstance->mIsReified) || (!declMethodInstance->mIsReified))
  17214. return;
  17215. if (methodInstance->mHotMethod == NULL)
  17216. CheckHotMethod(methodInstance, "");
  17217. if (methodInstance->mHotMethod == NULL)
  17218. return;
  17219. //BF_ASSERT(declMethodInstance->mHotMethod != NULL);
  17220. if (declMethodInstance->mHotMethod == NULL)
  17221. CheckHotMethod(declMethodInstance, "");
  17222. auto virtualDecl = mCompiler->mHotData->GetVirtualDeclaration(declMethodInstance->mHotMethod);
  17223. virtualDecl->mRefCount++;
  17224. methodInstance->mHotMethod->mReferences.Add(virtualDecl);
  17225. };
  17226. auto typeInstance = mCurTypeInstance;
  17227. auto typeDef = typeInstance->mTypeDef;
  17228. auto methodDef = methodInstance->mMethodDef;
  17229. auto methodDeclaration = methodDef->GetMethodDeclaration();
  17230. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  17231. auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration();
  17232. BfAstNode* declaringNode = methodDeclaration;
  17233. if (propertyMethodDeclaration != NULL)
  17234. declaringNode = propertyMethodDeclaration->mNameNode;
  17235. BfMethodInstance* methodOverriden = NULL;
  17236. bool usedMethod = false;
  17237. BfTokenNode* virtualToken = NULL;
  17238. if (propertyDeclaration != NULL)
  17239. virtualToken = propertyDeclaration->mVirtualSpecifier;
  17240. else if (methodDeclaration != NULL)
  17241. virtualToken = methodDeclaration->mVirtualSpecifier;
  17242. if ((methodDef->mIsVirtual) && (methodDef->mIsStatic))
  17243. {
  17244. Fail("Static members cannot be marked as override, virtual, or abstract", virtualToken, true);
  17245. }
  17246. else if (methodDef->mIsVirtual)
  17247. {
  17248. if (mCompiler->IsHotCompile())
  17249. mContext->EnsureHotMangledVirtualMethodName(methodInstance);
  17250. if ((methodDef->mProtection == BfProtection_Private) && (virtualToken != NULL))
  17251. Fail("Virtual or abstract members cannot be private", virtualToken, true);
  17252. BfTypeInstance* checkBase = typeInstance;
  17253. // If we are in an extension, look in ourselves first
  17254. if (methodDef->mDeclaringType->mTypeDeclaration == typeInstance->mTypeDef->mTypeDeclaration)
  17255. checkBase = checkBase->mBaseType;
  17256. if (typeInstance->IsValueType())
  17257. {
  17258. if (typeInstance->mBaseType == NULL)
  17259. return false; // It's actually ValueType
  17260. // We allow structs to override object methods for when they get boxed, so just ignore 'override' keyword until it gets boxed
  17261. if (!methodDef->mIsOverride)
  17262. {
  17263. Fail("Structs cannot have virtual methods", virtualToken, true);
  17264. return false;
  17265. }
  17266. checkBase = mContext->mBfObjectType;
  17267. if (checkBase->mVirtualMethodTableSize == 0)
  17268. PopulateType(checkBase, BfPopulateType_Full);
  17269. if (checkBase->mDefineState < BfTypeDefineState_DefinedAndMethodsSlotted)
  17270. return false; // System circular ref, don't do struct checking on those
  17271. }
  17272. int virtualMethodMatchIdx = -1;
  17273. bool hadHidingError = false;
  17274. BfMethodInstance* bestOverrideMethodInstance = NULL;
  17275. BfMethodInstance* ambiguousOverrideMethodInstance = NULL;
  17276. int bestOverrideMethodIdx = -1;
  17277. int ambiguousOverrideMethodIdx = -1;
  17278. if (checkBase != NULL)
  17279. {
  17280. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  17281. auto lookupType = checkBase;
  17282. while (lookupType != NULL)
  17283. {
  17284. lookupType->mTypeDef->PopulateMemberSets();
  17285. BfMethodDef* nextMethodDef = NULL;
  17286. BfMemberSetEntry* entry;
  17287. if (lookupType->mTypeDef->mMethodSet.TryGetWith(methodInstance->mMethodDef->mName, &entry))
  17288. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  17289. while (nextMethodDef != NULL)
  17290. {
  17291. auto checkMethodDef = nextMethodDef;
  17292. nextMethodDef = nextMethodDef->mNextWithSameName;
  17293. if ((!checkMethodDef->mIsVirtual) || (checkMethodDef->mIsOverride))
  17294. continue;
  17295. BfMethodInstance* lookupMethodInstance = lookupType->mMethodInstanceGroups[checkMethodDef->mIdx].mDefault;
  17296. if ((lookupMethodInstance == NULL) || (lookupMethodInstance->mVirtualTableIdx == -1))
  17297. continue;
  17298. int checkMethodIdx = lookupMethodInstance->mVirtualTableIdx;
  17299. auto& baseMethodRef = baseVirtualMethodTable[checkMethodIdx];
  17300. if (baseMethodRef.mDeclaringMethod.mMethodNum == -1)
  17301. {
  17302. BF_ASSERT(mCompiler->mOptions.mHasVDataExtender);
  17303. continue;
  17304. }
  17305. BfMethodInstance* baseMethodInstance = baseVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  17306. if (baseMethodInstance == NULL)
  17307. {
  17308. AssertErrorState();
  17309. continue;
  17310. }
  17311. if ((baseMethodInstance != NULL) && (CompareMethodSignatures(baseMethodInstance, methodInstance)))
  17312. {
  17313. if (methodDef->mIsOverride)
  17314. {
  17315. BfMethodInstance* checkMethodInstance;
  17316. if (typeInstance->IsValueType())
  17317. checkMethodInstance = checkBase->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  17318. else
  17319. checkMethodInstance = typeInstance->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  17320. auto newDeclType = checkMethodInstance->mMethodDef->mDeclaringType;
  17321. if (!typeInstance->IsTypeMemberAccessible(newDeclType, methodDef->mDeclaringType->mProject))
  17322. continue;
  17323. if (bestOverrideMethodInstance != NULL)
  17324. {
  17325. auto prevDeclType = bestOverrideMethodInstance->mMethodDef->mDeclaringType;
  17326. bool isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  17327. bool isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  17328. if (isBetter == isWorse)
  17329. {
  17330. ambiguousOverrideMethodInstance = bestOverrideMethodInstance;
  17331. }
  17332. else
  17333. {
  17334. if (isWorse)
  17335. continue;
  17336. ambiguousOverrideMethodInstance = NULL;
  17337. }
  17338. }
  17339. bestOverrideMethodInstance = checkMethodInstance;
  17340. bestOverrideMethodIdx = checkMethodIdx;
  17341. }
  17342. else
  17343. {
  17344. if ((baseMethodInstance->GetOwner() != methodInstance->GetOwner()) && (!methodDef->mIsNew))
  17345. {
  17346. if (!hadHidingError)
  17347. Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use either 'override' or 'new'.", TypeToString(checkBase).c_str()), declaringNode);
  17348. hadHidingError = true;
  17349. }
  17350. }
  17351. }
  17352. }
  17353. lookupType = lookupType->mBaseType;
  17354. }
  17355. }
  17356. //TODO:
  17357. if ((checkBase != NULL)
  17358. && (false)
  17359. )
  17360. {
  17361. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  17362. for (int checkMethodIdx = (int) baseVirtualMethodTable.size() - 1; checkMethodIdx >= 0; checkMethodIdx--)
  17363. {
  17364. auto& baseMethodRef = baseVirtualMethodTable[checkMethodIdx];
  17365. if (baseMethodRef.mDeclaringMethod.mMethodNum == -1)
  17366. {
  17367. BF_ASSERT(mCompiler->mOptions.mHasVDataExtender);
  17368. continue;
  17369. }
  17370. BfMethodInstance* baseMethodInstance = baseVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  17371. if (baseMethodInstance == NULL)
  17372. {
  17373. AssertErrorState();
  17374. continue;
  17375. }
  17376. if ((baseMethodInstance != NULL) && (CompareMethodSignatures(baseMethodInstance, methodInstance)))
  17377. {
  17378. if (methodDef->mIsOverride)
  17379. {
  17380. BfMethodInstance* checkMethodInstance;
  17381. if (typeInstance->IsValueType())
  17382. checkMethodInstance = checkBase->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  17383. else
  17384. checkMethodInstance = typeInstance->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  17385. auto newDeclType = checkMethodInstance->mMethodDef->mDeclaringType;
  17386. if (!typeInstance->IsTypeMemberAccessible(newDeclType, methodDef->mDeclaringType->mProject))
  17387. continue;
  17388. if (bestOverrideMethodInstance != NULL)
  17389. {
  17390. auto prevDeclType = bestOverrideMethodInstance->mMethodDef->mDeclaringType;
  17391. bool isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  17392. bool isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  17393. if (isBetter == isWorse)
  17394. {
  17395. ambiguousOverrideMethodInstance = bestOverrideMethodInstance;
  17396. }
  17397. else
  17398. {
  17399. if (isWorse)
  17400. continue;
  17401. ambiguousOverrideMethodInstance = NULL;
  17402. }
  17403. }
  17404. bestOverrideMethodInstance = checkMethodInstance;
  17405. bestOverrideMethodIdx = checkMethodIdx;
  17406. }
  17407. else
  17408. {
  17409. if ((baseMethodInstance->GetOwner() != methodInstance->GetOwner()) && (!methodDef->mIsNew))
  17410. {
  17411. if (!hadHidingError)
  17412. Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use either 'override' or 'new'.", TypeToString(checkBase).c_str()), declaringNode);
  17413. hadHidingError = true;
  17414. }
  17415. }
  17416. }
  17417. }
  17418. }
  17419. if (bestOverrideMethodInstance != NULL)
  17420. {
  17421. if (ambiguousOverrideMethodInstance != NULL)
  17422. {
  17423. bool allow = false;
  17424. // 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.
  17425. // When when specialize, the specialized type will determine wither it has illegally pulled in both declarations or not
  17426. bool canSeeEachOther = false;
  17427. //
  17428. {
  17429. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, ambiguousOverrideMethodInstance);
  17430. if (bestOverrideMethodInstance->GetOwner()->IsTypeMemberIncluded(bestOverrideMethodInstance->mMethodDef->mDeclaringType, ambiguousOverrideMethodInstance->mMethodDef->mDeclaringType, this))
  17431. canSeeEachOther = true;
  17432. }
  17433. //
  17434. {
  17435. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, bestOverrideMethodInstance);
  17436. if (ambiguousOverrideMethodInstance->GetOwner()->IsTypeMemberIncluded(ambiguousOverrideMethodInstance->mMethodDef->mDeclaringType, bestOverrideMethodInstance->mMethodDef->mDeclaringType, this))
  17437. canSeeEachOther = true;
  17438. }
  17439. if (!canSeeEachOther)
  17440. {
  17441. BF_ASSERT(bestOverrideMethodInstance->GetOwner()->IsUnspecializedType() && ambiguousOverrideMethodInstance->GetOwner()->IsUnspecializedType());
  17442. }
  17443. else
  17444. {
  17445. auto error = Fail(StrFormat("Method '%s' is an ambiguous override", MethodToString(methodInstance).c_str()), methodDef->GetRefNode());
  17446. if (error != NULL)
  17447. {
  17448. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", MethodToString(bestOverrideMethodInstance).c_str()), bestOverrideMethodInstance->mMethodDef->GetRefNode());
  17449. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", MethodToString(ambiguousOverrideMethodInstance).c_str()), ambiguousOverrideMethodInstance->mMethodDef->GetRefNode());
  17450. }
  17451. }
  17452. }
  17453. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  17454. BfMethodInstance* baseVirtualMethodInstance = baseVirtualMethodTable[bestOverrideMethodIdx].mDeclaringMethod;
  17455. if ((baseVirtualMethodInstance != methodInstance) && (methodDef->mIsOverride))
  17456. {
  17457. if (baseVirtualMethodInstance->mReturnType != methodInstance->mReturnType)
  17458. {
  17459. BfTypeReference* returnTypeRef;
  17460. if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  17461. {
  17462. returnTypeRef = propertyDeclaration->mTypeRef;
  17463. Fail("Property differs from overridden property by type", returnTypeRef, true);
  17464. }
  17465. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  17466. {
  17467. returnTypeRef = methodDeclaration->mReturnType;
  17468. Fail("Method differs from overridden method by return value", returnTypeRef, true);
  17469. }
  17470. else
  17471. {
  17472. Fail(StrFormat("Internal error with method '%s'", MethodToString(methodInstance).c_str()));
  17473. }
  17474. return usedMethod;
  17475. }
  17476. }
  17477. if (methodDef->mIsOverride)
  17478. {
  17479. // We can have multiple matches when a virtual method is used to implement interface methods
  17480. // It doesn't matter what we set mVirtualTableIdx, as all base classes will override all matching
  17481. // vtable entries for this method signature
  17482. virtualMethodMatchIdx = bestOverrideMethodIdx;
  17483. if (!typeInstance->IsValueType())
  17484. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  17485. if (typeInstance->IsValueType())
  17486. {
  17487. methodOverriden = checkBase->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod;
  17488. }
  17489. else
  17490. {
  17491. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  17492. auto& overridenRef = typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod;
  17493. if (overridenRef.mKind != BfMethodRefKind_AmbiguousRef)
  17494. {
  17495. methodOverriden = overridenRef;
  17496. BfMethodInstance* setMethodInstance = methodInstance;
  17497. bool doOverride = true;
  17498. if (methodOverriden->GetOwner() == methodInstance->GetOwner())
  17499. {
  17500. bool isBetter = false;
  17501. bool isWorse = false;
  17502. CompareDeclTypes(methodInstance->mMethodDef->mDeclaringType, methodOverriden->mMethodDef->mDeclaringType, isBetter, isWorse);
  17503. if (isBetter == isWorse)
  17504. {
  17505. // We have to resolve later per-project
  17506. if ((ambiguityContext != NULL) && (ambiguityContext->mIsProjectSpecific))
  17507. {
  17508. auto declMethodInstance = checkBase->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod;
  17509. ambiguityContext->Add(virtualMethodMatchIdx, NULL, -1, methodOverriden, methodInstance);
  17510. }
  17511. if ((ambiguityContext == NULL) || (!ambiguityContext->mIsProjectSpecific))
  17512. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod.mKind = BfMethodRefKind_AmbiguousRef;
  17513. doOverride = false;
  17514. }
  17515. else
  17516. {
  17517. if ((isBetter) && (ambiguityContext != NULL))
  17518. {
  17519. ambiguityContext->Remove(virtualMethodMatchIdx);
  17520. }
  17521. doOverride = isBetter;
  17522. }
  17523. }
  17524. if (doOverride)
  17525. {
  17526. auto declMethodInstance = (BfMethodInstance*)typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod;
  17527. _AddVirtualDecl(declMethodInstance);
  17528. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod = setMethodInstance;
  17529. }
  17530. }
  17531. }
  17532. if (methodOverriden != NULL)
  17533. {
  17534. auto prevProtection = methodOverriden->mMethodDef->mProtection;
  17535. if ((methodDef->mProtection != prevProtection) && (methodDef->mMethodType != BfMethodType_Dtor))
  17536. {
  17537. const char* protectionNames[] = {"hidden", "private", "protected", "public"};
  17538. BfAstNode* protectionRefNode = NULL;
  17539. if (auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration())
  17540. {
  17541. protectionRefNode = propertyMethodDeclaration->mProtectionSpecifier;
  17542. if (protectionRefNode == NULL)
  17543. protectionRefNode = propertyMethodDeclaration->mPropertyDeclaration->mProtectionSpecifier;
  17544. if (protectionRefNode == NULL)
  17545. protectionRefNode = propertyMethodDeclaration->mPropertyDeclaration->mNameNode;
  17546. }
  17547. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  17548. {
  17549. protectionRefNode = methodDeclaration->mProtectionSpecifier;
  17550. if (protectionRefNode == NULL)
  17551. protectionRefNode = methodDeclaration->mNameNode;
  17552. }
  17553. if (protectionRefNode != NULL)
  17554. Fail(StrFormat("Cannot change access modifiers when overriding '%s' inherited member", protectionNames[(int)prevProtection]), protectionRefNode, true);
  17555. }
  17556. }
  17557. }
  17558. }
  17559. if ((virtualMethodMatchIdx == -1) && ((ambiguityContext == NULL) || (!ambiguityContext->mIsReslotting)))
  17560. {
  17561. if (methodDef->mIsOverride)
  17562. {
  17563. BfTokenNode* overrideToken = NULL;
  17564. if (auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration())
  17565. overrideToken = propertyMethodDeclaration->mPropertyDeclaration->mVirtualSpecifier;
  17566. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  17567. overrideToken = methodDeclaration->mVirtualSpecifier;
  17568. if (overrideToken != NULL)
  17569. {
  17570. if ((propertyDeclaration != NULL) && (propertyDeclaration->mNameNode != NULL) &&
  17571. ((methodDef->mMethodType == BfMethodType_PropertyGetter) || (methodDef->mMethodType == BfMethodType_PropertySetter)))
  17572. Fail(StrFormat("No suitable method found to override for '%s.%s'",
  17573. propertyDeclaration->mNameNode->ToString().c_str(), (methodDef->mMethodType == BfMethodType_PropertyGetter) ? "get" : "set"), overrideToken, true);
  17574. else
  17575. Fail("No suitable method found to override", overrideToken, true);
  17576. }
  17577. return usedMethod;
  17578. }
  17579. UniqueSlotVirtualMethod(methodInstance);
  17580. }
  17581. else
  17582. usedMethod = true;
  17583. if (typeInstance->IsValueType())
  17584. return usedMethod;
  17585. }
  17586. bool foundInterface = false;
  17587. bool hadAnyMatch = false;
  17588. // See if this method matches interfaces
  17589. for (auto& ifaceTypeInst : typeInstance->mInterfaces)
  17590. {
  17591. auto ifaceInst = ifaceTypeInst.mInterfaceType;
  17592. if (ifaceInst->IsIncomplete())
  17593. PopulateType(ifaceInst, BfPopulateType_DataAndMethods);
  17594. int startIdx = ifaceTypeInst.mStartInterfaceTableIdx;
  17595. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  17596. // See "bidirectional" rules mentioned in DoTypeInstanceMethodProcessing
  17597. if ((!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, ifaceTypeInst.mDeclaringType)) &&
  17598. (!typeInstance->IsTypeMemberAccessible(ifaceTypeInst.mDeclaringType, methodDef->mDeclaringType)))
  17599. continue;
  17600. if (!typeInstance->IsTypeMemberIncluded(methodDef->mDeclaringType, ifaceTypeInst.mDeclaringType, this))
  17601. continue;
  17602. bool hadMatch = false;
  17603. bool hadNameMatch = false;
  17604. BfType* expectedReturnType = NULL;
  17605. bool showedError = false;
  17606. // We go through our VTable looking for NULL entries within the interface sections
  17607. // The only instance of finding a "better" method is when we have explicitly interface-dotted method
  17608. // because a normal method declared in this type could have matched earlier
  17609. //for (int iMethodIdx = 0; iMethodIdx < iMethodCount; iMethodIdx++)
  17610. ifaceInst->mTypeDef->PopulateMemberSets();
  17611. BfMethodDef* checkMethodDef = NULL;
  17612. BfMemberSetEntry* entry;
  17613. if (ifaceInst->mTypeDef->mMethodSet.TryGetWith(methodInstance->mMethodDef->mName, &entry))
  17614. checkMethodDef = (BfMethodDef*)entry->mMemberDef;
  17615. while (checkMethodDef != NULL)
  17616. {
  17617. int iMethodIdx = checkMethodDef->mIdx;
  17618. int iTableIdx = iMethodIdx + startIdx;
  17619. BfTypeInterfaceMethodEntry* interfaceMethodEntry = &typeInstance->mInterfaceMethodTable[iTableIdx];
  17620. auto iMethodPtr = &interfaceMethodEntry->mMethodRef;
  17621. bool storeIFaceMethod = false;
  17622. if ((mCompiler->mPassInstance->HasFailed()) && (iMethodIdx >= (int)ifaceInst->mMethodInstanceGroups.size()))
  17623. continue;
  17624. auto& iMethodGroup = ifaceInst->mMethodInstanceGroups[iMethodIdx];
  17625. auto iMethodInst = iMethodGroup.mDefault;
  17626. if (iMethodInst == NULL)
  17627. {
  17628. if ((!ifaceInst->IsGenericTypeInstance()) || (!ifaceInst->mTypeDef->mIsCombinedPartial))
  17629. AssertErrorState();
  17630. continue;
  17631. }
  17632. if (iMethodInst->mMethodDef->mName == methodInstance->mMethodDef->mName)
  17633. hadNameMatch = true;
  17634. bool doesMethodSignatureMatch = CompareMethodSignatures(iMethodInst, methodInstance);
  17635. if ((!doesMethodSignatureMatch) && (iMethodInst->GetNumGenericParams() == 0) && (interfaceMethodEntry->mMethodRef.IsNull()))
  17636. {
  17637. doesMethodSignatureMatch = IsCompatibleInterfaceMethod(iMethodInst, methodInstance);
  17638. }
  17639. if ((doesMethodSignatureMatch) && (methodInstance->GetOwner()->IsValueType()))
  17640. {
  17641. if ((!iMethodInst->mMethodDef->mIsMutating) && (methodInstance->mMethodDef->mIsMutating))
  17642. {
  17643. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface == ifaceInst))
  17644. {
  17645. auto error = mCompiler->mPassInstance->Fail(StrFormat("Implementation method '%s' cannot specify 'mut' because the interface method does not allow it",
  17646. MethodToString(methodInstance).c_str()), methodInstance->mMethodDef->GetMutNode());
  17647. if (error != NULL)
  17648. mCompiler->mPassInstance->MoreInfo(StrFormat("Declare the interface method as 'mut' to allow matching 'mut' implementations"), iMethodInst->mMethodDef->mMethodDeclaration);
  17649. showedError = true;
  17650. }
  17651. }
  17652. }
  17653. if (doesMethodSignatureMatch)
  17654. {
  17655. usedMethod = true;
  17656. hadMatch = true;
  17657. hadAnyMatch = true;
  17658. storeIFaceMethod = true;
  17659. if ((iMethodPtr->mKind != BfMethodRefKind_AmbiguousRef) && (iMethodPtr->mTypeInstance != NULL))
  17660. {
  17661. auto prevMethod = (BfMethodInstance*)*iMethodPtr;
  17662. if ((mCompiler->mIsResolveOnly) && (prevMethod == methodInstance))
  17663. {
  17664. // When autocompletion regenerates a single method body but not the whole type then
  17665. // we will see ourselves in the vtable already
  17666. return usedMethod;
  17667. }
  17668. bool isBetter = false;
  17669. bool isWorse = false;
  17670. isBetter = (methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL);
  17671. isWorse = (prevMethod->mMethodInfoEx != NULL) && (prevMethod->mMethodInfoEx->mExplicitInterface != NULL);
  17672. if (isBetter == isWorse)
  17673. CompareDeclTypes(methodInstance->mMethodDef->mDeclaringType, prevMethod->mMethodDef->mDeclaringType, isBetter, isWorse);
  17674. if (isBetter == isWorse)
  17675. {
  17676. if (ambiguityContext != NULL)
  17677. {
  17678. ambiguityContext->Add(~iTableIdx, &ifaceTypeInst, iMethodIdx, prevMethod, methodInstance);
  17679. }
  17680. iMethodPtr->mKind = BfMethodRefKind_AmbiguousRef;
  17681. storeIFaceMethod = true;
  17682. }
  17683. else
  17684. {
  17685. if ((isBetter) && (ambiguityContext != NULL))
  17686. ambiguityContext->Remove(~iTableIdx);
  17687. storeIFaceMethod = isBetter;
  17688. }
  17689. }
  17690. }
  17691. if (storeIFaceMethod)
  17692. {
  17693. _AddVirtualDecl(iMethodInst);
  17694. *iMethodPtr = methodInstance;
  17695. }
  17696. checkMethodDef = checkMethodDef->mNextWithSameName;
  17697. }
  17698. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface == ifaceInst) && (!hadMatch) && (!showedError))
  17699. {
  17700. if (expectedReturnType != NULL)
  17701. Fail(StrFormat("Wrong return type, expected '%s'", TypeToString(expectedReturnType).c_str()), declaringNode, true);
  17702. else if (hadNameMatch)
  17703. Fail("Method parameters don't match interface method", declaringNode, true);
  17704. else
  17705. Fail("Method name not found in interface", methodDef->GetRefNode(), true);
  17706. }
  17707. }
  17708. // Any overriden virtual methods that were used in interfaces also need to be replaced
  17709. if (methodOverriden != NULL)
  17710. {
  17711. for (auto& methodEntry : typeInstance->mInterfaceMethodTable)
  17712. {
  17713. if (methodEntry.mMethodRef == methodOverriden)
  17714. methodEntry.mMethodRef = methodInstance;
  17715. }
  17716. }
  17717. return usedMethod;
  17718. }
  17719. bool BfModule::SlotInterfaceMethod(BfMethodInstance* methodInstance)
  17720. {
  17721. auto typeInstance = mCurTypeInstance;
  17722. auto methodDef = methodInstance->mMethodDef;
  17723. if (methodDef->mMethodType == BfMethodType_Ctor)
  17724. return true;
  17725. bool foundOverride = false;
  17726. if ((methodDef->mBody == NULL) && (methodDef->mProtection == BfProtection_Private))
  17727. {
  17728. Fail("Private interface methods must provide a body", methodDef->GetMethodDeclaration()->mProtectionSpecifier);
  17729. }
  17730. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL) && (!methodDef->mIsOverride))
  17731. {
  17732. Fail("Explicit interfaces can only be specified for overrides in interface declarations", methodDef->GetMethodDeclaration()->mExplicitInterface);
  17733. }
  17734. BfAstNode* declaringNode = methodDef->GetRefNode();
  17735. for (auto& ifaceTypeInst : typeInstance->mInterfaces)
  17736. {
  17737. auto ifaceInst = ifaceTypeInst.mInterfaceType;
  17738. int startIdx = ifaceTypeInst.mStartInterfaceTableIdx;
  17739. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  17740. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != ifaceInst))
  17741. continue;
  17742. ifaceInst->mTypeDef->PopulateMemberSets();
  17743. BfMethodDef* nextMethod = NULL;
  17744. BfMemberSetEntry* entry = NULL;
  17745. if (ifaceInst->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  17746. nextMethod = (BfMethodDef*)entry->mMemberDef;
  17747. while (nextMethod != NULL)
  17748. {
  17749. auto checkMethod = nextMethod;
  17750. nextMethod = nextMethod->mNextWithSameName;
  17751. auto ifaceMethod = ifaceInst->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  17752. if (ifaceMethod == NULL)
  17753. continue;
  17754. if (CompareMethodSignatures(ifaceMethod, methodInstance))
  17755. {
  17756. if (methodDef->mIsOverride)
  17757. {
  17758. if (ifaceMethod->mMethodDef->mProtection == BfProtection_Private)
  17759. {
  17760. auto error = Fail(StrFormat("Interface method '%s' cannot override private interface method '%s'", MethodToString(methodInstance).c_str(), MethodToString(ifaceMethod).c_str()), declaringNode);
  17761. if (error != NULL)
  17762. {
  17763. mCompiler->mPassInstance->MoreInfo("See base interface method", ifaceMethod->mMethodDef->GetRefNode());
  17764. }
  17765. }
  17766. foundOverride = true;
  17767. }
  17768. else if (!methodDef->mIsNew)
  17769. {
  17770. Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use the 'new' keyword if hiding was intentional.", TypeToString(ifaceInst).c_str()), declaringNode);
  17771. }
  17772. }
  17773. }
  17774. }
  17775. if ((methodDef->mIsOverride) && (!foundOverride))
  17776. {
  17777. // This allows us to declare a method in the base definition or in an extension and then provide
  17778. // an implementation in a more-specific extension
  17779. typeInstance->mTypeDef->PopulateMemberSets();
  17780. BfMethodDef* nextMethod = NULL;
  17781. BfMemberSetEntry* entry = NULL;
  17782. if (typeInstance->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  17783. nextMethod = (BfMethodDef*)entry->mMemberDef;
  17784. while (nextMethod != NULL)
  17785. {
  17786. auto checkMethod = nextMethod;
  17787. nextMethod = nextMethod->mNextWithSameName;
  17788. auto ifaceMethod = typeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  17789. if (ifaceMethod == NULL)
  17790. continue;
  17791. if (ifaceMethod->mMethodDef->mDeclaringType == methodInstance->mMethodDef->mDeclaringType)
  17792. continue;
  17793. if (CompareMethodSignatures(ifaceMethod, methodInstance))
  17794. {
  17795. foundOverride = true;
  17796. }
  17797. }
  17798. // for (int methodIdx = 0; methodIdx < typeInstance->mMethodInstanceGroups.size(); methodIdx++)
  17799. // {
  17800. // auto ifaceMethod = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  17801. // if (ifaceMethod == NULL)
  17802. // continue;
  17803. // if (ifaceMethod->mMethodDef->mDeclaringType == methodInstance->mMethodDef->mDeclaringType)
  17804. // continue;
  17805. //
  17806. // if (CompareMethodSignatures(ifaceMethod, methodInstance))
  17807. // {
  17808. // foundOverride = true;
  17809. // }
  17810. // }
  17811. }
  17812. if (methodDef->mIsOverride)
  17813. {
  17814. if (!foundOverride)
  17815. {
  17816. BfTokenNode* overrideToken = NULL;
  17817. if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  17818. overrideToken = propertyDeclaration->mVirtualSpecifier;
  17819. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  17820. overrideToken = methodDeclaration->mVirtualSpecifier;
  17821. if (overrideToken != NULL)
  17822. {
  17823. Fail("No suitable method found to override", overrideToken, true);
  17824. }
  17825. else
  17826. {
  17827. // Possible cause - DTOR with params
  17828. AssertErrorState();
  17829. }
  17830. }
  17831. return true;
  17832. }
  17833. // Generic methods can't be called virtually
  17834. if (methodInstance->GetNumGenericParams() != 0)
  17835. return true;
  17836. // Only public methods can be called virtually
  17837. if (methodDef->mProtection != BfProtection_Public)
  17838. return true;
  17839. UniqueSlotVirtualMethod(methodInstance);
  17840. return true;
  17841. }
  17842. void BfModule::DbgFinish()
  17843. {
  17844. if ((mBfIRBuilder == NULL) || (mExtensionCount != 0))
  17845. return;
  17846. if (mAwaitingInitFinish)
  17847. FinishInit();
  17848. if (mHasForceLinkMarker)
  17849. return;
  17850. String markerName;
  17851. BfIRValue linkMarker;
  17852. if (mBfIRBuilder->DbgHasInfo())
  17853. {
  17854. bool needForceLinking = false;
  17855. for (auto& ownedType : mOwnedTypeInstances)
  17856. {
  17857. bool hasConfirmedReference = false;
  17858. for (auto& methodInstGroup : ownedType->mMethodInstanceGroups)
  17859. {
  17860. if ((methodInstGroup.IsImplemented()) && (methodInstGroup.mDefault != NULL) &&
  17861. (!methodInstGroup.mDefault->mMethodDef->mIsStatic) && (methodInstGroup.mDefault->mIsReified) &&
  17862. ((methodInstGroup.mOnDemandKind == BfMethodOnDemandKind_AlwaysInclude) || (methodInstGroup.mOnDemandKind == BfMethodOnDemandKind_Referenced)))
  17863. {
  17864. hasConfirmedReference = true;
  17865. }
  17866. }
  17867. if ((!hasConfirmedReference) || (ownedType->IsBoxed()))
  17868. needForceLinking = true;
  17869. }
  17870. if ((needForceLinking) && (mProject->mCodeGenOptions.mAsmKind == BfAsmKind_None))
  17871. {
  17872. BfMethodState methodState;
  17873. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  17874. methodState.mTempKind = BfMethodState::TempKind_Static;
  17875. mHasForceLinkMarker = true;
  17876. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  17877. SizedArray<BfIRType, 0> paramTypes;
  17878. BfIRFunctionType funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  17879. String linkName = "FORCELINKMOD_" + mModuleName;
  17880. BfIRFunction func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, linkName);
  17881. mBfIRBuilder->SetActiveFunction(func);
  17882. auto entryBlock = mBfIRBuilder->CreateBlock("main", true);
  17883. mBfIRBuilder->SetInsertPoint(entryBlock);
  17884. auto firstType = mOwnedTypeInstances[0];
  17885. UpdateSrcPos(mContext->mBfObjectType->mTypeDef->GetRefNode());
  17886. SizedArray<BfIRMDNode, 1> diParamTypes;
  17887. diParamTypes.Add(mBfIRBuilder->DbgGetType(GetPrimitiveType(BfTypeCode_None)));
  17888. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParamTypes);
  17889. auto diScope = mBfIRBuilder->DbgCreateFunction(mDICompileUnit, "FORCELINKMOD", linkName, mCurFilePosition.mFileInstance->mDIFile,
  17890. mCurFilePosition.mCurLine + 1, diFuncType, false, true, mCurFilePosition.mCurLine + 1, 0, false, func);
  17891. methodState.mCurScope->mDIScope = diScope;
  17892. UpdateSrcPos(mContext->mBfObjectType->mTypeDef->GetRefNode(), BfSrcPosFlag_Force);
  17893. SizedArray<BfIRValue, 8> args;
  17894. BfExprEvaluator exprEvaluator(this);
  17895. for (auto& ownedType : mOwnedTypeInstances)
  17896. {
  17897. auto alloca = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int8)));
  17898. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(diScope, "variable", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(ownedType));
  17899. mBfIRBuilder->DbgInsertDeclare(alloca, diVariable);
  17900. }
  17901. mBfIRBuilder->CreateRetVoid();
  17902. mBfIRBuilder->SetActiveFunction(BfIRFunction());
  17903. }
  17904. }
  17905. }
  17906. bool BfModule::Finish()
  17907. {
  17908. BP_ZONE("BfModule::Finish");
  17909. BfLogSysM("BfModule finish: %p\n", this);
  17910. if (mHadBuildError)
  17911. {
  17912. // Don't AssertErrorState here, this current pass may not have failed but
  17913. // the module was still queued in mFinishedModuleWorkList
  17914. ClearModule();
  17915. return true;
  17916. }
  17917. if (mUsedSlotCount != -1)
  17918. {
  17919. BF_ASSERT(mCompiler->mMaxInterfaceSlots != -1);
  17920. mUsedSlotCount = mCompiler->mMaxInterfaceSlots;
  17921. }
  17922. BF_ASSERT(mAddedToCount);
  17923. mAddedToCount = false;
  17924. mAwaitingFinish = false;
  17925. mCompiler->mStats.mModulesFinished++;
  17926. if (HasCompiledOutput())
  17927. {
  17928. DbgFinish();
  17929. if (mAwaitingInitFinish)
  17930. FinishInit();
  17931. for (auto ownedTypeInst : mOwnedTypeInstances)
  17932. {
  17933. // Generate dbg info and add global variables if we haven't already
  17934. mBfIRBuilder->PopulateType(ownedTypeInst);
  17935. }
  17936. if (mBfIRBuilder->DbgHasInfo())
  17937. {
  17938. mBfIRBuilder->DbgFinalize();
  17939. }
  17940. String objOutputPath;
  17941. String irOutputPath;
  17942. mIsModuleMutable = false;
  17943. //mOutFileNames.Clear();
  17944. BF_ASSERT((int)mOutFileNames.size() >= mExtensionCount);
  17945. bool writeModule = mBfIRBuilder->HasExports();
  17946. String outputPath;
  17947. BfCodeGenOptions codeGenOptions = mProject->mCodeGenOptions;
  17948. auto& compilerOpts = mCompiler->mOptions;
  17949. codeGenOptions.mSIMDSetting = compilerOpts.mSIMDSetting;
  17950. auto moduleOptions = GetModuleOptions();
  17951. codeGenOptions.mOptLevel = moduleOptions.mOptLevel;
  17952. codeGenOptions.mSIMDSetting = moduleOptions.mSIMDSetting;
  17953. codeGenOptions.mWriteLLVMIR = mCompiler->mOptions.mWriteIR;
  17954. codeGenOptions.mWriteObj = mCompiler->mOptions.mGenerateObj;
  17955. codeGenOptions.mWriteBitcode = mCompiler->mOptions.mGenerateBitcode;
  17956. codeGenOptions.mVirtualMethodOfs = 1 + mCompiler->GetDynCastVDataCount() + mCompiler->mMaxInterfaceSlots;
  17957. codeGenOptions.mDynSlotOfs = mSystem->mPtrSize - mCompiler->GetDynCastVDataCount() * 4;
  17958. mCompiler->mStats.mIRBytes += mBfIRBuilder->mStream.GetSize();
  17959. mCompiler->mStats.mConstBytes += mBfIRBuilder->mTempAlloc.GetAllocSize();
  17960. bool allowWriteToLib = true;
  17961. if ((allowWriteToLib) && (codeGenOptions.mOptLevel == BfOptLevel_OgPlus) && (mModuleName != "vdata"))
  17962. {
  17963. codeGenOptions.mWriteToLib = true;
  17964. mWroteToLib = true;
  17965. }
  17966. else
  17967. {
  17968. mWroteToLib = false;
  17969. }
  17970. for (int fileIdx = 0; fileIdx <= mExtensionCount; fileIdx++)
  17971. {
  17972. outputPath = mModuleName;
  17973. outputPath = mCompiler->mOutputDirectory + "/" + mProject->mName + "/" + outputPath;
  17974. BfModuleFileName moduleFileName;
  17975. if (mParentModule != NULL)
  17976. {
  17977. for (auto&& checkPair : mParentModule->mSpecializedMethodModules)
  17978. {
  17979. if (checkPair.mValue == this)
  17980. moduleFileName.mProjects = checkPair.mKey;
  17981. }
  17982. }
  17983. moduleFileName.mProjects.Add(mProject);
  17984. if (fileIdx > 0)
  17985. outputPath += StrFormat("@%d", fileIdx + 1);
  17986. if (mCompiler->mOptions.mWriteIR)
  17987. irOutputPath = outputPath + ".ll";
  17988. if (mCompiler->mOptions.mGenerateObj)
  17989. {
  17990. objOutputPath = outputPath + BF_OBJ_EXT;
  17991. moduleFileName.mFileName = objOutputPath;
  17992. }
  17993. else if (mCompiler->mOptions.mWriteIR)
  17994. {
  17995. moduleFileName.mFileName = irOutputPath;
  17996. }
  17997. else if ((!mCompiler->mOptions.mGenerateObj) && (!mCompiler->mOptions.mGenerateBitcode) && (!mCompiler->mOptions.mWriteIR))
  17998. {
  17999. BF_FATAL("Neither obj nor IR specified");
  18000. }
  18001. moduleFileName.mModuleWritten = writeModule;
  18002. moduleFileName.mWroteToLib = mWroteToLib;
  18003. if (!mOutFileNames.Contains(moduleFileName))
  18004. mOutFileNames.Add(moduleFileName);
  18005. }
  18006. if (mCompiler->IsHotCompile())
  18007. {
  18008. codeGenOptions.mIsHotCompile = true;
  18009. //TODO: Why did we have this 'mWroteToLib' check? 'vdata' didn't get this flag set, which
  18010. // is required for rebuilding vdata after we hot create a vdata
  18011. //if (mWroteToLib)
  18012. {
  18013. if (mParentModule != NULL)
  18014. mParentModule->mHadHotObjectWrites = true;
  18015. mHadHotObjectWrites = true;
  18016. }
  18017. }
  18018. //TODO: Testing VDATA
  18019. /*if (mModuleName == "vdata")
  18020. {
  18021. codeGenOptions.mOptLevel = 4;
  18022. }*/
  18023. codeGenOptions.GenerateHash();
  18024. BP_ZONE("BfModule::Finish.WriteObjectFile");
  18025. if ((writeModule) && (!mBfIRBuilder->mIgnoreWrites))
  18026. mCompiler->mCodeGen.WriteObjectFile(this, outputPath, codeGenOptions);
  18027. mLastModuleWrittenRevision = mCompiler->mRevision;
  18028. }
  18029. else
  18030. {
  18031. for (auto type : mOwnedTypeInstances)
  18032. {
  18033. BF_ASSERT(!type->IsIncomplete());
  18034. }
  18035. }
  18036. for (auto& specModulePair : mSpecializedMethodModules)
  18037. {
  18038. auto specModule = specModulePair.mValue;
  18039. if ((specModule->mIsModuleMutable) && (!specModule->mAwaitingFinish))
  18040. {
  18041. BfLogSysM(" Mutable spec module remaining: %p\n", specModule);
  18042. }
  18043. }
  18044. CleanupFileInstances();
  18045. // We can't ClearModuleData here because we need the mSpecializedMethodModules to remain valid until we Finish them too
  18046. return true;
  18047. }
  18048. void BfModule::ReportMemory(MemReporter* memReporter)
  18049. {
  18050. memReporter->Add(sizeof(BfModule));
  18051. if (mBfIRBuilder != NULL)
  18052. {
  18053. memReporter->BeginSection("IRBuilder_ConstData");
  18054. memReporter->Add("Used", mBfIRBuilder->mTempAlloc.GetAllocSize());
  18055. memReporter->Add("Unused", mBfIRBuilder->mTempAlloc.GetTotalAllocSize() - mBfIRBuilder->mTempAlloc.GetAllocSize());
  18056. memReporter->EndSection();
  18057. memReporter->BeginSection("IRBuilder_BFIR");
  18058. memReporter->Add("Used", (int)(mBfIRBuilder->mStream.GetSize()));
  18059. memReporter->Add("Unused", (int)(mBfIRBuilder->mStream.mPools.size() * ChunkedDataBuffer::ALLOC_SIZE) - mBfIRBuilder->mStream.GetSize());
  18060. memReporter->EndSection();
  18061. memReporter->Add(sizeof(BfIRBuilder));
  18062. }
  18063. memReporter->BeginSection("FileInstanceMap");
  18064. memReporter->AddMap(mFileInstanceMap);
  18065. memReporter->AddMap(mNamedFileInstanceMap);
  18066. memReporter->Add((int)mNamedFileInstanceMap.size() * sizeof(BfFileInstance));
  18067. memReporter->EndSection();
  18068. memReporter->AddVec(mOwnedTypeInstances, false);
  18069. memReporter->AddVec(mSpecializedMethodModules, false);
  18070. memReporter->AddVec(mOutFileNames, false);
  18071. memReporter->AddMap("FuncReferences", mFuncReferences, false);
  18072. memReporter->AddMap(mInterfaceSlotRefs, false);
  18073. memReporter->AddMap(mStaticFieldRefs, false);
  18074. memReporter->AddMap(mClassVDataRefs, false);
  18075. memReporter->AddMap("VDataExtMap", mClassVDataExtRefs, false);
  18076. memReporter->AddMap(mTypeDataRefs, false);
  18077. memReporter->AddMap(mDbgRawAllocDataRefs, false);
  18078. memReporter->AddMap(mDeferredMethodCallData, false);
  18079. memReporter->AddHashSet(mDeferredMethodIds, false);
  18080. memReporter->AddHashSet("ModuleRefs", mModuleRefs, false);
  18081. }
  18082. // ClearModuleData is called immediately after the module is compiled, so don't clear out any data that needs to
  18083. // be transient through the next compile
  18084. void BfModule::ClearModuleData()
  18085. {
  18086. BfLogSysM("ClearModuleData %p\n", this);
  18087. if (mAddedToCount)
  18088. {
  18089. mCompiler->mStats.mModulesFinished++;
  18090. mAddedToCount = false;
  18091. }
  18092. mDICompileUnit = BfIRMDNode();
  18093. mIsModuleMutable = false;
  18094. mIncompleteMethodCount = 0;
  18095. mHasGenericMethods = false;
  18096. // We don't want to clear these because we want it to persist through module extensions-
  18097. // otherwise we may think an extension succeeds even though the base module failed
  18098. //mHadBuildError = false;
  18099. //mHadBuildWarning = false;
  18100. mClassVDataRefs.Clear();
  18101. mClassVDataExtRefs.Clear();
  18102. for (auto& kv : mTypeDataRefs)
  18103. kv.mValue = BfIRValue();
  18104. mStringCharPtrPool.Clear();
  18105. mStringObjectPool.Clear();
  18106. mStaticFieldRefs.Clear();
  18107. BF_ASSERT(!mIgnoreErrors);
  18108. for (auto prevIRBuilder : mPrevIRBuilders)
  18109. delete prevIRBuilder;
  18110. mPrevIRBuilders.Clear();
  18111. for (auto& specPair : mSpecializedMethodModules)
  18112. {
  18113. auto specModule = specPair.mValue;
  18114. specModule->ClearModuleData();
  18115. }
  18116. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  18117. mBuiltInFuncs[i] = BfIRFunction();
  18118. if (mNextAltModule != NULL)
  18119. mNextAltModule->ClearModuleData();
  18120. BfLogSysM("ClearModuleData. Deleting IRBuilder: %p\n", mBfIRBuilder);
  18121. delete mBfIRBuilder;
  18122. mBfIRBuilder = NULL;
  18123. mWantsIRIgnoreWrites = false;
  18124. }
  18125. void BfModule::DisownMethods()
  18126. {
  18127. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  18128. mBuiltInFuncs[i] = BfIRFunction();
  18129. BfModule* methodModule = this;
  18130. if (mParentModule != NULL)
  18131. methodModule = mParentModule;
  18132. for (auto typeInst : methodModule->mOwnedTypeInstances)
  18133. {
  18134. for (auto& methodGroup : typeInst->mMethodInstanceGroups)
  18135. {
  18136. if (methodGroup.mDefault != NULL)
  18137. {
  18138. if (methodGroup.mDefault->mIRFunction)
  18139. {
  18140. BF_ASSERT(methodGroup.mDefault->mDeclModule != NULL);
  18141. if (methodGroup.mDefault->mDeclModule == this)
  18142. {
  18143. methodGroup.mDefault->mIRFunction = BfIRFunction();
  18144. }
  18145. }
  18146. }
  18147. if (methodGroup.mMethodSpecializationMap != NULL)
  18148. {
  18149. for (auto& mapPair : *methodGroup.mMethodSpecializationMap)
  18150. {
  18151. auto methodInstance = mapPair.mValue;
  18152. if (methodInstance->mDeclModule == this)
  18153. {
  18154. methodInstance->mIRFunction = BfIRFunction();
  18155. }
  18156. }
  18157. }
  18158. }
  18159. }
  18160. }
  18161. void BfModule::ClearModule()
  18162. {
  18163. ClearModuleData();
  18164. DisownMethods();
  18165. for (auto& specPair : mSpecializedMethodModules)
  18166. {
  18167. auto specModule = specPair.mValue;
  18168. specModule->ClearModule();
  18169. }
  18170. if (mNextAltModule != NULL)
  18171. mNextAltModule->ClearModule();
  18172. }