BfModule.cpp 707 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980
  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, type->mAlign);
  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, arrayType->mAlign);
  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. if (resultStr.IsEmpty())
  7968. return "<nothing>";
  7969. return resultStr;
  7970. }
  7971. void BfModule::CurrentAddToConstHolder(BfIRValue& irVal)
  7972. {
  7973. auto constant = mBfIRBuilder->GetConstant(irVal);
  7974. int stringPoolIdx = GetStringPoolIdx(irVal, mBfIRBuilder);
  7975. if (stringPoolIdx != -1)
  7976. {
  7977. irVal = mCurTypeInstance->GetOrCreateConstHolder()->CreateConst(BfTypeCode_Int32, stringPoolIdx);
  7978. return;
  7979. }
  7980. if (constant->mConstType == BfConstType_Array)
  7981. {
  7982. auto constArray = (BfConstantArray*)constant;
  7983. SizedArray<BfIRValue, 8> newVals;
  7984. for (auto val : constArray->mValues)
  7985. {
  7986. auto newVal = val;
  7987. CurrentAddToConstHolder(newVal);
  7988. newVals.push_back(newVal);
  7989. }
  7990. irVal = mCurTypeInstance->mConstHolder->CreateConstArray(constArray->mType, newVals);
  7991. return;
  7992. }
  7993. auto origConst = irVal;
  7994. if ((constant->mConstType == BfConstType_BitCast) || (constant->mConstType == BfConstType_BitCastNull))
  7995. {
  7996. auto bitcast = (BfConstantBitCast*)constant;
  7997. constant = mBfIRBuilder->GetConstantById(bitcast->mTarget);
  7998. }
  7999. irVal = mCurTypeInstance->CreateConst(constant, mBfIRBuilder);
  8000. }
  8001. void BfModule::ClearConstData()
  8002. {
  8003. mBfIRBuilder->ClearConstData();
  8004. mStringObjectPool.Clear();
  8005. mStringCharPtrPool.Clear();
  8006. mStringPoolRefs.Clear();
  8007. }
  8008. BfTypedValue BfModule::GetTypedValueFromConstant(BfConstant* constant, BfIRConstHolder* constHolder, BfType* wantType)
  8009. {
  8010. bool isString = false;
  8011. isString = (wantType->IsObject()) && (wantType->ToTypeInstance()->mTypeDef == mCompiler->mStringTypeDef);
  8012. if (wantType->IsPointer())
  8013. isString = true;
  8014. if (!isString)
  8015. {
  8016. switch (constant->mTypeCode)
  8017. {
  8018. case BfTypeCode_Boolean:
  8019. case BfTypeCode_Int8:
  8020. case BfTypeCode_UInt8:
  8021. case BfTypeCode_Int16:
  8022. case BfTypeCode_UInt16:
  8023. case BfTypeCode_Int32:
  8024. case BfTypeCode_UInt32:
  8025. case BfTypeCode_Int64:
  8026. case BfTypeCode_UInt64:
  8027. case BfTypeCode_IntPtr:
  8028. case BfTypeCode_UIntPtr:
  8029. case BfTypeCode_IntUnknown:
  8030. case BfTypeCode_UIntUnknown:
  8031. case BfTypeCode_Char8:
  8032. case BfTypeCode_Char16:
  8033. case BfTypeCode_Char32:
  8034. case BfTypeCode_Single:
  8035. case BfTypeCode_Double:
  8036. {
  8037. auto constVal = mBfIRBuilder->CreateConst(constant, constHolder);
  8038. auto typedValue = BfTypedValue(constVal, GetPrimitiveType(constant->mTypeCode));
  8039. if (typedValue.mType == wantType)
  8040. return typedValue;
  8041. if (wantType->IsTypedPrimitive())
  8042. {
  8043. if (typedValue.mType == wantType->GetUnderlyingType())
  8044. {
  8045. typedValue.mType = wantType;
  8046. return typedValue;
  8047. }
  8048. }
  8049. auto castedTypedValue = Cast(NULL, typedValue, wantType, (BfCastFlags)(BfCastFlags_SilentFail | BfCastFlags_Explicit));
  8050. BF_ASSERT(castedTypedValue);
  8051. return castedTypedValue;
  8052. }
  8053. break;
  8054. default: break;
  8055. }
  8056. }
  8057. BfIRValue irValue = ConstantToCurrent(constant, constHolder, wantType);
  8058. BF_ASSERT(irValue);
  8059. if (!irValue)
  8060. return BfTypedValue();
  8061. return BfTypedValue(irValue, wantType, false);
  8062. }
  8063. BfIRValue BfModule::ConstantToCurrent(BfConstant* constant, BfIRConstHolder* constHolder, BfType* wantType)
  8064. {
  8065. if (constant->mTypeCode == BfTypeCode_NullPtr)
  8066. {
  8067. return GetDefaultValue(wantType);
  8068. }
  8069. bool isString = false;
  8070. isString = (wantType->IsObject()) && (wantType->ToTypeInstance()->mTypeDef == mCompiler->mStringTypeDef);
  8071. if (((wantType->IsPointer()) || (isString)) && (mBfIRBuilder->IsInt(constant->mTypeCode)))
  8072. {
  8073. const StringImpl& str = mContext->mStringObjectIdMap[constant->mInt32].mString;
  8074. BfIRValue stringObjConst = GetStringObjectValue(str);
  8075. if (wantType->IsObject())
  8076. return stringObjConst;
  8077. return GetStringCharPtr(stringObjConst);
  8078. }
  8079. if (constant->mConstType == BfConstType_Array)
  8080. {
  8081. auto elementType = wantType->GetUnderlyingType();
  8082. auto constArray = (BfConstantArray*)constant;
  8083. SizedArray<BfIRValue, 8> newVals;
  8084. for (auto val : constArray->mValues)
  8085. {
  8086. newVals.push_back(ConstantToCurrent(constHolder->GetConstant(val), constHolder, elementType));
  8087. }
  8088. return mBfIRBuilder->CreateConstArray(mBfIRBuilder->MapType(wantType), newVals);
  8089. }
  8090. return mBfIRBuilder->CreateConst(constant, constHolder);
  8091. }
  8092. void BfModule::ValidateCustomAttributes(BfCustomAttributes* customAttributes, BfAttributeTargets attrTarget)
  8093. {
  8094. if (attrTarget == BfAttributeTargets_SkipValidate)
  8095. return;
  8096. for (auto& customAttribute : customAttributes->mAttributes)
  8097. {
  8098. if (!customAttribute.mAwaitingValidation)
  8099. continue;
  8100. if ((customAttribute.mType->mAttributeData->mAttributeTargets & attrTarget) == 0)
  8101. {
  8102. Fail(StrFormat("Attribute '%s' is not valid on this declaration type. It is only valid on %s.",
  8103. customAttribute.mRef->ToString().c_str(), GetAttributesTargetListString(customAttribute.mType->mAttributeData->mAttributeTargets).c_str()), customAttribute.mRef->mAttributeTypeRef); // CS0592
  8104. }
  8105. customAttribute.mAwaitingValidation = false;
  8106. }
  8107. }
  8108. void BfModule::GetCustomAttributes(BfCustomAttributes* customAttributes, BfAttributeDirective* attributesDirective, BfAttributeTargets attrTarget)
  8109. {
  8110. if ((attributesDirective != NULL) && (mCompiler->mResolvePassData != NULL) &&
  8111. (attributesDirective->IsFromParser(mCompiler->mResolvePassData->mParser)) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  8112. {
  8113. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(attributesDirective);
  8114. }
  8115. SetAndRestoreValue<bool> prevIsCapturingMethodMatchInfo;
  8116. if (mCompiler->IsAutocomplete())
  8117. prevIsCapturingMethodMatchInfo.Init(mCompiler->mResolvePassData->mAutoComplete->mIsCapturingMethodMatchInfo, false);
  8118. BfTypeInstance* baseAttrTypeInst = mContext->mUnreifiedModule->ResolveTypeDef(mCompiler->mAttributeTypeDef)->ToTypeInstance();
  8119. BfAttributeTargets targetOverride = (BfAttributeTargets)0;
  8120. BfAutoComplete* autoComplete = NULL;
  8121. if (mCompiler->mResolvePassData != NULL)
  8122. autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  8123. for (; attributesDirective != NULL; attributesDirective = attributesDirective->mNextAttribute)
  8124. {
  8125. BfAutoParentNodeEntry autoParentNodeEntry(this, attributesDirective);
  8126. BfCustomAttribute customAttribute;
  8127. customAttribute.mAwaitingValidation = true;
  8128. customAttribute.mRef = attributesDirective;
  8129. if (attributesDirective->mAttrOpenToken != NULL)
  8130. targetOverride = (BfAttributeTargets)0;
  8131. if (attributesDirective->mAttributeTypeRef == NULL)
  8132. {
  8133. AssertErrorState();
  8134. continue;
  8135. }
  8136. String attrName = attributesDirective->mAttributeTypeRef->ToString();
  8137. BfType* attrType = NULL;
  8138. BfAtomComposite nameComposite;
  8139. BfTypeDef* attrTypeDef = NULL;
  8140. if (mSystem->ParseAtomComposite(attrName + "Attribute", nameComposite))
  8141. {
  8142. BfTypeLookupError error;
  8143. error.mRefNode = attributesDirective->mAttributeTypeRef;
  8144. attrTypeDef = FindTypeDefRaw(nameComposite, 0, mCurTypeInstance, GetActiveTypeDef(NULL, true), &error);
  8145. }
  8146. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  8147. {
  8148. mCompiler->mResolvePassData->mAutoComplete->CheckAttributeTypeRef(attributesDirective->mAttributeTypeRef);
  8149. if (attrTypeDef != NULL)
  8150. mCompiler->mResolvePassData->HandleTypeReference(attributesDirective->mAttributeTypeRef, attrTypeDef);
  8151. }
  8152. if (attrTypeDef == NULL)
  8153. {
  8154. TypeRefNotFound(attributesDirective->mAttributeTypeRef, "Attribute");
  8155. continue;
  8156. }
  8157. bool isBypassedAttr = false;
  8158. if (attrTypeDef != NULL)
  8159. {
  8160. attrType = mContext->mUnreifiedModule->ResolveTypeDef(attrTypeDef, BfPopulateType_Identity);
  8161. // 'Object' has some dependencies on some attributes, but those attributes are classes so we have a circular dependency issue
  8162. // We solve it by having a 'bypass' for known attributes that Object depends on
  8163. if ((attributesDirective->mArguments.empty()) && (autoComplete == NULL) && (attrType != NULL) && (attrType->IsTypeInstance()))
  8164. {
  8165. if (attrTypeDef == mCompiler->mCReprAttributeTypeDef)
  8166. {
  8167. BfTypeInstance* attrTypeInst = attrType->ToTypeInstance();
  8168. for (auto methodDef : attrTypeDef->mMethods)
  8169. {
  8170. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mProtection == BfProtection_Public))
  8171. {
  8172. customAttribute.mType = attrType->ToTypeInstance();
  8173. customAttribute.mCtor = methodDef;
  8174. isBypassedAttr = true;
  8175. break;
  8176. }
  8177. }
  8178. }
  8179. }
  8180. if (isBypassedAttr)
  8181. {
  8182. customAttribute.mAwaitingValidation = false;
  8183. customAttributes->mAttributes.push_back(customAttribute);
  8184. continue;
  8185. }
  8186. if (mContext->mCurTypeState != NULL)
  8187. {
  8188. SetAndRestoreValue<BfTypeReference*> prevTypeRef(mContext->mCurTypeState->mCurAttributeTypeRef, attributesDirective->mAttributeTypeRef);
  8189. mContext->mUnreifiedModule->ResolveTypeResult(attributesDirective->mAttributeTypeRef, attrType, BfPopulateType_BaseType, (BfResolveTypeRefFlags)0);
  8190. }
  8191. else
  8192. {
  8193. mContext->mUnreifiedModule->ResolveTypeResult(attributesDirective->mAttributeTypeRef, attrType, BfPopulateType_BaseType, (BfResolveTypeRefFlags)0);
  8194. }
  8195. }
  8196. // Don't allow this
  8197. /*else if (mContext->mCurTypeState != NULL)
  8198. {
  8199. SetAndRestoreValue<BfTypeReference*> prevTypeRef(mContext->mCurTypeState->mCurAttributeTypeRef, attributesDirective->mAttributeTypeRef);
  8200. attrType = mContext->mUnreifiedModule->ResolveTypeRef(attributesDirective->mAttributeTypeRef, BfPopulateType_DataAndMethods);
  8201. }
  8202. else
  8203. {
  8204. attrType = mContext->mUnreifiedModule->ResolveTypeRef(attributesDirective->mAttributeTypeRef);
  8205. }*/
  8206. BfTypeInstance* attrTypeInst = NULL;
  8207. if (attrType == NULL)
  8208. continue;
  8209. mContext->mUnreifiedModule->PopulateType(attrType, BfPopulateType_DataAndMethods);
  8210. attrTypeInst = attrType->ToTypeInstance();
  8211. if ((attrTypeInst == NULL) || (!TypeIsSubTypeOf(attrTypeInst, baseAttrTypeInst)) || (attrTypeInst->mAttributeData == NULL))
  8212. {
  8213. Fail(StrFormat("'%s' is not an attribute class", TypeToString(attrType).c_str()), attributesDirective->mAttributeTypeRef); //CS0616
  8214. continue;
  8215. }
  8216. if (mCurTypeInstance != NULL)
  8217. AddDependency(attrTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  8218. customAttribute.mType = attrTypeInst;
  8219. BfConstResolver constResolver(this);
  8220. bool inPropSet = false;
  8221. SizedArray<BfResolvedArg, 2> argValues;
  8222. for (BfExpression* arg : attributesDirective->mArguments)
  8223. {
  8224. if (arg == NULL)
  8225. {
  8226. continue;
  8227. }
  8228. if (autoComplete != NULL)
  8229. autoComplete->mShowAttributeProperties = attrTypeInst;
  8230. if (auto assignExpr = BfNodeDynCast<BfAssignmentExpression>(arg))
  8231. {
  8232. inPropSet = true;
  8233. if (autoComplete != NULL)
  8234. autoComplete->CheckNode(assignExpr->mLeft);
  8235. String findName = assignExpr->mLeft->ToString();
  8236. BfPropertyDef* bestProp = NULL;
  8237. BfTypeInstance* bestPropTypeInst = NULL;
  8238. BfFieldDef* bestField = NULL;
  8239. BfTypeInstance* bestFieldTypeInst = NULL;
  8240. auto checkTypeInst = attrTypeInst;
  8241. while (checkTypeInst != NULL)
  8242. {
  8243. mContext->mUnreifiedModule->PopulateType(checkTypeInst, BfPopulateType_Data);
  8244. for (auto prop : checkTypeInst->mTypeDef->mProperties)
  8245. {
  8246. if (prop->mName == findName)
  8247. {
  8248. if ((bestProp == NULL) || (bestProp->mProtection != BfProtection_Public))
  8249. {
  8250. bestProp = prop;
  8251. bestPropTypeInst = checkTypeInst;
  8252. }
  8253. }
  8254. }
  8255. for (auto field : checkTypeInst->mTypeDef->mFields)
  8256. {
  8257. if (field->mName == findName)
  8258. {
  8259. if ((bestField == NULL) || (bestField->mProtection != BfProtection_Public))
  8260. {
  8261. bestField = field;
  8262. bestFieldTypeInst = checkTypeInst;
  8263. }
  8264. }
  8265. }
  8266. if ((bestProp != NULL) || (bestField != NULL))
  8267. break;
  8268. checkTypeInst = checkTypeInst->mBaseType;
  8269. }
  8270. bool handledExpr = false;
  8271. if (bestField != NULL)
  8272. {
  8273. handledExpr = true;
  8274. if (mCompiler->mResolvePassData != NULL)
  8275. {
  8276. mCompiler->mResolvePassData->HandleFieldReference(assignExpr->mLeft, attrTypeDef, bestField);
  8277. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(assignExpr->mLeft)))
  8278. {
  8279. autoComplete->mDefField = bestField;
  8280. autoComplete->mDefType = attrTypeDef;
  8281. }
  8282. }
  8283. if (bestField->mProtection != BfProtection_Public)
  8284. Fail(StrFormat("'%s.%s' is inaccessible due to its protection level", TypeToString(bestFieldTypeInst).c_str(), findName.c_str()), assignExpr->mLeft); // CS0122
  8285. AddDependency(bestFieldTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  8286. BfCustomAttributeSetField setField;
  8287. setField.mFieldRef = BfFieldRef(bestFieldTypeInst, bestField);
  8288. auto& fieldTypeInst = checkTypeInst->mFieldInstances[bestField->mIdx];
  8289. if (assignExpr->mRight != NULL)
  8290. {
  8291. BfTypedValue result = constResolver.Resolve(assignExpr->mRight, fieldTypeInst.mResolvedType);
  8292. if (result)
  8293. {
  8294. CurrentAddToConstHolder(result.mValue);
  8295. setField.mParam = result;
  8296. customAttribute.mSetField.push_back(setField);
  8297. }
  8298. }
  8299. }
  8300. else if (bestProp == NULL)
  8301. {
  8302. Fail(StrFormat("'%s' does not contain a field or property named '%s'", TypeToString(attrTypeInst).c_str(), findName.c_str()), assignExpr->mLeft);
  8303. }
  8304. else
  8305. {
  8306. BfMethodDef* setMethod = NULL;
  8307. for (auto methodDef : bestProp->mMethods)
  8308. {
  8309. if (methodDef->mMethodType == BfMethodType_PropertySetter)
  8310. {
  8311. setMethod = methodDef;
  8312. break;
  8313. }
  8314. }
  8315. if (setMethod == NULL)
  8316. {
  8317. Fail("Property has no setter", assignExpr->mLeft);
  8318. }
  8319. else
  8320. {
  8321. if (mCompiler->mResolvePassData != NULL)
  8322. {
  8323. mCompiler->mResolvePassData->HandlePropertyReference(assignExpr->mLeft, attrTypeDef, bestProp);
  8324. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(assignExpr->mLeft)))
  8325. {
  8326. autoComplete->mDefProp = bestProp;
  8327. autoComplete->mDefType = attrTypeDef;
  8328. }
  8329. }
  8330. handledExpr = true;
  8331. if (bestProp->mProtection != BfProtection_Public)
  8332. Fail(StrFormat("'%s.%s' is inaccessible due to its protection level", TypeToString(bestPropTypeInst).c_str(), findName.c_str()), assignExpr->mLeft); // CS0122
  8333. BfResolvedArg resolvedArg;
  8334. AddDependency(bestPropTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  8335. BfCustomAttributeSetProperty setProperty;
  8336. setProperty.mPropertyRef = BfPropertyRef(bestPropTypeInst, bestProp);
  8337. // We don't actually need the mFunc, so get the ModuleMethodInstance from the native module
  8338. auto methodInstance = bestPropTypeInst->mModule->GetMethodInstance(bestPropTypeInst, setMethod, BfTypeVector());
  8339. if (methodInstance.mMethodInstance != NULL)
  8340. {
  8341. auto propType = methodInstance.mMethodInstance->GetParamType(0);
  8342. if (assignExpr->mRight != NULL)
  8343. {
  8344. BfTypedValue result = constResolver.Resolve(assignExpr->mRight, propType);
  8345. if (result)
  8346. {
  8347. BF_ASSERT(result.mType == propType);
  8348. CurrentAddToConstHolder(result.mValue);
  8349. setProperty.mParam = result;
  8350. customAttribute.mSetProperties.push_back(setProperty);
  8351. }
  8352. }
  8353. }
  8354. }
  8355. }
  8356. if ((!handledExpr) && (assignExpr->mRight != NULL))
  8357. constResolver.Resolve(assignExpr->mRight);
  8358. }
  8359. else
  8360. {
  8361. if (inPropSet)
  8362. {
  8363. Fail("Named attribute argument expected", arg); // CS1016
  8364. }
  8365. BfDeferEvalChecker deferEvalChecker;
  8366. arg->Accept(&deferEvalChecker);
  8367. bool deferParamEval = deferEvalChecker.mNeedsDeferEval;
  8368. BfResolvedArg resolvedArg;
  8369. resolvedArg.mExpression = arg;
  8370. if (deferParamEval)
  8371. {
  8372. resolvedArg.mArgFlags = BfArgFlag_DeferredEval;
  8373. }
  8374. else
  8375. resolvedArg.mTypedValue = constResolver.Resolve(arg);
  8376. if (!inPropSet)
  8377. argValues.push_back(resolvedArg);
  8378. }
  8379. if (autoComplete != NULL)
  8380. autoComplete->mShowAttributeProperties = NULL;
  8381. }
  8382. auto wasCapturingMethodInfo = false;
  8383. if (autoComplete != NULL)
  8384. {
  8385. wasCapturingMethodInfo = autoComplete->mIsCapturingMethodMatchInfo;
  8386. if (attributesDirective->mCtorOpenParen != NULL)
  8387. autoComplete->CheckInvocation(attributesDirective, attributesDirective->mCtorOpenParen, attributesDirective->mCtorCloseParen, attributesDirective->mCommas);
  8388. }
  8389. BfMethodMatcher methodMatcher(attributesDirective, this, "", argValues, NULL);
  8390. attrTypeDef = attrTypeInst->mTypeDef;
  8391. bool success = true;
  8392. bool isFailurePass = false;
  8393. for (int pass = 0; pass < 2; pass++)
  8394. {
  8395. bool isFailurePass = pass == 1;
  8396. for (auto checkMethod : attrTypeDef->mMethods)
  8397. {
  8398. if ((isFailurePass) && (checkMethod->mMethodDeclaration == NULL))
  8399. continue; // Don't match private default ctor if there's a user-defined one
  8400. if ((checkMethod->mIsStatic) || (checkMethod->mMethodType != BfMethodType_Ctor))
  8401. continue;
  8402. if ((!isFailurePass) && (!CheckProtection(checkMethod->mProtection, false, false)))
  8403. continue;
  8404. methodMatcher.CheckMethod(attrTypeInst, checkMethod, isFailurePass);
  8405. }
  8406. if ((methodMatcher.mBestMethodDef != NULL) || (methodMatcher.mBackupMethodDef != NULL))
  8407. break;
  8408. }
  8409. if (autoComplete != NULL)
  8410. {
  8411. if ((wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo))
  8412. {
  8413. autoComplete->mIsCapturingMethodMatchInfo = true;
  8414. BF_ASSERT(autoComplete->mMethodMatchInfo != NULL);
  8415. }
  8416. else
  8417. autoComplete->mIsCapturingMethodMatchInfo = false;
  8418. }
  8419. if (methodMatcher.mBestMethodDef == NULL)
  8420. methodMatcher.mBestMethodDef = methodMatcher.mBackupMethodDef;
  8421. BF_ASSERT(methodMatcher.mBestMethodDef != NULL);
  8422. customAttribute.mCtor = methodMatcher.mBestMethodDef;
  8423. if (methodMatcher.mBestMethodTypeInstance == mCurTypeInstance)
  8424. {
  8425. Fail("Custom attribute circular reference", attributesDirective);
  8426. }
  8427. if (mCurTypeInstance != NULL)
  8428. AddDependency(methodMatcher.mBestMethodTypeInstance, mCurTypeInstance, BfDependencyMap::DependencyFlag_CustomAttribute);
  8429. if (!constResolver.PrepareMethodArguments(attributesDirective->mAttributeTypeRef, &methodMatcher, customAttribute.mCtorArgs))
  8430. success = false;
  8431. for (auto& arg : argValues)
  8432. {
  8433. if ((arg.mArgFlags & BfArgFlag_DeferredEval) != 0)
  8434. {
  8435. if (auto expr = BfNodeDynCast<BfExpression>(arg.mExpression))
  8436. constResolver.Resolve(expr);
  8437. }
  8438. }
  8439. // Move all those to the constHolder
  8440. for (auto& ctorArg : customAttribute.mCtorArgs)
  8441. {
  8442. CurrentAddToConstHolder(ctorArg);
  8443. }
  8444. if (attributesDirective->mAttributeTargetSpecifier != NULL)
  8445. {
  8446. targetOverride = BfAttributeTargets_ReturnValue;
  8447. if (attrTarget != BfAttributeTargets_Method)
  8448. {
  8449. 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.",
  8450. GetAttributesTargetListString(targetOverride).c_str(), GetAttributesTargetListString(attrTarget).c_str()), attributesDirective->mAttributeTargetSpecifier); // CS0657
  8451. }
  8452. success = false;
  8453. }
  8454. if ((success) && (targetOverride != (BfAttributeTargets)0))
  8455. {
  8456. if ((targetOverride == BfAttributeTargets_ReturnValue) && (attrTarget == BfAttributeTargets_Method))
  8457. {
  8458. auto methodInfoEx = mCurMethodInstance->GetMethodInfoEx();
  8459. if (methodInfoEx->mMethodCustomAttributes == NULL)
  8460. methodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  8461. if (success)
  8462. {
  8463. if (methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes == NULL)
  8464. methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes = new BfCustomAttributes();
  8465. methodInfoEx->mMethodCustomAttributes->mReturnCustomAttributes->mAttributes.push_back(customAttribute);
  8466. }
  8467. }
  8468. else
  8469. {
  8470. // Failed - ignore
  8471. success = false;
  8472. }
  8473. }
  8474. if (success)
  8475. {
  8476. if (!attrTypeInst->mAttributeData->mAllowMultiple)
  8477. {
  8478. for (auto& prevCustomAttribute : customAttributes->mAttributes)
  8479. {
  8480. if (prevCustomAttribute.mType == attrTypeInst)
  8481. {
  8482. Fail(StrFormat("Duplicate '%s' attribute", attributesDirective->mAttributeTypeRef->ToString().c_str()), attributesDirective->mAttributeTypeRef); // CS0579
  8483. }
  8484. }
  8485. }
  8486. }
  8487. if (success)
  8488. {
  8489. customAttributes->mAttributes.push_back(customAttribute);
  8490. }
  8491. }
  8492. ValidateCustomAttributes(customAttributes, attrTarget);
  8493. }
  8494. BfCustomAttributes* BfModule::GetCustomAttributes(BfAttributeDirective* attributesDirective, BfAttributeTargets attrType)
  8495. {
  8496. BfCustomAttributes* customAttributes = new BfCustomAttributes();
  8497. GetCustomAttributes(customAttributes, attributesDirective, attrType);
  8498. return customAttributes;
  8499. }
  8500. void BfModule::ProcessTypeInstCustomAttributes(bool& isPacked, bool& isUnion, bool& isCRepr, bool& isOrdered)
  8501. {
  8502. if (mCurTypeInstance->mCustomAttributes != NULL)
  8503. {
  8504. for (auto& customAttribute : mCurTypeInstance->mCustomAttributes->mAttributes)
  8505. {
  8506. String typeName = TypeToString(customAttribute.mType);
  8507. if (typeName == "System.PackedAttribute")
  8508. {
  8509. isPacked = true;
  8510. }
  8511. else if (typeName == "System.UnionAttribute")
  8512. {
  8513. isUnion = true;
  8514. }
  8515. else if (typeName == "System.CReprAttribute")
  8516. {
  8517. isCRepr = true;
  8518. isOrdered = true;
  8519. }
  8520. else if (typeName == "System.OrderedAttribute")
  8521. {
  8522. isOrdered = true;
  8523. }
  8524. else if (typeName == "System.AlwaysIncludeAttribute")
  8525. {
  8526. for (auto setProp : customAttribute.mSetProperties)
  8527. {
  8528. BfPropertyDef* propertyDef = setProp.mPropertyRef;
  8529. if (propertyDef->mName == "AssumeInstantiated")
  8530. {
  8531. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  8532. if ((constant != NULL) && (constant->mBool))
  8533. mCurTypeInstance->mHasBeenInstantiated = true;
  8534. }
  8535. }
  8536. }
  8537. }
  8538. }
  8539. }
  8540. // Checking to see if we're an attribute or not
  8541. void BfModule::ProcessCustomAttributeData()
  8542. {
  8543. bool isAttribute = false;
  8544. auto checkTypeInst = mCurTypeInstance->mBaseType;
  8545. while (checkTypeInst != NULL)
  8546. {
  8547. if (checkTypeInst->mTypeDef == mCompiler->mAttributeTypeDef)
  8548. isAttribute = true;
  8549. checkTypeInst = checkTypeInst->mBaseType;
  8550. }
  8551. if (!isAttribute)
  8552. return;
  8553. auto attributeData = new BfAttributeData();
  8554. bool hasCustomAttribute = false;
  8555. if (mCurTypeInstance->mCustomAttributes != NULL)
  8556. {
  8557. for (auto& customAttribute : mCurTypeInstance->mCustomAttributes->mAttributes)
  8558. {
  8559. if (customAttribute.mType->mTypeDef == mCompiler->mAttributeUsageAttributeTypeDef)
  8560. {
  8561. if (customAttribute.mCtorArgs.size() > 0)
  8562. {
  8563. auto constant = mCurTypeInstance->mConstHolder->GetConstant(customAttribute.mCtorArgs[0]);
  8564. if ((constant != NULL) && (mBfIRBuilder->IsInt(constant->mTypeCode)))
  8565. attributeData->mAttributeTargets = (BfAttributeTargets)constant->mInt32;
  8566. }
  8567. for (auto& setProp : customAttribute.mSetProperties)
  8568. {
  8569. BfPropertyDef* propDef = setProp.mPropertyRef;
  8570. if (propDef->mName == "AllowMultiple")
  8571. {
  8572. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  8573. if (constant != NULL)
  8574. attributeData->mAllowMultiple = constant->mBool;
  8575. }
  8576. else if (propDef->mName == "Inherited")
  8577. {
  8578. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  8579. if (constant != NULL)
  8580. attributeData->mInherited = constant->mBool;
  8581. }
  8582. else if (propDef->mName == "ValidOn")
  8583. {
  8584. auto constant = mCurTypeInstance->mConstHolder->GetConstant(setProp.mParam.mValue);
  8585. if (constant != NULL)
  8586. attributeData->mAttributeTargets = (BfAttributeTargets)constant->mInt32;
  8587. }
  8588. }
  8589. hasCustomAttribute = true;
  8590. }
  8591. }
  8592. }
  8593. if ((!hasCustomAttribute) && (mCurTypeInstance->mBaseType->mAttributeData != NULL))
  8594. {
  8595. attributeData->mAttributeTargets = mCurTypeInstance->mBaseType->mAttributeData->mAttributeTargets;
  8596. attributeData->mInherited = mCurTypeInstance->mBaseType->mAttributeData->mInherited;
  8597. attributeData->mAllowMultiple = mCurTypeInstance->mBaseType->mAttributeData->mAllowMultiple;
  8598. }
  8599. mCurTypeInstance->mAttributeData = attributeData;
  8600. }
  8601. bool BfModule::TryGetConstString(BfIRConstHolder* constHolder, BfIRValue irValue, StringImpl& str)
  8602. {
  8603. auto constant = constHolder->GetConstant(irValue);
  8604. if (constant == NULL)
  8605. return false;
  8606. if (!BfIRConstHolder::IsInt(constant->mTypeCode))
  8607. return false;
  8608. int stringId = constant->mInt32;
  8609. BfStringPoolEntry* entry = NULL;
  8610. if (mContext->mStringObjectIdMap.TryGetValue(stringId, &entry))
  8611. {
  8612. str = entry->mString;
  8613. }
  8614. else
  8615. {
  8616. BF_DBG_FATAL("Failed to find string by id");
  8617. }
  8618. return true;
  8619. }
  8620. BfVariant BfModule::TypedValueToVariant(BfAstNode* refNode, const BfTypedValue& value, bool allowUndef)
  8621. {
  8622. BfVariant variant;
  8623. variant.mTypeCode = BfTypeCode_None;
  8624. BfType* primType = NULL;
  8625. if (value.mType->IsPrimitiveType())
  8626. primType = (BfPrimitiveType*)value.mType;
  8627. else if (value.mType->IsTypedPrimitive())
  8628. primType = value.mType->GetUnderlyingType();
  8629. if (primType)
  8630. {
  8631. auto constant = mBfIRBuilder->GetConstant(value.mValue);
  8632. if (constant != NULL)
  8633. {
  8634. if ((allowUndef) && (constant->mConstType == BfConstType_Undef))
  8635. {
  8636. variant.mTypeCode = BfTypeCode_Let;
  8637. return variant;
  8638. }
  8639. switch (constant->mTypeCode)
  8640. {
  8641. case BfTypeCode_Int8:
  8642. case BfTypeCode_UInt8:
  8643. case BfTypeCode_Int16:
  8644. case BfTypeCode_UInt16:
  8645. case BfTypeCode_Int32:
  8646. case BfTypeCode_UInt32:
  8647. case BfTypeCode_Int64:
  8648. case BfTypeCode_UInt64:
  8649. case BfTypeCode_IntPtr:
  8650. case BfTypeCode_UIntPtr:
  8651. case BfTypeCode_IntUnknown:
  8652. case BfTypeCode_UIntUnknown:
  8653. case BfTypeCode_Single:
  8654. case BfTypeCode_Double:
  8655. case BfTypeCode_Char8:
  8656. case BfTypeCode_Char16:
  8657. case BfTypeCode_Char32:
  8658. variant.mTypeCode = constant->mTypeCode;
  8659. variant.mInt64 = constant->mInt64;
  8660. break;
  8661. default:
  8662. if (refNode != NULL)
  8663. Fail("Invalid const expression type", refNode);
  8664. break;
  8665. }
  8666. }
  8667. }
  8668. return variant;
  8669. }
  8670. BfTypedValue BfModule::RemoveRef(BfTypedValue typedValue)
  8671. {
  8672. if ((typedValue.mType != NULL) && (typedValue.mType->IsRef()))
  8673. {
  8674. auto elementType = typedValue.mType->GetUnderlyingType();
  8675. if (typedValue.IsAddr())
  8676. {
  8677. if (elementType->IsValuelessType())
  8678. {
  8679. BF_ASSERT(!typedValue.mValue);
  8680. typedValue = BfTypedValue(typedValue.mValue, elementType, true);
  8681. }
  8682. else
  8683. typedValue = BfTypedValue(mBfIRBuilder->CreateLoad(typedValue.mValue), elementType, true);
  8684. }
  8685. else
  8686. typedValue = BfTypedValue(typedValue.mValue, elementType, true);
  8687. if (typedValue.mType->IsValuelessType())
  8688. {
  8689. BF_ASSERT(typedValue.mValue.IsFake());
  8690. }
  8691. }
  8692. return typedValue;
  8693. }
  8694. BfTypedValue BfModule::LoadValue(BfTypedValue typedValue, BfAstNode* refNode, bool isVolatile)
  8695. {
  8696. if (!typedValue.IsAddr())
  8697. return typedValue;
  8698. if (typedValue.mType->IsValuelessType())
  8699. return BfTypedValue(mBfIRBuilder->GetFakeVal(), typedValue.mType, false);
  8700. BfIRValue loadedVal = typedValue.mValue;
  8701. if (loadedVal)
  8702. {
  8703. if (typedValue.mType->IsVar())
  8704. {
  8705. return BfTypedValue(loadedVal, typedValue.mType, false);
  8706. }
  8707. /*if (isVolatile)
  8708. mBfIRBuilder->CreateFence(BfIRFenceType_AcquireRelease);*/
  8709. PopulateType(typedValue.mType, BfPopulateType_Data);
  8710. loadedVal = mBfIRBuilder->CreateAlignedLoad(loadedVal, std::max(1, (int)typedValue.mType->mAlign), isVolatile);
  8711. }
  8712. return BfTypedValue(loadedVal, typedValue.mType, false);
  8713. }
  8714. BfTypedValue BfModule::LoadOrAggregateValue(BfTypedValue typedValue)
  8715. {
  8716. if (typedValue.IsSplat())
  8717. return AggregateSplat(typedValue);
  8718. if (typedValue.IsAddr())
  8719. return LoadValue(typedValue);
  8720. return typedValue;
  8721. }
  8722. BfTypedValue BfModule::AggregateSplat(BfTypedValue typedValue, BfIRValue* valueArrPtr)
  8723. {
  8724. if (!typedValue.IsSplat())
  8725. return typedValue;
  8726. if (typedValue.mType->IsValuelessType())
  8727. return typedValue;
  8728. int elementIdx = 0;
  8729. auto _ExtractValue = [&](BfType* checkType)
  8730. {
  8731. if (valueArrPtr != NULL)
  8732. return valueArrPtr[elementIdx++];
  8733. return ExtractSplatValue(typedValue, elementIdx++, checkType);
  8734. };
  8735. std::function<BfIRValue(BfType*)> checkTypeLambda = [&](BfType* checkType)
  8736. {
  8737. if (checkType->IsStruct())
  8738. {
  8739. BfIRValue curValue = mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(checkType, BfIRPopulateType_Full));
  8740. auto checkTypeInstance = checkType->ToTypeInstance();
  8741. if (checkTypeInstance->mBaseType != NULL)
  8742. {
  8743. mBfIRBuilder->PopulateType(checkTypeInstance->mBaseType, BfIRPopulateType_Full);
  8744. BfIRValue baseValue = checkTypeLambda(checkTypeInstance->mBaseType);
  8745. curValue = mBfIRBuilder->CreateInsertValue(curValue, baseValue, 0);
  8746. }
  8747. if (checkTypeInstance->mIsUnion)
  8748. {
  8749. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  8750. if (!unionInnerType->IsValuelessType())
  8751. {
  8752. BfIRValue fieldValue = checkTypeLambda(unionInnerType);
  8753. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, 1);
  8754. }
  8755. if (checkTypeInstance->IsEnum())
  8756. {
  8757. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  8758. BfIRValue fieldValue = checkTypeLambda(dscrType);
  8759. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, 2);
  8760. }
  8761. }
  8762. else
  8763. {
  8764. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  8765. {
  8766. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  8767. if (fieldInstance->mDataIdx >= 0)
  8768. {
  8769. BfIRValue fieldValue = checkTypeLambda(fieldInstance->GetResolvedType());
  8770. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, fieldInstance->mDataIdx);
  8771. }
  8772. }
  8773. }
  8774. return curValue;
  8775. }
  8776. else if (checkType->IsMethodRef())
  8777. {
  8778. BfMethodRefType* methodRefType = (BfMethodRefType*)checkType;
  8779. BfIRValue curValue = mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(checkType, BfIRPopulateType_Full));
  8780. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  8781. {
  8782. BfIRValue fieldValue;
  8783. auto checkType = methodRefType->GetCaptureType(dataIdx);
  8784. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  8785. {
  8786. fieldValue = checkTypeLambda(checkType);
  8787. }
  8788. else
  8789. {
  8790. fieldValue = _ExtractValue(checkType);
  8791. }
  8792. curValue = mBfIRBuilder->CreateInsertValue(curValue, fieldValue, dataIdx);
  8793. }
  8794. return curValue;
  8795. }
  8796. else if (!checkType->IsValuelessType())
  8797. {
  8798. return _ExtractValue(checkType);
  8799. }
  8800. return BfIRValue();
  8801. };
  8802. BfIRValue value = checkTypeLambda(typedValue.mType);
  8803. return BfTypedValue(value, typedValue.mType, typedValue.IsThis() ? BfTypedValueKind_ThisValue : BfTypedValueKind_Value);
  8804. }
  8805. void BfModule::AggregateSplatIntoAddr(BfTypedValue typedValue, BfIRValue addrVal)
  8806. {
  8807. if (!typedValue.IsSplat())
  8808. return;
  8809. if (typedValue.mType->IsValuelessType())
  8810. return;
  8811. /*static int sCallIdx = 0;
  8812. if (!mCompiler->mIsResolveOnly)
  8813. sCallIdx++;
  8814. int callIdx = sCallIdx;*/
  8815. int elementIdx = 0;
  8816. std::function<void(BfType*, BfIRValue)> checkTypeLambda = [&](BfType* checkType, BfIRValue curAddrVal)
  8817. {
  8818. if (checkType->IsStruct())
  8819. {
  8820. auto checkTypeInstance = checkType->ToTypeInstance();
  8821. if (checkTypeInstance->mBaseType != NULL)
  8822. {
  8823. mBfIRBuilder->PopulateType(checkTypeInstance->mBaseType);
  8824. auto baseAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 0);
  8825. checkTypeLambda(checkTypeInstance->mBaseType, baseAddrVal);
  8826. }
  8827. if (checkTypeInstance->mIsUnion)
  8828. {
  8829. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  8830. if (!unionInnerType->IsValuelessType())
  8831. {
  8832. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 1);
  8833. checkTypeLambda(unionInnerType, fieldAddrVal);
  8834. }
  8835. if (checkTypeInstance->IsEnum())
  8836. {
  8837. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  8838. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, 2);
  8839. checkTypeLambda(dscrType, fieldAddrVal);
  8840. }
  8841. }
  8842. else
  8843. {
  8844. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  8845. {
  8846. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  8847. if (fieldInstance->mDataIdx >= 0)
  8848. {
  8849. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, fieldInstance->mDataIdx);
  8850. checkTypeLambda(fieldInstance->mResolvedType, fieldAddrVal);
  8851. }
  8852. }
  8853. }
  8854. }
  8855. else if (checkType->IsMethodRef())
  8856. {
  8857. BfMethodRefType* methodRefType = (BfMethodRefType*)checkType;
  8858. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  8859. {
  8860. auto dataType = methodRefType->GetCaptureType(dataIdx);
  8861. auto fieldAddrVal = mBfIRBuilder->CreateInBoundsGEP(curAddrVal, 0, dataIdx);
  8862. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  8863. {
  8864. checkTypeLambda(methodRefType->GetCaptureType(dataIdx), fieldAddrVal);
  8865. }
  8866. else
  8867. {
  8868. // static int sItrCount = 0;
  8869. // sItrCount++;
  8870. // int curItr = sItrCount;
  8871. // if (curItr == 1)
  8872. // {
  8873. // NOP;
  8874. // }
  8875. auto val = ExtractSplatValue(typedValue, elementIdx++, dataType);
  8876. mBfIRBuilder->CreateStore(val, fieldAddrVal);
  8877. }
  8878. }
  8879. }
  8880. else if (!checkType->IsValuelessType())
  8881. {
  8882. auto val = ExtractSplatValue(typedValue, elementIdx++, checkType);
  8883. mBfIRBuilder->CreateStore(val, curAddrVal);
  8884. }
  8885. };
  8886. checkTypeLambda(typedValue.mType, addrVal);
  8887. }
  8888. BfTypedValue BfModule::MakeAddressable(BfTypedValue typedVal)
  8889. {
  8890. bool wasReadOnly = typedVal.IsReadOnly();
  8891. if ((typedVal.mType->IsValueType()) &&
  8892. (!typedVal.mType->IsValuelessType()))
  8893. {
  8894. wasReadOnly = true; // Any non-addr is implicitly read-only
  8895. //static int gCallIdx = 0;
  8896. if (typedVal.IsAddr())
  8897. return typedVal;
  8898. BfType* type = typedVal.mType;
  8899. PopulateType(type);
  8900. auto tempVar = CreateAlloca(type);
  8901. if (typedVal.IsSplat())
  8902. AggregateSplatIntoAddr(typedVal, tempVar);
  8903. else
  8904. mBfIRBuilder->CreateAlignedStore(typedVal.mValue, tempVar, type->mAlign);
  8905. return BfTypedValue(tempVar, type,
  8906. typedVal.IsThis() ?
  8907. (wasReadOnly ? BfTypedValueKind_ReadOnlyThisAddr : BfTypedValueKind_ThisAddr) :
  8908. (wasReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr));
  8909. }
  8910. return LoadValue(typedVal);
  8911. }
  8912. BfTypedValue BfModule::RemoveReadOnly(BfTypedValue typedValue)
  8913. {
  8914. if (typedValue.mKind == BfTypedValueKind_ReadOnlyAddr)
  8915. typedValue.mKind = BfTypedValueKind_Addr;
  8916. return typedValue;
  8917. }
  8918. BfIRValue BfModule::ExtractSplatValue(BfTypedValue typedValue, int componentIdx, BfType* wantType, bool* isAddr)
  8919. {
  8920. BfIRValue val;
  8921. if (typedValue.mValue.IsArg())
  8922. {
  8923. val = mBfIRBuilder->GetArgument(typedValue.mValue.mId + componentIdx);
  8924. if (isAddr != NULL)
  8925. {
  8926. if (wantType != NULL)
  8927. *isAddr = wantType->IsComposite();
  8928. else
  8929. *isAddr = false;
  8930. }
  8931. else if (wantType->IsComposite())
  8932. val = mBfIRBuilder->CreateLoad(val);
  8933. }
  8934. if (!val)
  8935. {
  8936. auto checkMethodState = mCurMethodState;
  8937. while (checkMethodState != NULL)
  8938. {
  8939. for (int idx = 0; idx < (int)checkMethodState->mSplatDecompAddrs.size(); idx++)
  8940. {
  8941. auto decompAddr = checkMethodState->mSplatDecompAddrs[idx];
  8942. if (decompAddr == typedValue.mValue)
  8943. {
  8944. val = checkMethodState->mSplatDecompAddrs[idx + componentIdx];
  8945. if ((wantType->IsComposite()) && (typedValue.mType->IsMethodRef()))
  8946. {
  8947. // This is really backing for a POINTER to a composite inside a methodRef
  8948. val = mBfIRBuilder->CreateLoad(val);
  8949. }
  8950. if ((isAddr != NULL) && (typedValue.mKind != BfTypedValueKind_SplatHead_NeedsCasting))
  8951. {
  8952. *isAddr = true;
  8953. return val;
  8954. }
  8955. else
  8956. {
  8957. val = mBfIRBuilder->CreateLoad(val);
  8958. break;
  8959. }
  8960. }
  8961. }
  8962. if (val)
  8963. break;
  8964. checkMethodState = checkMethodState->mPrevMethodState;
  8965. }
  8966. }
  8967. if (val)
  8968. {
  8969. if (typedValue.mKind == BfTypedValueKind_SplatHead_NeedsCasting)
  8970. {
  8971. BF_ASSERT(wantType != NULL);
  8972. if (wantType != NULL)
  8973. return mBfIRBuilder->CreateBitCast(val, mBfIRBuilder->MapType(wantType));
  8974. }
  8975. return val;
  8976. }
  8977. BF_FATAL("Splat not found");
  8978. return BfIRValue();
  8979. }
  8980. BfTypedValue BfModule::ExtractValue(BfTypedValue typedValue, BfFieldInstance* fieldInstance, int fieldIdx)
  8981. {
  8982. int useFieldIdx = fieldIdx;
  8983. BfType* fieldType = NULL;
  8984. if (fieldInstance != NULL)
  8985. {
  8986. fieldType = fieldInstance->mResolvedType;
  8987. if (typedValue.mType->IsUnion())
  8988. {
  8989. if (fieldIdx == 1)
  8990. {
  8991. if (typedValue.IsSplat())
  8992. {
  8993. BfTypedValue innerVal = typedValue;
  8994. innerVal.mType = fieldType;
  8995. return innerVal;
  8996. }
  8997. }
  8998. }
  8999. }
  9000. else
  9001. {
  9002. if (typedValue.mType->IsPayloadEnum())
  9003. {
  9004. auto typeInst = typedValue.mType->ToTypeInstance();
  9005. if (fieldIdx == 1)
  9006. fieldType = typeInst->GetUnionInnerType();
  9007. else if (fieldIdx == 2)
  9008. {
  9009. fieldType = typeInst->GetDiscriminatorType(&useFieldIdx);
  9010. }
  9011. }
  9012. else if (typedValue.mType->IsUnion())
  9013. {
  9014. if (fieldIdx == 1)
  9015. {
  9016. fieldType = typedValue.mType->ToTypeInstance()->GetUnionInnerType();
  9017. if (typedValue.IsSplat())
  9018. {
  9019. BfTypedValue innerVal = typedValue;
  9020. innerVal.mType = fieldType;
  9021. return innerVal;
  9022. }
  9023. }
  9024. }
  9025. }
  9026. BF_ASSERT(typedValue.mType->IsStruct());
  9027. if (typedValue.IsSplat())
  9028. {
  9029. if (typedValue.mType->IsPayloadEnum())
  9030. {
  9031. if (fieldIdx == 1)
  9032. {
  9033. // Payload
  9034. auto typeInst = typedValue.mType->ToTypeInstance();
  9035. auto unionInnerType = typeInst->GetUnionInnerType();
  9036. bool isAddr = false;
  9037. BfIRValue irVal = ExtractSplatValue(typedValue, 0, unionInnerType, &isAddr);
  9038. return BfTypedValue(irVal, unionInnerType, BfTypedValueKind_SplatHead);
  9039. }
  9040. if (fieldIdx == 2)
  9041. {
  9042. // Discriminator
  9043. auto typeInst = typedValue.mType->ToTypeInstance();
  9044. auto unionInnerType = typeInst->GetUnionInnerType();
  9045. auto dscrType = typeInst->GetDiscriminatorType();
  9046. int argIdx = typedValue.mValue.mId;
  9047. int componentIdx = 0;
  9048. BfTypeUtils::SplatIterate([&](BfType* checkType) { componentIdx++; }, unionInnerType);
  9049. bool isAddr;
  9050. BfIRValue irVal = ExtractSplatValue(typedValue, componentIdx, dscrType, &isAddr);
  9051. return BfTypedValue(irVal, dscrType, isAddr);
  9052. }
  9053. }
  9054. int componentIdx = 0;
  9055. BfTypedValue retVal;
  9056. BfFieldInstance* wantFieldInstance = fieldInstance;
  9057. std::function<void(BfType*)> checkTypeLambda = [&](BfType* checkType)
  9058. {
  9059. if (checkType->IsStruct())
  9060. {
  9061. auto checkTypeInstance = checkType->ToTypeInstance();
  9062. if ((checkType->IsUnion()) || (checkType->IsEnum()))
  9063. {
  9064. //TODO: Why did we have this removed? It messed up an extraction from a nullable splattable
  9065. fieldType = checkTypeInstance->GetUnionInnerType();
  9066. checkTypeLambda(fieldType);
  9067. if (checkType->IsEnum())
  9068. {
  9069. // Past discriminator...
  9070. componentIdx++;
  9071. }
  9072. return;
  9073. }
  9074. if (checkTypeInstance->mBaseType != NULL)
  9075. checkTypeLambda(checkTypeInstance->mBaseType);
  9076. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  9077. {
  9078. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  9079. if (fieldInstance == wantFieldInstance)
  9080. {
  9081. bool isAddr = false;
  9082. BfIRValue val = ExtractSplatValue(typedValue, componentIdx, fieldInstance->mResolvedType, &isAddr);
  9083. retVal = BfTypedValue(val, fieldInstance->mResolvedType,
  9084. fieldInstance->mResolvedType->IsComposite() ? BfTypedValueKind_SplatHead :
  9085. isAddr ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Value);
  9086. if ((retVal.IsAddr()) && (!fieldInstance->mResolvedType->IsValueType()))
  9087. {
  9088. retVal = LoadValue(retVal);
  9089. }
  9090. break;
  9091. }
  9092. if (fieldInstance->mDataIdx >= 0)
  9093. checkTypeLambda(fieldInstance->GetResolvedType());
  9094. }
  9095. }
  9096. else if (!checkType->IsValuelessType())
  9097. {
  9098. componentIdx++;
  9099. //argIdx++;
  9100. }
  9101. };
  9102. checkTypeLambda(typedValue.mType);
  9103. BF_ASSERT(retVal);
  9104. return retVal;
  9105. }
  9106. if (typedValue.IsAddr())
  9107. {
  9108. BF_ASSERT(fieldType != NULL);
  9109. auto valRef = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, useFieldIdx);
  9110. return BfTypedValue(valRef, fieldType, BfTypedValueKind_ReadOnlyAddr);
  9111. }
  9112. else
  9113. {
  9114. BF_ASSERT(fieldType != NULL);
  9115. return BfTypedValue(mBfIRBuilder->CreateExtractValue(typedValue.mValue, useFieldIdx), fieldType, BfTypedValueKind_Value);
  9116. }
  9117. }
  9118. BfIRValue BfModule::ExtractValue(BfTypedValue typedValue, int dataIdx)
  9119. {
  9120. if (typedValue.IsAddr())
  9121. {
  9122. auto addrVal = mBfIRBuilder->CreateInBoundsGEP(typedValue.mValue, 0, dataIdx);
  9123. return mBfIRBuilder->CreateLoad(addrVal);
  9124. }
  9125. return mBfIRBuilder->CreateExtractValue(typedValue.mValue, dataIdx);
  9126. }
  9127. BfIRValue BfModule::CreateIndexedValue(BfType* elementType, BfIRValue value, BfIRValue indexValue, bool isElementIndex)
  9128. {
  9129. if (elementType->IsSizeAligned())
  9130. {
  9131. if (isElementIndex)
  9132. return mBfIRBuilder->CreateInBoundsGEP(value, GetConstValue(0), indexValue);
  9133. else
  9134. return mBfIRBuilder->CreateInBoundsGEP(value, indexValue);
  9135. }
  9136. auto ptrType = CreatePointerType(elementType);
  9137. auto ofsVal = mBfIRBuilder->CreateNumericCast(indexValue, true, BfTypeCode_IntPtr);
  9138. auto ofsScaledVal = mBfIRBuilder->CreateMul(ofsVal, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, elementType->GetStride()));
  9139. auto intVal = mBfIRBuilder->CreatePtrToInt(value, BfTypeCode_IntPtr);
  9140. auto newIntVal = mBfIRBuilder->CreateAdd(intVal, ofsScaledVal);
  9141. return mBfIRBuilder->CreateIntToPtr(newIntVal, mBfIRBuilder->MapType(ptrType));
  9142. }
  9143. BfIRValue BfModule::CreateIndexedValue(BfType* elementType, BfIRValue value, int indexValue, bool isElementIndex)
  9144. {
  9145. if (elementType->IsSizeAligned())
  9146. {
  9147. if (isElementIndex)
  9148. return mBfIRBuilder->CreateInBoundsGEP(value, 0, indexValue);
  9149. else
  9150. return mBfIRBuilder->CreateInBoundsGEP(value, indexValue);
  9151. }
  9152. return CreateIndexedValue(elementType, value, GetConstValue(indexValue), isElementIndex);
  9153. }
  9154. bool BfModule::CheckModifyValue(BfTypedValue& typedValue, BfAstNode* refNode, const char* modifyType)
  9155. {
  9156. if (modifyType == NULL)
  9157. modifyType = "modify";
  9158. if (typedValue.mType->IsVar())
  9159. return true;
  9160. if (typedValue.IsReadOnly())
  9161. {
  9162. Fail(StrFormat("Cannot %s read-only variable", modifyType), refNode);
  9163. return false;
  9164. }
  9165. if ((!typedValue.IsAddr()) && (!typedValue.mType->IsValuelessType()))
  9166. {
  9167. Fail(StrFormat("Cannot %s value", modifyType), refNode);
  9168. return false;
  9169. }
  9170. if (typedValue.mKind == BfTypedValueKind_TempAddr)
  9171. {
  9172. Fail(StrFormat("Cannot %s temporary value", modifyType), refNode);
  9173. return false;
  9174. }
  9175. return true;
  9176. }
  9177. bool BfModule::CompareMethodSignatures(BfMethodInstance* methodA, BfMethodInstance* methodB)
  9178. {
  9179. // If one is an interface and the other is an impl, B is the impl
  9180. auto implOwner = methodB->GetOwner();
  9181. if (methodA->mMethodDef->mIsLocalMethod)
  9182. {
  9183. int sepPosA = (int)BF_MIN(methodA->mMethodDef->mName.IndexOf('@'), methodA->mMethodDef->mName.length());
  9184. int sepPosB = (int)BF_MIN(methodB->mMethodDef->mName.IndexOf('@'), methodB->mMethodDef->mName.length());
  9185. if (sepPosA != sepPosB)
  9186. return false;
  9187. if (strncmp(methodA->mMethodDef->mName.c_str(), methodB->mMethodDef->mName.c_str(), sepPosA) != 0)
  9188. return false;
  9189. }
  9190. else if (methodA->mMethodDef->mName != methodB->mMethodDef->mName)
  9191. return false;
  9192. if (methodA->mMethodDef->mCheckedKind != methodB->mMethodDef->mCheckedKind)
  9193. return false;
  9194. if (methodA->mMethodDef->mMethodType == BfMethodType_Ctor)
  9195. {
  9196. if (methodA->mMethodDef->mIsStatic != methodB->mMethodDef->mIsStatic)
  9197. return false;
  9198. }
  9199. if (methodA->mMethodDef->mMethodType == BfMethodType_Operator)
  9200. {
  9201. if (methodB->mMethodDef->mMethodType != BfMethodType_Operator)
  9202. return false;
  9203. auto operatorA = (BfOperatorDef*)methodA->mMethodDef;
  9204. auto operatorB = (BfOperatorDef*)methodB->mMethodDef;
  9205. if (operatorA->mOperatorDeclaration->mBinOp != operatorB->mOperatorDeclaration->mBinOp)
  9206. return false;
  9207. if (operatorA->mOperatorDeclaration->mUnaryOp != operatorB->mOperatorDeclaration->mUnaryOp)
  9208. return false;
  9209. if (operatorA->mOperatorDeclaration->mIsConvOperator)
  9210. {
  9211. if (!BfTypeUtils::TypeEquals(methodA->mReturnType, methodB->mReturnType, implOwner))
  9212. return false;
  9213. }
  9214. }
  9215. int implicitParamCountA = methodA->GetImplicitParamCount();
  9216. int implicitParamCountB = methodB->GetImplicitParamCount();
  9217. if (methodA->GetParamCount() - implicitParamCountA != methodB->GetParamCount() - implicitParamCountB)
  9218. return false;
  9219. if (methodA->mHadGenericDelegateParams != methodB->mHadGenericDelegateParams)
  9220. return false;
  9221. for (int paramIdx = 0; paramIdx < (int)methodA->GetParamCount() - implicitParamCountA; paramIdx++)
  9222. {
  9223. if ((!BfTypeUtils::TypeEquals(methodA->GetParamType(paramIdx + implicitParamCountA), methodB->GetParamType(paramIdx + implicitParamCountB), implOwner)) ||
  9224. (methodA->GetParamKind(paramIdx + implicitParamCountA) != methodB->GetParamKind(paramIdx + implicitParamCountB)))
  9225. return false;
  9226. }
  9227. // Compare generic params. Generic params are part of the method signature here
  9228. if (methodA->GetNumGenericParams() != methodB->GetNumGenericParams())
  9229. return false;
  9230. for (int genericParamIdx = 0; genericParamIdx < (int)methodA->GetNumGenericParams(); genericParamIdx++)
  9231. {
  9232. auto genericParamA = methodA->mMethodInfoEx->mGenericParams[genericParamIdx];
  9233. auto genericParamB = methodB->mMethodInfoEx->mGenericParams[genericParamIdx];
  9234. if (genericParamA->mGenericParamFlags != genericParamB->mGenericParamFlags)
  9235. return false;
  9236. if (genericParamA->mTypeConstraint != genericParamB->mTypeConstraint)
  9237. return false;
  9238. if (genericParamA->mInterfaceConstraints.size() != genericParamB->mInterfaceConstraints.size())
  9239. return false;
  9240. for (int interfaceIdx = 0; interfaceIdx < (int)genericParamA->mInterfaceConstraints.size(); interfaceIdx++)
  9241. if (genericParamA->mInterfaceConstraints[interfaceIdx] != genericParamB->mInterfaceConstraints[interfaceIdx])
  9242. return false;
  9243. }
  9244. return true;
  9245. }
  9246. bool BfModule::IsCompatibleInterfaceMethod(BfMethodInstance* iMethodInst, BfMethodInstance* methodInstance)
  9247. {
  9248. if (iMethodInst->mMethodDef->mName != methodInstance->mMethodDef->mName)
  9249. return false;
  9250. if (iMethodInst->mMethodDef->mIsOperator != methodInstance->mMethodDef->mIsOperator)
  9251. return false;
  9252. if (iMethodInst->mMethodDef->mIsOperator)
  9253. {
  9254. auto iOperatorDef = (BfOperatorDef*)iMethodInst->mMethodDef;
  9255. auto operatorDef = (BfOperatorDef*)methodInstance->mMethodDef;
  9256. if (iOperatorDef->mOperatorDeclaration->mUnaryOp != operatorDef->mOperatorDeclaration->mUnaryOp)
  9257. return false;
  9258. if (iOperatorDef->mOperatorDeclaration->mBinOp != operatorDef->mOperatorDeclaration->mBinOp)
  9259. return false;
  9260. }
  9261. if (iMethodInst->GetParamCount() != methodInstance->GetParamCount())
  9262. return false;
  9263. for (int paramIdx = 0; paramIdx < (int)iMethodInst->GetParamCount(); paramIdx++)
  9264. {
  9265. if (iMethodInst->GetParamKind(paramIdx) != methodInstance->GetParamKind(paramIdx))
  9266. return false;
  9267. BfType* iParamType = iMethodInst->GetParamType(paramIdx);
  9268. BfType* methodParamType = methodInstance->GetParamType(paramIdx);
  9269. if (iParamType->IsSelf())
  9270. {
  9271. if (methodParamType != methodInstance->GetOwner())
  9272. return false;
  9273. }
  9274. else if (!iParamType->IsGenericParam())
  9275. {
  9276. if (methodParamType != iParamType)
  9277. return false;
  9278. }
  9279. else
  9280. {
  9281. if (!methodParamType->IsGenericParam())
  9282. return false;
  9283. auto genericParamType = (BfGenericParamType*)methodParamType;
  9284. if (genericParamType->mGenericParamKind == BfGenericParamKind_Type)
  9285. return false;
  9286. auto genericParam = methodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  9287. bool hadInterface = false;
  9288. for (auto interfaceConstraint : genericParam->mInterfaceConstraints)
  9289. if (interfaceConstraint == iParamType)
  9290. hadInterface = true;
  9291. if (!hadInterface)
  9292. return false;
  9293. }
  9294. }
  9295. return true;
  9296. }
  9297. void BfModule::AddMethodReference(const BfMethodRef& methodRef, BfGetMethodInstanceFlags flags)
  9298. {
  9299. BfMethodInstance* methodInstance = methodRef;
  9300. if ((mCurTypeInstance != NULL) && (!mCompiler->IsAutocomplete()))
  9301. {
  9302. auto methodInstanceGroup = methodInstance->mMethodInstanceGroup;
  9303. if ((methodInstance->IsSpecializedGenericMethod()) || (methodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_AlwaysInclude))
  9304. {
  9305. BF_ASSERT(!methodRef.mTypeInstance->IsFunction());
  9306. BfMethodRef methodRef = methodInstance;
  9307. BfSpecializedMethodRefInfo* specializedMethodRefInfo = NULL;
  9308. bool isNew = mCurTypeInstance->mSpecializedMethodReferences.TryAdd(methodRef, NULL, &specializedMethodRefInfo);
  9309. if (((flags & BfGetMethodInstanceFlag_Unreified) == 0) &&
  9310. ((flags & BfGetMethodInstanceFlag_NoForceReification) == 0) &&
  9311. (mIsReified))
  9312. {
  9313. specializedMethodRefInfo->mHasReifiedRef = true;
  9314. }
  9315. }
  9316. }
  9317. }
  9318. BfModuleMethodInstance BfModule::ReferenceExternalMethodInstance(BfMethodInstance* methodInstance, BfGetMethodInstanceFlags flags)
  9319. {
  9320. if ((flags & BfGetMethodInstanceFlag_ResultNotUsed) != 0)
  9321. return BfModuleMethodInstance(methodInstance, BfIRValue());
  9322. if (mBfIRBuilder == NULL)
  9323. return BfModuleMethodInstance(methodInstance, BfIRValue());
  9324. if (methodInstance->GetOwner()->IsFunction())
  9325. {
  9326. // No actual ref needed- not an actual generated function
  9327. return BfModuleMethodInstance(methodInstance, BfIRValue());
  9328. }
  9329. bool isGenFunction = methodInstance->mMethodInstanceGroup->mMethodIdx < 0;
  9330. if (!isGenFunction)
  9331. AddMethodReference(methodInstance, flags);
  9332. if (mBfIRBuilder->mIgnoreWrites)
  9333. return BfModuleMethodInstance(methodInstance, mBfIRBuilder->GetFakeVal());
  9334. if (mCompiler->IsSkippingExtraResolveChecks())
  9335. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  9336. if (methodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)
  9337. {
  9338. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  9339. }
  9340. bool isInlined = (methodInstance->mAlwaysInline) || ((flags & BfGetMethodInstanceFlag_ForceInline) != 0);
  9341. BfMethodRef methodRef = methodInstance;
  9342. if (isInlined)
  9343. methodRef.mMethodRefFlags = (BfMethodRefFlags)(methodRef.mMethodRefFlags | BfMethodRefFlag_AlwaysInclude);
  9344. else
  9345. methodRef.mMethodRefFlags = BfMethodRefFlag_None;
  9346. if (!isGenFunction)
  9347. {
  9348. BfIRValue* irFuncPtr = NULL;
  9349. if (mFuncReferences.TryGetValue(methodRef, &irFuncPtr))
  9350. return BfModuleMethodInstance(methodInstance, *irFuncPtr);
  9351. }
  9352. if (mAwaitingInitFinish)
  9353. FinishInit();
  9354. BfIRValue func = CreateFunctionFrom(methodInstance, isGenFunction, isInlined);
  9355. if (!isGenFunction)
  9356. mFuncReferences[methodRef] = func;
  9357. BfLogSysM("Adding func reference. Module:%p MethodInst:%p NewLLVMFunc:%d OldLLVMFunc:%d\n", this, methodInstance, func.mId, methodInstance->mIRFunction.mId);
  9358. if ((isInlined) && (!mIsScratchModule))
  9359. {
  9360. // We can't just add a dependency to mCurTypeInstance because we may have nested inlined functions, and
  9361. // mCurTypeInstance will just reflect the owner of the method currently being inlined, not the top-level
  9362. // type instance
  9363. // Be smarter about this if we ever insert a lot of type instances into a single module - track in a field
  9364. BF_ASSERT(mOwnedTypeInstances.size() <= 1);
  9365. for (auto ownedTypeInst : mOwnedTypeInstances)
  9366. AddDependency(methodInstance->GetOwner(), ownedTypeInst, BfDependencyMap::DependencyFlag_InlinedCall);
  9367. if ((!mCompiler->mIsResolveOnly) && (mIsReified) && (!methodInstance->mIsUnspecialized))
  9368. {
  9369. mIncompleteMethodCount++;
  9370. BfInlineMethodRequest* inlineMethodRequest = mContext->mInlineMethodWorkList.Alloc();
  9371. inlineMethodRequest->mType = methodInstance->GetOwner();
  9372. inlineMethodRequest->mFromModule = this;
  9373. inlineMethodRequest->mFunc = func;
  9374. inlineMethodRequest->mFromModuleRevision = mRevision;
  9375. inlineMethodRequest->mMethodInstance = methodInstance;
  9376. BF_ASSERT(mIsModuleMutable);
  9377. BfLogSysM("mInlineMethodWorkList %p for method %p in module %p in ReferenceExternalMethodInstance\n", inlineMethodRequest, methodInstance, this);
  9378. }
  9379. }
  9380. return BfModuleMethodInstance(methodInstance, func);
  9381. }
  9382. BfModule* BfModule::GetOrCreateMethodModule(BfMethodInstance* methodInstance)
  9383. {
  9384. BfTypeInstance* typeInst = methodInstance->mMethodInstanceGroup->mOwner;
  9385. if (mBfIRBuilder == NULL)
  9386. {
  9387. // To allow for custom attribute data
  9388. PrepareForIRWriting(typeInst);
  9389. }
  9390. BfModule* declareModule = this;
  9391. // Get to the optionless branch head -- but this could still be a specialized method module, not the true root
  9392. while ((declareModule->mParentModule != NULL) && (!declareModule->mIsSpecializedMethodModuleRoot))
  9393. declareModule = declareModule->mParentModule;
  9394. // Check for attributes
  9395. if (typeInst == mContext->mBfObjectType)
  9396. {
  9397. auto methodDecl = methodInstance->mMethodDef->GetMethodDeclaration();
  9398. if (methodDecl != NULL)
  9399. {
  9400. auto attributesDirective = methodDecl->mAttributes;
  9401. if ((attributesDirective != NULL) && (mCompiler->mResolvePassData != NULL) &&
  9402. (attributesDirective->IsFromParser(mCompiler->mResolvePassData->mParser)) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  9403. {
  9404. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(attributesDirective);
  9405. }
  9406. }
  9407. }
  9408. else
  9409. {
  9410. // Only allow attributes on System.Object methods that can be handled inside the DefBuilder
  9411. GetMethodCustomAttributes(methodInstance);
  9412. }
  9413. BF_ASSERT(mModuleOptions == NULL);
  9414. if (methodInstance->GetCustomAttributes() != NULL)
  9415. {
  9416. auto project = typeInst->mTypeDef->mProject;
  9417. BfModuleOptions moduleOptions = declareModule->GetModuleOptions();
  9418. BfModuleOptions wantOptions = moduleOptions;
  9419. auto typeOptions = mSystem->GetTypeOptions(typeInst->mTypeOptionsIdx);
  9420. if (typeOptions != NULL)
  9421. {
  9422. wantOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)wantOptions.mOptLevel, (int)typeOptions->mOptimizationLevel);
  9423. wantOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mSIMDSetting, typeOptions->mSIMDSetting);
  9424. wantOptions.mEmitDebugInfo = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mEmitDebugInfo, typeOptions->mEmitDebugInfo);
  9425. }
  9426. if (!mCompiler->mAttributeTypeOptionMap.IsEmpty())
  9427. {
  9428. StringT<128> attrName;
  9429. for (auto& customAttrs : methodInstance->GetCustomAttributes()->mAttributes)
  9430. {
  9431. attrName.Clear();
  9432. customAttrs.mType->mTypeDef->mFullName.ToString(attrName);
  9433. Array<int>* arrPtr;
  9434. if (mCompiler->mAttributeTypeOptionMap.TryGetValue(attrName, &arrPtr))
  9435. {
  9436. for (auto optionsIdx : *arrPtr)
  9437. {
  9438. auto& typeOptions = mCompiler->mSystem->mTypeOptions[optionsIdx];
  9439. wantOptions.mOptLevel = (BfOptLevel)BfTypeOptions::Apply((int)wantOptions.mOptLevel, (int)typeOptions.mOptimizationLevel);
  9440. wantOptions.mSIMDSetting = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mSIMDSetting, typeOptions.mSIMDSetting);
  9441. wantOptions.mEmitDebugInfo = (BfSIMDSetting)BfTypeOptions::Apply((int)wantOptions.mEmitDebugInfo, typeOptions.mEmitDebugInfo);
  9442. }
  9443. }
  9444. }
  9445. }
  9446. if ((HasCompiledOutput()) && (wantOptions != moduleOptions) && (!mIsScratchModule))
  9447. {
  9448. auto lastCheckModule = this;
  9449. auto checkModule = this->mNextAltModule;
  9450. while (checkModule != NULL)
  9451. {
  9452. if (*checkModule->mModuleOptions == wantOptions)
  9453. {
  9454. declareModule = checkModule;
  9455. break;
  9456. }
  9457. lastCheckModule = checkModule;
  9458. checkModule = checkModule->mNextAltModule;
  9459. }
  9460. // Not found?
  9461. if (declareModule == this)
  9462. {
  9463. String specModuleName = mModuleName + "@@";
  9464. if (wantOptions.mOptLevel != moduleOptions.mOptLevel)
  9465. specModuleName += StrFormat("O%d", wantOptions.mOptLevel);
  9466. if (wantOptions.mSIMDSetting != moduleOptions.mSIMDSetting)
  9467. specModuleName += StrFormat("SIMD%d", wantOptions.mSIMDSetting);
  9468. declareModule = new BfModule(mContext, specModuleName);
  9469. declareModule->mProject = project;
  9470. declareModule->mModuleOptions = new BfModuleOptions();
  9471. *declareModule->mModuleOptions = wantOptions;
  9472. declareModule->mParentModule = lastCheckModule;
  9473. declareModule->Init();
  9474. lastCheckModule->mNextAltModule = declareModule;
  9475. }
  9476. }
  9477. }
  9478. declareModule->PrepareForIRWriting(typeInst);
  9479. return declareModule;
  9480. }
  9481. BfModuleMethodInstance BfModule::GetMethodInstance(BfTypeInstance* typeInst, BfMethodDef* methodDef, const BfTypeVector& methodGenericArguments, BfGetMethodInstanceFlags flags, BfTypeInstance* foreignType)
  9482. {
  9483. if (((flags & BfGetMethodInstanceFlag_ForceInline) != 0) && (mCompiler->mIsResolveOnly))
  9484. {
  9485. // Don't bother inlining for resolve-only
  9486. flags = (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline);
  9487. }
  9488. bool processNow = false;
  9489. bool keepInCurrentModule = false;
  9490. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsUnspecialized))
  9491. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_NoForceReification);
  9492. if (!typeInst->IsTypeMemberIncluded(methodDef->mDeclaringType))
  9493. {
  9494. return BfModuleMethodInstance();
  9495. }
  9496. if (methodDef->mIsLocalMethod)
  9497. {
  9498. auto rootMethodState = mCurMethodState->GetRootMethodState();
  9499. BfLocalMethod* localMethod;
  9500. if (rootMethodState->mLocalMethodCache.TryGetValue(methodDef->mName, &localMethod))
  9501. {
  9502. // Handle the def in the correct method state
  9503. return GetLocalMethodInstance(localMethod, methodGenericArguments);
  9504. }
  9505. BF_FATAL("Cannot find local method");
  9506. return BfModuleMethodInstance();
  9507. }
  9508. #ifdef _DEBUG
  9509. for (auto arg : methodGenericArguments)
  9510. BF_ASSERT(!arg->IsVar());
  9511. #endif
  9512. BF_ASSERT(methodDef->mMethodType != BfMethodType_Ignore);
  9513. // We need to do the 'mNeedsMethodProcessing' check because we want to do a proper initial "awaiting reference" population
  9514. // on the methods before we handle an on-demand situation. This also ensures that our type options are set before doing
  9515. // a FinishInit
  9516. if ((typeInst->IsIncomplete()) &&
  9517. (!typeInst->mResolvingVarField) && (!typeInst->mTypeFailed))
  9518. {
  9519. // For autocomplete, we still may not actually generate methods. This shouldn't matter, and on-demand works differently
  9520. // for resolve-only because we don't differentiate between reified/unreified there
  9521. PopulateType(typeInst, BfPopulateType_Full);
  9522. }
  9523. bool tryModuleMethodLookup = false;
  9524. BfModuleMethodInstance moduleMethodInst;
  9525. BfModule* instModule = typeInst->mModule;
  9526. if (keepInCurrentModule)
  9527. {
  9528. // Stay here
  9529. instModule = this;
  9530. }
  9531. if (this == mContext->mUnreifiedModule)
  9532. {
  9533. // Stay in this 'resolve only' module here
  9534. }
  9535. else if (flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass)
  9536. {
  9537. BF_ASSERT(this == mContext->mUnreifiedModule);
  9538. }
  9539. else if (flags & BfGetMethodInstanceFlag_ExplicitSpecializedModule)
  9540. {
  9541. BF_ASSERT(instModule == mParentModule);
  9542. }
  9543. else if (instModule != this)
  9544. {
  9545. if ((!mIsReified) && (instModule->mIsReified))
  9546. {
  9547. BF_ASSERT(!mCompiler->mIsResolveOnly);
  9548. // A resolve-only module is specializing a method from a type in a reified module,
  9549. // we need to take care that this doesn't cause anything new to become reified
  9550. return mContext->mUnreifiedModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ExplicitResolveOnlyPass), foreignType);
  9551. }
  9552. else
  9553. {
  9554. if ((mIsReified) && (!instModule->mIsReified))
  9555. {
  9556. if (!instModule->mReifyQueued)
  9557. {
  9558. BF_ASSERT((mCompiler->mCompileState != BfCompiler::CompileState_Unreified) && (mCompiler->mCompileState != BfCompiler::CompileState_VData));
  9559. BfLogSysM("Queueing ReifyModule: %p\n", instModule);
  9560. mContext->mReifyModuleWorkList.Add(instModule);
  9561. instModule->mReifyQueued = true;
  9562. }
  9563. // This ensures that the method will actually be created when it gets reified
  9564. BfMethodSpecializationRequest* specializationRequest = mContext->mMethodSpecializationWorkList.Alloc();
  9565. specializationRequest->mFromModule = typeInst->mModule;
  9566. specializationRequest->mFromModuleRevision = typeInst->mModule->mRevision;
  9567. specializationRequest->mMethodDef = methodDef;
  9568. specializationRequest->mMethodGenericArguments = methodGenericArguments;
  9569. specializationRequest->mType = typeInst;
  9570. specializationRequest->mFlags = flags;
  9571. }
  9572. auto defFlags = (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline);
  9573. // Not extern
  9574. // Create the instance in the proper module and then create a reference in this one
  9575. moduleMethodInst = instModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, defFlags, foreignType);
  9576. tryModuleMethodLookup = true;
  9577. if ((mIsReified) && (!moduleMethodInst.mMethodInstance->mIsReified))
  9578. {
  9579. CheckHotMethod(moduleMethodInst.mMethodInstance, "");
  9580. }
  9581. }
  9582. }
  9583. if (tryModuleMethodLookup)
  9584. return ReferenceExternalMethodInstance(moduleMethodInst.mMethodInstance, flags);
  9585. if (((flags & BfGetMethodInstanceFlag_ForceInline) != 0) && (!methodDef->mAlwaysInline))
  9586. {
  9587. auto moduleMethodInstance = GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags & ~BfGetMethodInstanceFlag_ForceInline), foreignType);
  9588. if (moduleMethodInstance)
  9589. return ReferenceExternalMethodInstance(moduleMethodInstance.mMethodInstance, flags);
  9590. return moduleMethodInst;
  9591. }
  9592. bool isReified = mIsReified /* || ((flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass) != 0)*/;
  9593. bool hadConcreteInterfaceGenericArgument = false;
  9594. if ((flags & BfGetMethodInstanceFlag_Unreified) != 0)
  9595. isReified = false;
  9596. if ((flags & BfGetMethodInstanceFlag_ExplicitResolveOnlyPass) != 0)
  9597. {
  9598. isReified = false;
  9599. }
  9600. BfTypeVector sanitizedMethodGenericArguments;
  9601. SizedArray<BfProject*, 4> projectList;
  9602. bool isUnspecializedPass = (flags & BfGetMethodInstanceFlag_UnspecializedPass) != 0;
  9603. if ((isUnspecializedPass) && (methodDef->mGenericParams.size() == 0))
  9604. isUnspecializedPass = false;
  9605. // 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
  9606. bool isExternalExtensionMethod = false;
  9607. if ((!typeInst->IsUnspecializedType()) && (!isUnspecializedPass))
  9608. {
  9609. if (((flags & BfGetMethodInstanceFlag_ForeignMethodDef) == 0) && (methodDef->mDeclaringType->mProject != typeInst->mTypeDef->mProject))
  9610. {
  9611. auto specProject = methodDef->mDeclaringType->mProject;
  9612. isExternalExtensionMethod = true;
  9613. if (typeInst->IsGenericTypeInstance())
  9614. {
  9615. auto genericTypeInst = (BfGenericTypeInstance*)typeInst;
  9616. if (genericTypeInst->mProjectsReferenced.empty())
  9617. genericTypeInst->GenerateProjectsReferenced();
  9618. if (genericTypeInst->mProjectsReferenced.Contains(specProject))
  9619. {
  9620. // This is a generic type where a generic param is already confined to the project in question
  9621. isExternalExtensionMethod = false;
  9622. }
  9623. }
  9624. if (isExternalExtensionMethod)
  9625. {
  9626. BF_ASSERT(typeInst->mTypeDef->mIsCombinedPartial);
  9627. projectList.push_back(methodDef->mDeclaringType->mProject);
  9628. }
  9629. }
  9630. }
  9631. if ((!isUnspecializedPass) && (methodGenericArguments.size() != 0))
  9632. {
  9633. int typeProjectsCounts = 0;
  9634. if (typeInst->IsGenericTypeInstance())
  9635. {
  9636. auto genericTypeInst = (BfGenericTypeInstance*)typeInst;
  9637. if (genericTypeInst->mProjectsReferenced.empty())
  9638. genericTypeInst->GenerateProjectsReferenced();
  9639. typeProjectsCounts = (int)genericTypeInst->mProjectsReferenced.size();
  9640. projectList.Insert(0, &genericTypeInst->mProjectsReferenced[0], genericTypeInst->mProjectsReferenced.size());
  9641. }
  9642. else
  9643. {
  9644. typeProjectsCounts = 1;
  9645. projectList.Insert(0, typeInst->mTypeDef->mProject);
  9646. }
  9647. isUnspecializedPass = true;
  9648. for (int genericArgIdx = 0; genericArgIdx < (int) methodGenericArguments.size(); genericArgIdx++)
  9649. {
  9650. auto genericArgType = methodGenericArguments[genericArgIdx];
  9651. //BF_ASSERT(!genericArgType->IsRef());
  9652. if (genericArgType->IsConcreteInterfaceType())
  9653. {
  9654. hadConcreteInterfaceGenericArgument = true;
  9655. auto concreteInterfaceType = (BfConcreteInterfaceType*)genericArgType;
  9656. genericArgType = concreteInterfaceType->mInterface;
  9657. }
  9658. if (genericArgType->IsGenericParam())
  9659. {
  9660. auto genericParam = (BfGenericParamType*) genericArgType;
  9661. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  9662. isUnspecializedPass = false;
  9663. }
  9664. else
  9665. {
  9666. BfTypeUtils::GetProjectList(genericArgType, &projectList, typeProjectsCounts);
  9667. isUnspecializedPass = false;
  9668. }
  9669. sanitizedMethodGenericArguments.push_back(genericArgType);
  9670. }
  9671. if ((int)projectList.size() > typeProjectsCounts)
  9672. {
  9673. // Just leave the new items
  9674. projectList.RemoveRange(0, typeProjectsCounts);
  9675. std::sort(projectList.begin(), projectList.end(), [](BfProject* lhs, BfProject*rhs)
  9676. {
  9677. return lhs->mName < rhs->mName;
  9678. });
  9679. }
  9680. else
  9681. {
  9682. projectList.Clear();
  9683. }
  9684. }
  9685. const BfTypeVector& lookupMethodGenericArguments = isUnspecializedPass ? BfTypeVector() : sanitizedMethodGenericArguments;
  9686. BfMethodInstanceGroup* methodInstGroup = NULL;
  9687. if ((flags & BfGetMethodInstanceFlag_ForeignMethodDef) != 0)
  9688. {
  9689. BF_ASSERT(!typeInst->IsInterface());
  9690. //for (auto& checkGroup : typeInst->mMethodInstanceGroups)
  9691. for (int methodIdx = (int)typeInst->mTypeDef->mMethods.size(); methodIdx < (int)typeInst->mMethodInstanceGroups.size(); methodIdx++)
  9692. {
  9693. auto& checkGroup = typeInst->mMethodInstanceGroups[methodIdx];
  9694. // if (checkGroup.mDefault == NULL)
  9695. // {
  9696. // // This should only be for when we explicitly add a spot so we can set mOnDemandKind
  9697. // BF_ASSERT(methodIdx == typeInst->mMethodInstanceGroups.size() - 1);
  9698. // methodInstGroup = &checkGroup;
  9699. // break;
  9700. // }
  9701. if ((checkGroup.mDefault != NULL) && (checkGroup.mDefault->mMethodDef == methodDef))
  9702. {
  9703. methodInstGroup = &checkGroup;
  9704. break;
  9705. }
  9706. }
  9707. if (methodInstGroup == NULL)
  9708. {
  9709. // Allocate a new entry
  9710. typeInst->mMethodInstanceGroups.Resize(typeInst->mMethodInstanceGroups.size() + 1);
  9711. methodInstGroup = &typeInst->mMethodInstanceGroups.back();
  9712. methodInstGroup->mMethodIdx = (int)typeInst->mMethodInstanceGroups.size() - 1;
  9713. methodInstGroup->mOwner = typeInst;
  9714. // if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet)
  9715. // methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  9716. if (mCompiler->mOptions.mCompileOnDemandKind == BfCompileOnDemandKind_AlwaysInclude)
  9717. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  9718. else
  9719. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingDecl;
  9720. }
  9721. }
  9722. else
  9723. {
  9724. methodInstGroup = &typeInst->mMethodInstanceGroups[methodDef->mIdx];
  9725. }
  9726. if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet)
  9727. {
  9728. BfLogSysM("Forcing BfMethodOnDemandKind_NotSet to BfMethodOnDemandKind_AlwaysInclude for Method:%s in Type:%p\n", methodDef->mName.c_str(), typeInst);
  9729. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  9730. }
  9731. BfIRFunction prevIRFunc;
  9732. bool doingRedeclare = false;
  9733. BfMethodInstance* methodInstance = NULL;
  9734. auto _SetReified = [&]()
  9735. {
  9736. methodInstance->mIsReified = true;
  9737. };
  9738. if (lookupMethodGenericArguments.size() == 0)
  9739. {
  9740. methodInstance = methodInstGroup->mDefault;
  9741. if ((methodInstance != NULL) && (isReified) && (!methodInstance->mIsReified))
  9742. {
  9743. MarkDerivedDirty(typeInst);
  9744. if (mIsScratchModule)
  9745. {
  9746. BfLogSysM("Marking scratch module method instance as reified: %p\n", methodInstance);
  9747. _SetReified();
  9748. CheckHotMethod(methodInstance, "");
  9749. }
  9750. else if ((flags & BfGetMethodInstanceFlag_NoForceReification) != 0)
  9751. {
  9752. // We don't need to force reification if we're in an unspecialized generic- we can wait for
  9753. // the specializations to handle that for us
  9754. return BfModuleMethodInstance(methodInstance);
  9755. }
  9756. else if (methodInstGroup->mOnDemandKind == BfMethodOnDemandKind_Referenced)
  9757. {
  9758. if (methodDef->mIsAbstract)
  9759. {
  9760. BfLogSysM("Reifying abstract unreified method instance: %p IRFunction:%d\n", methodInstance, methodInstance->mIRFunction.mId);
  9761. _SetReified();
  9762. }
  9763. else
  9764. {
  9765. BfLogSysM("Re-declaring processed but unreified method instance: %p IRFunction:%d\n", methodInstance, methodInstance->mIRFunction.mId);
  9766. methodInstGroup->mOnDemandKind = BfMethodOnDemandKind_NoDecl_AwaitingReference;
  9767. methodInstance->UndoDeclaration(!methodInstance->mIRFunction.IsFake());
  9768. doingRedeclare = true;
  9769. mOnDemandMethodCount++;
  9770. }
  9771. }
  9772. else
  9773. {
  9774. BfLogSysM("Marking unprocessed method instance as reified: %p\n", methodInstance);
  9775. // We haven't processed it yet
  9776. _SetReified();
  9777. CheckHotMethod(methodInstance, "");
  9778. if (methodInstance->mDeclModule == this)
  9779. {
  9780. if (methodInstance->mMethodProcessRequest != NULL)
  9781. {
  9782. // Disconnect method process request
  9783. BF_ASSERT(methodInstance->mMethodProcessRequest->mFromModule == this);
  9784. }
  9785. }
  9786. else
  9787. {
  9788. if (methodInstance->mMethodProcessRequest != NULL)
  9789. {
  9790. // Disconnect method process request
  9791. BF_ASSERT(methodInstance->mMethodProcessRequest->mFromModule == mContext->mUnreifiedModule);
  9792. methodInstance->mMethodProcessRequest->mMethodInstance = NULL;
  9793. methodInstance->mMethodProcessRequest = NULL;
  9794. }
  9795. if (methodInstance->mDeclModule == mContext->mUnreifiedModule)
  9796. {
  9797. // Add new request in proper module
  9798. methodInstance->mDeclModule = this;
  9799. }
  9800. else
  9801. {
  9802. if (methodInstance->mDeclModule == NULL)
  9803. {
  9804. //
  9805. }
  9806. else if (methodInstance->mDeclModule != this)
  9807. {
  9808. // Is from specialized module?
  9809. BF_ASSERT(methodInstance->mDeclModule->mParentModule == this);
  9810. }
  9811. }
  9812. if ((!methodInstance->mIRFunction) || (methodInstance->mIRFunction.IsFake()))
  9813. {
  9814. methodInstance->mIRFunction = BfIRFunction();
  9815. if (!mIsModuleMutable)
  9816. StartExtension();
  9817. if ((!mBfIRBuilder->mIgnoreWrites) && (methodInstance->mDeclModule != NULL))
  9818. {
  9819. StringT<128> mangledName;
  9820. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  9821. bool isIntrinsic = false;
  9822. SetupIRFunction(methodInstance, mangledName, false, &isIntrinsic);
  9823. BfLogSysM("Creating new IRFunction %d\n", methodInstance->mIRFunction.mId);
  9824. }
  9825. }
  9826. AddMethodToWorkList(methodInstance);
  9827. }
  9828. }
  9829. }
  9830. }
  9831. else
  9832. {
  9833. BF_ASSERT(lookupMethodGenericArguments.size() != 0);
  9834. if (methodInstGroup->mMethodSpecializationMap == NULL)
  9835. methodInstGroup->mMethodSpecializationMap = new BfMethodInstanceGroup::MapType();
  9836. BfMethodInstance** methodInstancePtr = NULL;
  9837. if (methodInstGroup->mMethodSpecializationMap->TryGetValue(lookupMethodGenericArguments, &methodInstancePtr))
  9838. {
  9839. methodInstance = *methodInstancePtr;
  9840. if ((isReified) && (!methodInstance->mIsReified))
  9841. {
  9842. MarkDerivedDirty(typeInst);
  9843. if (methodInstance->mHasBeenProcessed)
  9844. {
  9845. BfLogSysM("Deleting processed but unreified specialized method instance %p\n", methodInstance);
  9846. delete methodInstance;
  9847. methodInstGroup->mMethodSpecializationMap->Remove(lookupMethodGenericArguments);
  9848. methodInstance = NULL;
  9849. }
  9850. else if ((!methodInstance->mIRFunction) || (methodInstance->mIRFunction.IsFake()))
  9851. {
  9852. BfLogSysM("Deleting declared but uncreated specialized method instance %p\n", methodInstance);
  9853. delete methodInstance;
  9854. methodInstGroup->mMethodSpecializationMap->Remove(lookupMethodGenericArguments);
  9855. methodInstance = NULL;
  9856. }
  9857. else
  9858. {
  9859. BfLogSysM("Reifying declared but unreified method instance %p\n", methodInstance);
  9860. // We haven't processed it yet
  9861. _SetReified();
  9862. CheckHotMethod(methodInstance, "");
  9863. }
  9864. }
  9865. }
  9866. }
  9867. if ((methodInstance != NULL) && (!doingRedeclare))
  9868. {
  9869. if (methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference)
  9870. {
  9871. /*if ((!mCompiler->mIsResolveOnly) && (!isReified))
  9872. BF_ASSERT(!methodInstance->mIsReified);*/
  9873. if (methodInstance->mIsReified != isReified)
  9874. BfLogSysM("GetMethodInstance %p Decl_AwaitingReference setting reified to %d\n", methodInstance, isReified);
  9875. if ((!isReified) &&
  9876. ((methodInstance->mDeclModule == NULL) || (!methodInstance->mDeclModule->mIsModuleMutable)))
  9877. {
  9878. methodInstance->mDeclModule = mContext->mUnreifiedModule;
  9879. methodInstance->mIRFunction = BfIRFunction();
  9880. }
  9881. methodInstance->mIsReified = isReified;
  9882. if ((methodInstance->mHotMethod != NULL) && (!mCompiler->IsHotCompile()) && (isReified))
  9883. {
  9884. methodInstance->mHotMethod->mFlags = (BfHotDepDataFlags)(methodInstance->mHotMethod->mFlags | BfHotDepDataFlag_IsOriginalBuild);
  9885. }
  9886. if (!methodInstance->mMethodDef->mIsAbstract)
  9887. {
  9888. AddMethodToWorkList(methodInstance);
  9889. }
  9890. else
  9891. {
  9892. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Referenced;
  9893. }
  9894. }
  9895. if (mExtensionCount > 0)
  9896. {
  9897. if ((mIsModuleMutable) && (!methodInstance->mIRFunction) &&
  9898. ((projectList.IsEmpty() || ((flags & BfGetMethodInstanceFlag_ExplicitSpecializedModule) != 0))))
  9899. {
  9900. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, false);
  9901. if (mAwaitingInitFinish)
  9902. FinishInit();
  9903. // We need to refer to a function that was defined in a prior module
  9904. bool isInlined = (methodInstance->mAlwaysInline) || ((flags & BfGetMethodInstanceFlag_ForceInline) != 0);
  9905. methodInstance->mIRFunction = CreateFunctionFrom(methodInstance, false, isInlined);
  9906. BF_ASSERT((methodInstance->mDeclModule == this) || (methodInstance->mDeclModule == mContext->mUnreifiedModule) || (methodInstance->mDeclModule == NULL));
  9907. methodInstance->mDeclModule = this;
  9908. // Add this inlined def to ourselves
  9909. if ((methodInstance->mAlwaysInline) && (HasCompiledOutput()) && (!methodInstance->mIsUnspecialized))
  9910. {
  9911. mIncompleteMethodCount++;
  9912. BfInlineMethodRequest* inlineMethodRequest = mContext->mInlineMethodWorkList.Alloc();
  9913. inlineMethodRequest->mType = typeInst;
  9914. inlineMethodRequest->mFromModule = this;
  9915. inlineMethodRequest->mFunc = methodInstance->mIRFunction;
  9916. inlineMethodRequest->mFromModuleRevision = mRevision;
  9917. inlineMethodRequest->mMethodInstance = methodInstance;
  9918. BfLogSysM("mInlineMethodWorkList %p for method %p in module %p in GetMethodInstance\n", inlineMethodRequest, methodInstance, this);
  9919. BF_ASSERT(mIsModuleMutable);
  9920. }
  9921. }
  9922. }
  9923. if (mCompiler->IsSkippingExtraResolveChecks())
  9924. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  9925. else
  9926. {
  9927. if (methodInstance->mDeclModule != this)
  9928. return ReferenceExternalMethodInstance(methodInstance, flags);
  9929. if ((!methodInstance->mIRFunction) && (mIsModuleMutable) && (!mBfIRBuilder->mIgnoreWrites))
  9930. {
  9931. auto importKind = methodInstance->GetImportCallKind();
  9932. if (importKind != BfImportCallKind_None)
  9933. {
  9934. BfLogSysM("DllImportGlobalVar creating %p\n", methodInstance);
  9935. methodInstance->mIRFunction = mBfIRBuilder->GetFakeVal();
  9936. mFuncReferences[methodInstance] = CreateDllImportGlobalVar(methodInstance, true);;
  9937. }
  9938. }
  9939. return BfModuleMethodInstance(methodInstance);
  9940. }
  9941. }
  9942. if (!doingRedeclare)
  9943. {
  9944. BfModule* specModule = NULL;
  9945. if ((!keepInCurrentModule) && (projectList.size() > 0) && (!isUnspecializedPass) && (HasCompiledOutput()) && (!mIsScratchModule))
  9946. {
  9947. specModule = GetSpecializedMethodModule(projectList);
  9948. }
  9949. if ((specModule != NULL) && (specModule != this))
  9950. {
  9951. auto specMethodInstance = specModule->GetMethodInstance(typeInst, methodDef, methodGenericArguments, (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ExplicitSpecializedModule));
  9952. if (mAwaitingInitFinish)
  9953. return BfModuleMethodInstance(specMethodInstance.mMethodInstance, BfIRFunction());
  9954. return ReferenceExternalMethodInstance(specMethodInstance.mMethodInstance, flags);
  9955. }
  9956. if ((!isUnspecializedPass) && (methodGenericArguments.size() != 0) && (methodInstGroup->mDefault == NULL))
  9957. {
  9958. // We are attempting to specialize but we don't have the unspecialized method yet. Generate that first.
  9959. GetMethodInstance(typeInst, methodDef, BfTypeVector(), BfGetMethodInstanceFlag_UnspecializedPass);
  9960. }
  9961. }
  9962. if (methodInstance == NULL)
  9963. {
  9964. if (lookupMethodGenericArguments.size() == 0)
  9965. {
  9966. BF_ASSERT(methodInstGroup->mDefault == NULL);
  9967. methodInstance = new BfMethodInstance();
  9968. methodInstGroup->mDefault = methodInstance;
  9969. BfLogSysM("Created Default MethodInst: %p TypeInst: %p Group: %p\n", methodInstance, typeInst, methodInstGroup);
  9970. }
  9971. else
  9972. {
  9973. BfMethodInstance** methodInstancePtr = NULL;
  9974. bool added = methodInstGroup->mMethodSpecializationMap->TryAdd(lookupMethodGenericArguments, NULL, &methodInstancePtr);
  9975. BF_ASSERT(added);
  9976. methodInstance = new BfMethodInstance();
  9977. *methodInstancePtr = methodInstance;
  9978. BfLogSysM("Created Specialized MethodInst: %p TypeInst: %p\n", methodInstance, typeInst);
  9979. }
  9980. if ((prevIRFunc) && (!prevIRFunc.IsFake()))
  9981. methodInstance->mIRFunction = prevIRFunc; // Take it over
  9982. }
  9983. /*// 24 bits for typeid, 20 for method id, 20 for specialization index
  9984. methodInstance->mMethodId = ((int64)typeInst->mTypeId) + ((int64)methodInstGroup->mMethodIdx << 24);
  9985. if (methodInstGroup->mMethodSpecializationMap != NULL)
  9986. methodInstance->mMethodId += ((int64)methodInstGroup->mMethodSpecializationMap->size() << 44);*/
  9987. methodInstance->mMethodDef = methodDef;
  9988. methodInstance->mAlwaysInline = methodDef->mAlwaysInline;
  9989. methodInstance->mMethodInstanceGroup = methodInstGroup;
  9990. methodInstance->mIsReified = isReified;
  9991. SetupMethodIdHash(methodInstance);
  9992. if (hadConcreteInterfaceGenericArgument)
  9993. methodInstance->mIgnoreBody = true;
  9994. if ((flags & BfGetMethodInstanceFlag_ForeignMethodDef) != 0)
  9995. {
  9996. methodInstance->mIsForeignMethodDef = true;
  9997. BF_ASSERT(foreignType != NULL);
  9998. methodInstance->GetMethodInfoEx()->mForeignType = foreignType;
  9999. }
  10000. if ((typeInst->mTypeDef == mCompiler->mValueTypeTypeDef) && (methodDef->mName == BF_METHODNAME_EQUALS))
  10001. {
  10002. if (!lookupMethodGenericArguments.empty())
  10003. {
  10004. auto compareType = lookupMethodGenericArguments[0];
  10005. PopulateType(compareType, BfPopulateType_Data);
  10006. if (compareType->IsSplattable())
  10007. methodInstance->mAlwaysInline = true;
  10008. }
  10009. }
  10010. if (methodDef->mDeclaringType->mTypeDeclaration != typeInst->mTypeDef->mTypeDeclaration)
  10011. {
  10012. // With extensions we can have multiple definitions of the same method
  10013. //methodInstance->mMangleWithIdx = true;
  10014. }
  10015. BfModule* declareModule = GetOrCreateMethodModule(methodInstance);
  10016. BF_ASSERT(typeInst == methodInstance->GetOwner());
  10017. auto methodDeclaration = methodDef->GetMethodDeclaration();
  10018. if (isUnspecializedPass)
  10019. {
  10020. for (int genericParamIdx = 0; genericParamIdx < (int) methodDef->mGenericParams.size(); genericParamIdx++)
  10021. {
  10022. auto genericParamType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  10023. methodInstance->GetMethodInfoEx()->mMethodGenericArguments.Add(genericParamType);
  10024. }
  10025. }
  10026. else if ((methodDeclaration != NULL) && (methodDeclaration->mGenericParams != NULL))
  10027. {
  10028. if (!sanitizedMethodGenericArguments.IsEmpty())
  10029. methodInstance->GetMethodInfoEx()->mMethodGenericArguments = sanitizedMethodGenericArguments;
  10030. if (methodDef->mGenericParams.size() != sanitizedMethodGenericArguments.size())
  10031. {
  10032. Fail("Internal error");
  10033. BF_FATAL("Generic method argument counts mismatch");
  10034. return NULL;
  10035. }
  10036. for (auto genericArg : sanitizedMethodGenericArguments)
  10037. {
  10038. if (genericArg->IsPrimitiveType())
  10039. genericArg = GetWrappedStructType(genericArg);
  10040. AddDependency(genericArg, typeInst, BfDependencyMap::DependencyFlag_MethodGenericArg);
  10041. if (genericArg->IsMethodRef())
  10042. {
  10043. auto methodRefType = (BfMethodRefType*)genericArg;
  10044. //AddDependency(genericArg, typeInst, BfDependencyMap::DependencyFlag_);
  10045. }
  10046. }
  10047. }
  10048. // Generic constraints
  10049. for (int genericParamIdx = 0; genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  10050. {
  10051. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, genericParamIdx);
  10052. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  10053. }
  10054. for (int externConstraintIdx = 0; externConstraintIdx < (int)methodDef->mExternalConstraints.size(); externConstraintIdx++)
  10055. {
  10056. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, externConstraintIdx + (int)methodDef->mGenericParams.size());
  10057. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  10058. }
  10059. bool addToWorkList = !processNow;
  10060. if (mCompiler->GetAutoComplete() != NULL)
  10061. {
  10062. if (typeInst->IsSpecializedByAutoCompleteMethod())
  10063. addToWorkList = false;
  10064. }
  10065. BF_ASSERT(declareModule != NULL);
  10066. methodInstance->mDeclModule = declareModule;
  10067. if ((!methodInstance->mIsReified) && (mCompiler->mCompileState != BfCompiler::CompileState_Normal))
  10068. {
  10069. // We can be sure this method won't become reified later. Normally we can "go either way" with an unreified method
  10070. // of a reified module -
  10071. // If we declare it in the reified module then we can switch it to "reified" before actual processing without any extra work,
  10072. // BUT if we don't reify it then we have to remove the body after processing.
  10073. // 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
  10074. // the proper reified module.
  10075. declareModule = mContext->mUnreifiedModule;
  10076. }
  10077. else if ((!declareModule->mIsModuleMutable) && (!mCompiler->mIsResolveOnly))
  10078. {
  10079. BF_ASSERT(!methodInstance->mIsReified);
  10080. declareModule = mContext->mUnreifiedModule;
  10081. }
  10082. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  10083. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(declareModule->mCurTypeInstance, typeInst);
  10084. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  10085. declareModule->DoMethodDeclaration(methodDef->GetMethodDeclaration(), false, addToWorkList);
  10086. if (processNow)
  10087. {
  10088. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, NULL);
  10089. ProcessMethod(methodInstance);
  10090. }
  10091. if (mCompiler->IsSkippingExtraResolveChecks())
  10092. return BfModuleMethodInstance(methodInstance, BfIRFunction());
  10093. return BfModuleMethodInstance(methodInstance);
  10094. }
  10095. BfModuleMethodInstance BfModule::GetMethodInstance(BfMethodInstance* methodInstance, BfGetMethodInstanceFlags flags)
  10096. {
  10097. BF_ASSERT((methodInstance->mMethodInfoEx == NULL) || (methodInstance->mMethodInfoEx->mGenericParams.IsEmpty()));
  10098. if (methodInstance->mIsForeignMethodDef)
  10099. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ForeignMethodDef);
  10100. return GetMethodInstance(methodInstance->GetOwner(), methodInstance->mMethodDef, BfTypeVector(), flags);
  10101. }
  10102. BfMethodInstance* BfModule::GetOuterMethodInstance(BfMethodInstance* methodInstance)
  10103. {
  10104. if (!methodInstance->mMethodDef->mIsLocalMethod)
  10105. return NULL;
  10106. auto outerLocal = methodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod->mOuterLocalMethod;
  10107. if (outerLocal == NULL)
  10108. return NULL;
  10109. BfTypeVector genericArgs;
  10110. for (int i = 0; i < (int)outerLocal->mMethodDef->mGenericParams.size(); i++)
  10111. genericArgs.Add(methodInstance->mMethodInfoEx->mMethodGenericArguments[i]);
  10112. return GetLocalMethodInstance(outerLocal, genericArgs).mMethodInstance;
  10113. }
  10114. void BfModule::SetupMethodIdHash(BfMethodInstance* methodInstance)
  10115. {
  10116. HashContext hashCtx;
  10117. std::function<void(BfMethodInstance*)> _MixinMethodInstance = [&](BfMethodInstance* methodInstance)
  10118. {
  10119. hashCtx.Mixin(methodInstance->GetOwner()->mTypeId);
  10120. hashCtx.Mixin(methodInstance->mMethodDef->mIdx);
  10121. if (methodInstance->GetNumGenericArguments() != 0)
  10122. {
  10123. hashCtx.Mixin((int32)methodInstance->mMethodInfoEx->mMethodGenericArguments.size());
  10124. for (auto methodGenericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  10125. hashCtx.Mixin(methodGenericArg->mTypeId);
  10126. }
  10127. };
  10128. _MixinMethodInstance(methodInstance);
  10129. if (methodInstance->mMethodDef->mIsLocalMethod)
  10130. {
  10131. auto outmostMethodInstance = mCurMethodState->GetRootMethodState()->mMethodInstance;
  10132. BF_ASSERT((outmostMethodInstance->mIdHash != 0) || (outmostMethodInstance->mIsAutocompleteMethod));
  10133. hashCtx.Mixin(outmostMethodInstance->mIdHash);
  10134. }
  10135. methodInstance->mIdHash = (int64)hashCtx.Finish64();
  10136. }
  10137. BfIRValue BfModule::GetInterfaceSlotNum(BfTypeInstance* ifaceType)
  10138. {
  10139. BfIRValue globalValue;
  10140. BfIRValue* globalValuePtr = NULL;
  10141. if (mInterfaceSlotRefs.TryGetValue(ifaceType, &globalValuePtr))
  10142. {
  10143. globalValue = *globalValuePtr;
  10144. }
  10145. if (!globalValue)
  10146. {
  10147. // This is necessary to reify the interface type
  10148. PopulateType(ifaceType);
  10149. StringT<128> slotVarName;
  10150. BfMangler::MangleStaticFieldName(slotVarName, mCompiler->GetMangleKind(), ifaceType, "sBfSlotOfs");
  10151. BfType* intType = GetPrimitiveType(BfTypeCode_Int32);
  10152. BfIRValue value;
  10153. if ((mCompiler->mHotState != NULL) && (ifaceType->mSlotNum >= 0))
  10154. {
  10155. /*// If this interface already existed before this hot compile but we never indirectly called any of its methods
  10156. // then the sBfSlotOfs could have gotten its symbol stripped, so actually define it here.
  10157. int virtSlotIdx = ifaceType->mSlotNum + 1;
  10158. value = GetConstValue32(virtSlotIdx);*/
  10159. mCompiler->mHotState->mSlotDefineTypeIds.Add(ifaceType->mTypeId);
  10160. ifaceType->mDirty = true; // Makes sure we create interface in vdata
  10161. }
  10162. globalValue = mBfIRBuilder->CreateGlobalVariable(mBfIRBuilder->MapType(intType), true, BfIRLinkageType_External, value, slotVarName);
  10163. mInterfaceSlotRefs[ifaceType] = globalValue;
  10164. }
  10165. return mBfIRBuilder->CreateLoad(globalValue/*, "slotOfs"*/);
  10166. }
  10167. void BfModule::HadSlotCountDependency()
  10168. {
  10169. if (mCompiler->mIsResolveOnly)
  10170. return;
  10171. BF_ASSERT(!mBfIRBuilder->mIgnoreWrites);
  10172. BF_ASSERT((mUsedSlotCount == BF_MAX(mCompiler->mMaxInterfaceSlots, 0)) || (mUsedSlotCount == -1));
  10173. mUsedSlotCount = BF_MAX(mCompiler->mMaxInterfaceSlots, 0);
  10174. }
  10175. BfTypedValue BfModule::ReferenceStaticField(BfFieldInstance* fieldInstance)
  10176. {
  10177. if (mIsScratchModule)
  10178. {
  10179. // Just fake it for the extern and unspecialized modules
  10180. auto ptrType = CreatePointerType(fieldInstance->GetResolvedType());
  10181. return BfTypedValue(GetDefaultValue(ptrType), fieldInstance->GetResolvedType(), true);
  10182. }
  10183. BfIRValue globalValue;
  10184. auto fieldDef = fieldInstance->GetFieldDef();
  10185. if ((fieldDef->mIsConst) && (!fieldDef->mIsExtern))
  10186. {
  10187. if (fieldInstance->mConstIdx != -1)
  10188. {
  10189. auto constant = fieldInstance->mOwner->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  10190. return BfTypedValue(ConstantToCurrent(constant, fieldInstance->mOwner->mConstHolder, fieldInstance->GetResolvedType()), fieldInstance->GetResolvedType());
  10191. }
  10192. else
  10193. {
  10194. return GetDefaultTypedValue(fieldInstance->GetResolvedType());
  10195. }
  10196. }
  10197. BfIRValue* globalValuePtr = NULL;
  10198. if (mStaticFieldRefs.TryGetValue(fieldInstance, &globalValuePtr))
  10199. {
  10200. globalValue = *globalValuePtr;
  10201. BF_ASSERT(globalValue);
  10202. }
  10203. else
  10204. {
  10205. StringT<128> staticVarName;
  10206. BfMangler::Mangle(staticVarName, mCompiler->GetMangleKind(), fieldInstance);
  10207. auto typeType = fieldInstance->GetResolvedType();
  10208. if ((fieldDef->mIsExtern) && (fieldDef->mIsConst) && (typeType->IsPointer()))
  10209. {
  10210. typeType = typeType->GetUnderlyingType();
  10211. }
  10212. PopulateType(typeType);
  10213. if ((typeType != NULL) && (!typeType->IsValuelessType()))
  10214. {
  10215. globalValue = mBfIRBuilder->CreateGlobalVariable(
  10216. mBfIRBuilder->MapType(typeType),
  10217. false,
  10218. BfIRLinkageType_External,
  10219. BfIRValue(),
  10220. staticVarName,
  10221. IsThreadLocal(fieldInstance));
  10222. if (!mBfIRBuilder->mIgnoreWrites)
  10223. {
  10224. // Only store this if we actually did the creation
  10225. BF_ASSERT(globalValue);
  10226. mStaticFieldRefs[fieldInstance] = globalValue;
  10227. }
  10228. BfLogSysM("Mod:%p Type:%p ReferenceStaticField %p -> %p\n", this, fieldInstance->mOwner, fieldInstance, globalValue);
  10229. }
  10230. }
  10231. auto type = fieldInstance->GetResolvedType();
  10232. if (type->IsValuelessType())
  10233. return BfTypedValue(globalValue, type);
  10234. return BfTypedValue(globalValue, type, !fieldDef->mIsConst);
  10235. }
  10236. BfTypedValue BfModule::GetThis()
  10237. {
  10238. auto useMethodState = mCurMethodState;
  10239. while ((useMethodState != NULL) && (useMethodState->mClosureState != NULL) && (useMethodState->mClosureState->mCapturing))
  10240. {
  10241. useMethodState = useMethodState->mPrevMethodState;
  10242. }
  10243. if (useMethodState != NULL)
  10244. {
  10245. // Fake a 'this' for var field resolution
  10246. if (useMethodState->mTempKind == BfMethodState::TempKind_NonStatic)
  10247. {
  10248. auto thisType = mCurTypeInstance;
  10249. if (thisType->IsValueType())
  10250. return BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInstPtr(thisType)), thisType, BfTypedValueKind_ThisAddr);
  10251. else
  10252. return BfTypedValue(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapTypeInst(thisType)), thisType, BfTypedValueKind_ThisValue);
  10253. }
  10254. else if (useMethodState->mTempKind == BfMethodState::TempKind_Static)
  10255. {
  10256. return BfTypedValue();
  10257. }
  10258. }
  10259. else
  10260. {
  10261. //TODO: Do we allow useMethodState to be NULL anymore?
  10262. return BfTypedValue();
  10263. }
  10264. // if (useMethodState->HasNonStaticMixin())
  10265. // {
  10266. // auto checkMethodState = useMethodState;
  10267. // while (checkMethodState != NULL)
  10268. // {
  10269. // for (int localIdx = (int)checkMethodState->mLocals.size() - 1; localIdx >= 0; localIdx--)
  10270. // {
  10271. // auto varDecl = checkMethodState->mLocals[localIdx];
  10272. // if (varDecl->mName == "this")
  10273. // {
  10274. // varDecl->mReadFromId = useMethodState->GetRootMethodState()->mCurAccessId++;
  10275. // if (varDecl->mIsSplat)
  10276. // {
  10277. // return BfTypedValue(varDecl->mValue, varDecl->mResolvedType, BfTypedValueKind_ThisSplatHead);
  10278. // }
  10279. // else if ((varDecl->mResolvedType->IsValueType()) && (varDecl->mAddr))
  10280. // {
  10281. // return BfTypedValue(varDecl->mAddr, varDecl->mResolvedType, BfTypedValueKind_ThisAddr);
  10282. // }
  10283. // return BfTypedValue(varDecl->mValue, varDecl->mResolvedType, varDecl->mResolvedType->IsValueType() ? BfTypedValueKind_ThisAddr : BfTypedValueKind_ThisValue);
  10284. // }
  10285. // }
  10286. //
  10287. // checkMethodState = checkMethodState->mPrevMethodState;
  10288. // }
  10289. // }
  10290. // Check mixin state for 'this'
  10291. {
  10292. auto checkMethodState = useMethodState;
  10293. while (checkMethodState != NULL)
  10294. {
  10295. if (checkMethodState->mMixinState != NULL)
  10296. {
  10297. BfTypedValue thisValue = checkMethodState->mMixinState->mTarget;
  10298. if (thisValue)
  10299. {
  10300. checkMethodState->mMixinState->mLastTargetAccessId = useMethodState->GetRootMethodState()->mCurAccessId++;
  10301. if (!thisValue.mType->IsValueType())
  10302. thisValue = LoadValue(thisValue);
  10303. return thisValue;
  10304. }
  10305. }
  10306. checkMethodState = checkMethodState->mPrevMethodState;
  10307. }
  10308. }
  10309. auto curMethodInstance = mCurMethodInstance;
  10310. if (useMethodState->mMethodInstance != NULL)
  10311. curMethodInstance = useMethodState->mMethodInstance;
  10312. if ((curMethodInstance == NULL) /*|| (!mCurMethodInstance->mIRFunction)*/ || (curMethodInstance->mMethodDef->mIsStatic))
  10313. {
  10314. if ((useMethodState->mClosureState != NULL) && (!useMethodState->mClosureState->mConstLocals.empty()))
  10315. {
  10316. auto& constLocal = useMethodState->mClosureState->mConstLocals[0];
  10317. if (constLocal.mIsThis)
  10318. {
  10319. BF_ASSERT(constLocal.mResolvedType->IsValuelessType());
  10320. return BfTypedValue(mBfIRBuilder->GetFakeVal(), constLocal.mResolvedType);
  10321. }
  10322. }
  10323. return BfTypedValue();
  10324. }
  10325. bool preferValue = !IsTargetingBeefBackend();
  10326. if (useMethodState->mLocals.IsEmpty())
  10327. {
  10328. // 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
  10329. BF_ASSERT(useMethodState->mPrevMethodState != NULL);
  10330. return BfTypedValue();
  10331. }
  10332. auto thisLocal = useMethodState->mLocals[0];
  10333. BF_ASSERT(thisLocal->mIsThis);
  10334. BfIRValue thisValue;
  10335. if ((preferValue) || (!thisLocal->mAddr) /*|| (thisLocal->mIsSplat)*/)
  10336. thisValue = thisLocal->mValue;
  10337. else if ((thisLocal->mIsSplat) || (thisLocal->mIsLowered))
  10338. thisValue = thisLocal->mAddr;
  10339. else
  10340. thisValue = mBfIRBuilder->CreateLoad(thisLocal->mAddr);
  10341. useMethodState->mLocals[0]->mReadFromId = useMethodState->GetRootMethodState()->mCurAccessId++;
  10342. if (useMethodState->mClosureState != NULL)
  10343. {
  10344. auto closureTypeInst = useMethodState->mClosureState->mClosureType;
  10345. if (closureTypeInst != NULL)
  10346. {
  10347. if (closureTypeInst->mFieldInstances.size() > 0)
  10348. {
  10349. auto& field = closureTypeInst->mFieldInstances[0];
  10350. auto fieldDef = field.GetFieldDef();
  10351. if (fieldDef->mName == "__this")
  10352. {
  10353. if (mCurMethodState->mClosureState->mCapturing)
  10354. mCurMethodState->mClosureState->mReferencedOuterClosureMembers.Add(&field);
  10355. // This is a captured 'this'
  10356. BfTypedValue result = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(thisValue, 0, field.mDataIdx), field.mResolvedType, true);
  10357. if (field.mResolvedType->IsRef())
  10358. {
  10359. auto refType = (BfRefType*)field.mResolvedType;
  10360. auto underlyingType = refType->GetUnderlyingType();
  10361. result = BfTypedValue(mBfIRBuilder->CreateLoad(result.mValue), underlyingType, true);
  10362. }
  10363. if (field.mResolvedType->IsObject())
  10364. {
  10365. result = LoadValue(result);
  10366. result.mKind = BfTypedValueKind_ThisValue;
  10367. }
  10368. else
  10369. {
  10370. if (fieldDef->mIsReadOnly)
  10371. result.mKind = BfTypedValueKind_ReadOnlyThisAddr;
  10372. else
  10373. result.mKind = BfTypedValueKind_ThisAddr;
  10374. }
  10375. return result;
  10376. }
  10377. }
  10378. return BfTypedValue();
  10379. }
  10380. if (useMethodState->mClosureState->mCapturing)
  10381. {
  10382. auto thisType = useMethodState->mLocals[0]->mResolvedType;
  10383. if (thisType->IsValueType())
  10384. return BfTypedValue(CreateAlloca(thisType), thisType, BfTypedValueKind_ThisAddr);
  10385. else
  10386. return BfTypedValue(GetDefaultValue(thisType), thisType, BfTypedValueKind_ThisValue);
  10387. }
  10388. }
  10389. auto localDef = useMethodState->mLocals[0];
  10390. auto curMethodOwner = mCurMethodInstance->mMethodInstanceGroup->mOwner;
  10391. if ((curMethodOwner->IsStruct()) || (curMethodOwner->IsTypedPrimitive()))
  10392. {
  10393. if ((localDef->mResolvedType->IsTypedPrimitive()) && (!mCurMethodInstance->mMethodDef->mIsMutating))
  10394. {
  10395. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, BfTypedValueKind_ReadOnlyThisValue);
  10396. }
  10397. if (localDef->mIsSplat)
  10398. {
  10399. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, BfTypedValueKind_ThisSplatHead);
  10400. }
  10401. return BfTypedValue(thisValue, useMethodState->mLocals[0]->mResolvedType, localDef->mIsReadOnly ? BfTypedValueKind_ReadOnlyThisAddr : BfTypedValueKind_ThisAddr);
  10402. }
  10403. return BfTypedValue(thisValue, mCurMethodInstance->mMethodInstanceGroup->mOwner, BfTypedValueKind_ThisValue);
  10404. }
  10405. BfLocalVariable* BfModule::GetThisVariable()
  10406. {
  10407. if (mCurMethodState == NULL)
  10408. return NULL;
  10409. auto methodState = mCurMethodState->GetNonCaptureState();
  10410. if ((methodState->mLocals.size() > 0) && (methodState->mLocals[0]->mIsThis))
  10411. return methodState->mLocals[0];
  10412. return NULL;
  10413. }
  10414. bool BfModule::IsInGeneric()
  10415. {
  10416. return (mCurMethodInstance->GetNumGenericArguments() != 0) || (mCurTypeInstance->IsGenericTypeInstance());
  10417. }
  10418. bool BfModule::IsInSpecializedGeneric()
  10419. {
  10420. if ((mCurMethodInstance == NULL) || (mCurMethodInstance->mIsUnspecialized))
  10421. return false;
  10422. return (mCurMethodInstance->GetNumGenericArguments() != 0) || (mCurTypeInstance->IsGenericTypeInstance());
  10423. }
  10424. bool BfModule::IsInSpecializedSection()
  10425. {
  10426. return IsInSpecializedGeneric() ||
  10427. ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL));
  10428. }
  10429. bool BfModule::IsInUnspecializedGeneric()
  10430. {
  10431. if (mCurMethodInstance != NULL)
  10432. return mCurMethodInstance->mIsUnspecialized;
  10433. return false;
  10434. }
  10435. //////////////////////////////////////////////////////////////////////////
  10436. BfIRValue BfModule::AllocLocalVariable(BfType* type, const StringImpl& name, bool doLifetimeEnd)
  10437. {
  10438. //if ((type->IsValuelessType()) || (type->IsMethodRef()))
  10439. if (type->IsValuelessType())
  10440. return mBfIRBuilder->GetFakeVal();
  10441. auto allocaInst = CreateAlloca(type, doLifetimeEnd, name.c_str());
  10442. if ((!doLifetimeEnd) && (WantsLifetimes()))
  10443. {
  10444. auto lifetimeStart = mBfIRBuilder->CreateLifetimeStart(allocaInst);
  10445. mBfIRBuilder->ClearDebugLocation(lifetimeStart);
  10446. }
  10447. bool initLocalVariables = mCompiler->mOptions.mInitLocalVariables;
  10448. auto typeOptions = GetTypeOptions();
  10449. if (typeOptions != NULL)
  10450. initLocalVariables = BfTypeOptions::Apply(initLocalVariables, typeOptions->mInitLocalVariables);
  10451. // Local variable inits are implicitly handled in the Beef Backend
  10452. if ((initLocalVariables) && (!IsTargetingBeefBackend()))
  10453. {
  10454. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  10455. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  10456. auto storeInst = mBfIRBuilder->CreateAlignedStore(GetDefaultValue(type), allocaInst, type->mAlign);
  10457. mBfIRBuilder->ClearDebugLocation(storeInst);
  10458. mBfIRBuilder->SetInsertPoint(prevBlock);
  10459. }
  10460. return allocaInst;
  10461. }
  10462. void BfModule::DoAddLocalVariable(BfLocalVariable* localVar)
  10463. {
  10464. localVar->mLocalVarIdx = (int)mCurMethodState->mLocals.size();
  10465. mCurMethodState->mLocals.push_back(localVar);
  10466. BfLocalVarEntry* localVarEntryPtr;
  10467. if (!mCurMethodState->mLocalVarSet.TryAdd(BfLocalVarEntry(localVar), &localVarEntryPtr))
  10468. {
  10469. localVar->mShadowedLocal = localVarEntryPtr->mLocalVar;
  10470. localVarEntryPtr->mLocalVar = localVar;
  10471. }
  10472. }
  10473. BfLocalVariable* BfModule::AddLocalVariableDef(BfLocalVariable* localVarDef, bool addDebugInfo, bool doAliasValue, BfIRValue declareBefore, BfIRInitType initType)
  10474. {
  10475. if ((localVarDef->mValue) && (!localVarDef->mAddr) && (IsTargetingBeefBackend()))
  10476. {
  10477. if ((!localVarDef->mValue.IsConst()) && (!localVarDef->mValue.IsArg()) && (!localVarDef->mValue.IsFake()))
  10478. {
  10479. mBfIRBuilder->CreateValueScopeRetain(localVarDef->mValue);
  10480. mCurMethodState->mCurScope->mHadScopeValueRetain = true;
  10481. }
  10482. }
  10483. if ((addDebugInfo) && (mBfIRBuilder->DbgHasInfo()) &&
  10484. ((mCurMethodInstance == NULL) || (!mCurMethodInstance->mIsUnspecialized)) &&
  10485. (mHasFullDebugInfo) &&
  10486. ((mCurMethodState->mClosureState == NULL) || (!mCurMethodState->mClosureState->mCapturing)))
  10487. {
  10488. auto varType = localVarDef->mResolvedType;
  10489. if (localVarDef->mResolvedType->IsValuelessType())
  10490. {
  10491. }
  10492. else
  10493. {
  10494. bool isByAddr = false;
  10495. auto diValue = localVarDef->mValue;
  10496. if (localVarDef->mConstValue)
  10497. diValue = localVarDef->mConstValue;
  10498. else if (localVarDef->mAddr)
  10499. {
  10500. diValue = localVarDef->mAddr;
  10501. isByAddr = true;
  10502. }
  10503. auto diType = mBfIRBuilder->DbgGetType(localVarDef->mResolvedType);
  10504. bool didConstToMem = false;
  10505. bool isConstant = false;
  10506. if ((localVarDef->mIsReadOnly) && (localVarDef->mAddr))
  10507. diType = mBfIRBuilder->DbgCreateConstType(diType);
  10508. else if (localVarDef->mConstValue)
  10509. {
  10510. auto constant = mBfIRBuilder->GetConstant(localVarDef->mConstValue);
  10511. isConstant =
  10512. (constant->mConstType < BfConstType_GlobalVar) ||
  10513. (constant->mConstType == BfConstType_AggZero) ||
  10514. (constant->mConstType == BfConstType_Array);
  10515. if (isConstant)
  10516. {
  10517. if (localVarDef->mResolvedType->IsComposite())
  10518. {
  10519. mBfIRBuilder->PopulateType(localVarDef->mResolvedType);
  10520. auto constMem = mBfIRBuilder->ConstToMemory(localVarDef->mConstValue);
  10521. if (IsTargetingBeefBackend())
  10522. {
  10523. diValue = mBfIRBuilder->CreateAliasValue(constMem);
  10524. didConstToMem = true;
  10525. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  10526. }
  10527. else
  10528. {
  10529. isByAddr = true;
  10530. mBfIRBuilder->SaveDebugLocation();
  10531. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  10532. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRInitBlock);
  10533. mBfIRBuilder->ClearDebugLocation();
  10534. auto ptrType = CreatePointerType(localVarDef->mResolvedType);
  10535. auto addrVal = CreateAlloca(ptrType);
  10536. mBfIRBuilder->CreateStore(constMem, addrVal);
  10537. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  10538. diValue = addrVal;
  10539. didConstToMem = true;
  10540. mBfIRBuilder->SetInsertPoint(prevBlock);
  10541. mBfIRBuilder->RestoreDebugLocation();
  10542. }
  10543. }
  10544. if (mCompiler->mOptions.IsCodeView())
  10545. diType = mBfIRBuilder->DbgCreateConstType(diType);
  10546. }
  10547. }
  10548. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  10549. localVarDef->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, initType);
  10550. localVarDef->mDbgVarInst = diVariable;
  10551. if (mBfIRBuilder->HasDebugLocation())
  10552. {
  10553. if ((isConstant) && (!didConstToMem))
  10554. {
  10555. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(localVarDef->mConstValue, diVariable);
  10556. }
  10557. else
  10558. {
  10559. if ((IsTargetingBeefBackend()) && (doAliasValue))
  10560. {
  10561. diValue = mBfIRBuilder->CreateAliasValue(diValue);
  10562. mCurMethodState->mCurScope->mDeferredLifetimeEnds.Add(diValue);
  10563. }
  10564. if (isByAddr)
  10565. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertDeclare(diValue, diVariable, declareBefore);
  10566. else if (diValue)
  10567. {
  10568. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(diValue, diVariable);
  10569. }
  10570. else if (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU) // DWARF chokes on this:
  10571. localVarDef->mDbgDeclareInst = mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  10572. }
  10573. }
  10574. }
  10575. }
  10576. localVarDef->mDeclBlock = mBfIRBuilder->GetInsertBlock();
  10577. DoAddLocalVariable(localVarDef);
  10578. auto rootMethodState = mCurMethodState->GetRootMethodState();
  10579. if (localVarDef->mLocalVarId == -1)
  10580. {
  10581. BF_ASSERT(rootMethodState->mCurLocalVarId >= 0);
  10582. localVarDef->mLocalVarId = rootMethodState->mCurLocalVarId++;
  10583. }
  10584. if ((localVarDef->mNameNode != NULL) && (mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  10585. mCompiler->mResolvePassData->mAutoComplete->CheckLocalDef(localVarDef->mNameNode, localVarDef);
  10586. if ((localVarDef->mNameNode != NULL) && (mCurMethodInstance != NULL))
  10587. {
  10588. bool isClosureProcessing = (mCurMethodState->mClosureState != NULL) && (!mCurMethodState->mClosureState->mCapturing);
  10589. if ((!isClosureProcessing) && (mCompiler->mResolvePassData != NULL) && (localVarDef->mNameNode != NULL))
  10590. mCompiler->mResolvePassData->HandleLocalReference(localVarDef->mNameNode, rootMethodState->mMethodInstance->GetOwner()->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, localVarDef->mLocalVarId);
  10591. }
  10592. return localVarDef;
  10593. }
  10594. void BfModule::CreateDIRetVal()
  10595. {
  10596. if (!WantsDebugInfo())
  10597. return;
  10598. /*if (!mCurMethodState->mRetVal)
  10599. {
  10600. if (mCurMethodInstance->mMethodDef->mName != "Ziggle")
  10601. return;
  10602. }*/
  10603. if ((mCurMethodState->mRetVal) || (mCurMethodState->mRetValAddr))
  10604. {
  10605. BfType* dbgType = mCurMethodInstance->mReturnType;
  10606. BfIRValue dbgValue = mCurMethodState->mRetVal.mValue;
  10607. if (mCurMethodInstance->HasStructRet())
  10608. {
  10609. BF_ASSERT(mCurMethodState->mRetValAddr);
  10610. dbgType = CreatePointerType(dbgType);
  10611. dbgValue = mCurMethodState->mRetValAddr;
  10612. }
  10613. else
  10614. {
  10615. BF_ASSERT(!mCurMethodState->mRetValAddr);
  10616. }
  10617. mCurMethodState->mDIRetVal = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  10618. "__return", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(dbgType));
  10619. auto declareCall = mBfIRBuilder->DbgInsertDeclare(dbgValue, mCurMethodState->mDIRetVal);
  10620. }
  10621. }
  10622. void BfModule::CheckVariableDef(BfLocalVariable* variableDef)
  10623. {
  10624. BfLocalVarEntry* localVarEntryPtr = NULL;
  10625. if ((mCurMethodState != NULL) && (mCurMethodState->mLocalVarSet.TryGet(BfLocalVarEntry(variableDef), &localVarEntryPtr)))
  10626. {
  10627. auto checkLocal = localVarEntryPtr->mLocalVar;
  10628. if ((checkLocal->mLocalVarIdx >= mCurMethodState->GetLocalStartIdx()) && (!checkLocal->mIsShadow))
  10629. {
  10630. BfError* error;
  10631. if (checkLocal->mIsImplicitParam)
  10632. return; // Ignore 'redefinition'
  10633. if (checkLocal->IsParam())
  10634. error = Fail(StrFormat("A parameter named '%s' has already been declared.", variableDef->mName.c_str()), variableDef->mNameNode);
  10635. else if (checkLocal->mLocalVarIdx < mCurMethodState->mCurScope->mLocalVarStart)
  10636. error = Fail(StrFormat("A variable named '%s' has already been declared in this parent's scope.", variableDef->mName.c_str()), variableDef->mNameNode);
  10637. else
  10638. error = Fail(StrFormat("A variable named '%s' has already been declared in this scope.", variableDef->mName.c_str()), variableDef->mNameNode);
  10639. if ((checkLocal->mNameNode != NULL) && (error != NULL))
  10640. mCompiler->mPassInstance->MoreInfo("Previous declaration", checkLocal->mNameNode);
  10641. return;
  10642. }
  10643. }
  10644. }
  10645. BfScopeData* BfModule::FindScope(BfAstNode* scopeName, BfMixinState* fromMixinState, bool allowAcrossDeferredBlock)
  10646. {
  10647. bool inMixinDecl = (mCurMethodInstance != NULL) && (mCurMethodInstance->IsMixin());
  10648. if (auto tokenNode = BfNodeDynCast<BfTokenNode>(scopeName))
  10649. {
  10650. if (tokenNode->GetToken() == BfToken_Colon)
  10651. {
  10652. if ((!allowAcrossDeferredBlock) && (mCurMethodState->mInDeferredBlock))
  10653. {
  10654. Fail("Cannot access method scope across deferred block boundary", scopeName);
  10655. return NULL;
  10656. }
  10657. return &mCurMethodState->mHeadScope;
  10658. }
  10659. else if (tokenNode->GetToken() == BfToken_Mixin)
  10660. {
  10661. if (fromMixinState == NULL)
  10662. {
  10663. if (mCurMethodInstance->mMethodDef->mMethodType != BfMethodType_Mixin)
  10664. Fail("'mixin' scope specifier can only be used within a mixin declaration", scopeName);
  10665. return mCurMethodState->mCurScope;
  10666. }
  10667. fromMixinState->mUsedInvocationScope = true;
  10668. return fromMixinState->mTargetScope;
  10669. }
  10670. else if (tokenNode->GetToken() == BfToken_New)
  10671. return NULL;
  10672. }
  10673. if (auto identifier = BfNodeDynCast<BfIdentifierNode>(scopeName))
  10674. {
  10675. auto findLabel = scopeName->ToString();
  10676. bool crossedDeferredBlock = false;
  10677. auto checkScope = mCurMethodState->mCurScope;
  10678. while (checkScope != NULL)
  10679. {
  10680. if (checkScope->mIsDeferredBlock)
  10681. crossedDeferredBlock = true;
  10682. if (checkScope->mLabel == findLabel)
  10683. {
  10684. if ((crossedDeferredBlock) && (!allowAcrossDeferredBlock))
  10685. {
  10686. Fail(StrFormat("Cannot access scope '%s' across deferred block boundary", findLabel.c_str()), scopeName);
  10687. return NULL;
  10688. }
  10689. return checkScope;
  10690. }
  10691. checkScope = checkScope->mPrevScope;
  10692. }
  10693. if (!inMixinDecl)
  10694. Fail(StrFormat("Unable to locate label '%s'", findLabel.c_str()), scopeName);
  10695. }
  10696. if (auto scopeNode = BfNodeDynCast<BfScopeNode>(scopeName))
  10697. {
  10698. return FindScope(scopeNode->mTargetNode, allowAcrossDeferredBlock);
  10699. }
  10700. return mCurMethodState->mCurScope;
  10701. }
  10702. BfScopeData* BfModule::FindScope(BfAstNode* scopeName, bool allowAcrossDeferredBlock)
  10703. {
  10704. return FindScope(scopeName, mCurMethodState->mMixinState, allowAcrossDeferredBlock);
  10705. }
  10706. BfBreakData* BfModule::FindBreakData(BfAstNode* scopeName)
  10707. {
  10708. auto scopeData = FindScope(scopeName, false);
  10709. if (scopeData == NULL)
  10710. return NULL;
  10711. int scopeDepth = scopeData->GetDepth();
  10712. // Find the first break data that is at or below the depth of our requested scope
  10713. auto breakData = mCurMethodState->mBreakData;
  10714. while ((breakData != NULL) && (scopeDepth < breakData->mScope->GetDepth()))
  10715. {
  10716. if (breakData->mScope->mIsConditional)
  10717. return NULL;
  10718. breakData = breakData->mPrevBreakData;
  10719. }
  10720. return breakData;
  10721. }
  10722. void BfModule::EmitLifetimeEnds(BfScopeData* scopeData)
  10723. {
  10724. // LLVM is stricter about the placement of these (ie: they can't occur after a 'ret')
  10725. if (!IsTargetingBeefBackend())
  10726. return;
  10727. for (auto lifetimeEnd : scopeData->mDeferredLifetimeEnds)
  10728. {
  10729. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  10730. }
  10731. }
  10732. void BfModule::ClearLifetimeEnds()
  10733. {
  10734. auto scopeData = mCurMethodState->mCurScope;
  10735. while (scopeData != NULL)
  10736. {
  10737. scopeData->mDeferredLifetimeEnds.Clear();
  10738. scopeData = scopeData->mPrevScope;
  10739. }
  10740. }
  10741. bool BfModule::WantsDebugInfo()
  10742. {
  10743. if ((mCurMethodInstance != NULL) &&
  10744. ((mCurMethodInstance->mIsUnspecialized) || (mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)))
  10745. return false;
  10746. return (mBfIRBuilder->DbgHasInfo()) && (mHasFullDebugInfo) &&
  10747. ((mCurMethodState == NULL) || (mCurMethodState->mClosureState == NULL) || (!mCurMethodState->mClosureState->mCapturing));
  10748. }
  10749. BfTypeOptions* BfModule::GetTypeOptions()
  10750. {
  10751. if ((mCurMethodState != NULL) && (mCurMethodState->mMethodTypeOptions != NULL))
  10752. return mCurMethodState->mMethodTypeOptions;
  10753. return mSystem->GetTypeOptions(mCurTypeInstance->mTypeOptionsIdx);
  10754. }
  10755. bool BfModule::HasDeferredScopeCalls(BfScopeData* scope)
  10756. {
  10757. BfScopeData* checkScope = mCurMethodState->mCurScope;
  10758. while (checkScope != NULL)
  10759. {
  10760. if ((!checkScope->mDeferredCallEntries.IsEmpty()) || (!checkScope->mDeferredLifetimeEnds.empty()))
  10761. return true;
  10762. if (checkScope == scope)
  10763. break;
  10764. checkScope = checkScope->mPrevScope;
  10765. }
  10766. return false;
  10767. }
  10768. void BfModule::EmitDeferredScopeCalls(bool useSrcPositions, BfScopeData* scopeData, BfIRBlock doneBlock)
  10769. {
  10770. // Is there anything we need to do here?
  10771. if (mBfIRBuilder->mIgnoreWrites)
  10772. {
  10773. // Just visit deferred blocks
  10774. BfScopeData* checkScope = mCurMethodState->mCurScope;
  10775. while (checkScope != NULL)
  10776. {
  10777. BfDeferredCallEntry* deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  10778. while (deferredCallEntry != NULL)
  10779. {
  10780. if (deferredCallEntry->mDeferredBlock != NULL)
  10781. {
  10782. VisitEmbeddedStatement(deferredCallEntry->mDeferredBlock, NULL, BfEmbeddedStatementFlags_IsDeferredBlock);
  10783. }
  10784. deferredCallEntry = deferredCallEntry->mNext;
  10785. }
  10786. if (checkScope == scopeData)
  10787. break;
  10788. checkScope = checkScope->mPrevScope;
  10789. }
  10790. return;
  10791. }
  10792. // Why did we want to do SetIllegalSrcPos here?
  10793. // Don't we always want to step onto these instances?
  10794. // Find a case where we don't and perhaps only do it there.
  10795. // The downside was that 'EmitEnsureInstructionAt' on the end of block statements causes
  10796. // a (seemingly) unneeded NOP when we do SetIllegalSrcPos
  10797. //SetIllegalSrcPos();
  10798. bool setSrcPos = false;
  10799. bool wantsNop = true;
  10800. BfAstNode* deferCloseNode = NULL;
  10801. if (mCurMethodState->mInPostReturn)
  10802. {
  10803. // These won't get used, they are post-return
  10804. return;
  10805. }
  10806. SizedArray<BfIRValue, 8> deferredLifetimeEnds;
  10807. BfScopeData* scopeJumpBlock = NULL;
  10808. bool hadExtraDeferredLifetimeEnds = false;
  10809. auto _FlushLifetimeEnds = [&]()
  10810. {
  10811. for (auto lifetimeEnd : deferredLifetimeEnds)
  10812. {
  10813. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  10814. mBfIRBuilder->ClearDebugLocation_Last();
  10815. }
  10816. deferredLifetimeEnds.clear();
  10817. };
  10818. BfScopeData* checkScope = mCurMethodState->mCurScope;
  10819. while (checkScope != NULL)
  10820. {
  10821. if (checkScope->mCloseNode != NULL)
  10822. deferCloseNode = checkScope->mCloseNode;
  10823. if (doneBlock)
  10824. {
  10825. // Try to find a match where we've already emitted these calls and then jumped to the correct block
  10826. for (auto& checkHandler : checkScope->mDeferredHandlers)
  10827. {
  10828. if (checkHandler.mDoneBlock == doneBlock)
  10829. {
  10830. scopeJumpBlock = checkScope;
  10831. mBfIRBuilder->CreateBr(checkHandler.mHandlerBlock);
  10832. mBfIRBuilder->ClearDebugLocation_Last();
  10833. _FlushLifetimeEnds();
  10834. break;
  10835. }
  10836. }
  10837. if (scopeJumpBlock != NULL)
  10838. break;
  10839. }
  10840. bool hasWork = (checkScope->mSavedStack) || (checkScope->mDeferredCallEntries.mHead != NULL);
  10841. if (checkScope != scopeData) // Only emit a block for deferred lifetimes if we're going back beyond this entry
  10842. hasWork |= (!deferredLifetimeEnds.IsEmpty());
  10843. if (hasWork)
  10844. {
  10845. SetAndRestoreValue<BfScopeData*> prevScope(mCurMethodState->mCurScope, checkScope);
  10846. if (deferCloseNode != NULL)
  10847. {
  10848. UpdateSrcPos(deferCloseNode);
  10849. }
  10850. if (doneBlock)
  10851. {
  10852. bool crossingMixin = mCurMethodState->mCurScope->mMixinDepth != checkScope->mMixinDepth;
  10853. String blockName = "deferredCalls";
  10854. //blockName += StrFormat("_%d", mBfIRBuilder->mBlockCount);
  10855. BfDeferredHandler deferredHandler;
  10856. if ((!crossingMixin) && (deferredLifetimeEnds.IsEmpty()))
  10857. {
  10858. mBfIRBuilder->SaveDebugLocation();
  10859. mBfIRBuilder->ClearDebugLocation();
  10860. deferredHandler.mHandlerBlock = mBfIRBuilder->MaybeChainNewBlock(blockName);
  10861. mBfIRBuilder->RestoreDebugLocation();
  10862. }
  10863. else
  10864. {
  10865. // Definitely chain
  10866. deferredHandler.mHandlerBlock = mBfIRBuilder->CreateBlock(blockName);
  10867. mBfIRBuilder->CreateBr(deferredHandler.mHandlerBlock);
  10868. mBfIRBuilder->ClearDebugLocation_Last();
  10869. _FlushLifetimeEnds();
  10870. mBfIRBuilder->AddBlock(deferredHandler.mHandlerBlock);
  10871. mBfIRBuilder->SetInsertPoint(deferredHandler.mHandlerBlock);
  10872. }
  10873. deferredHandler.mDoneBlock = doneBlock;
  10874. if (!mBfIRBuilder->mIgnoreWrites)
  10875. checkScope->mDeferredHandlers.push_back(deferredHandler);
  10876. if (checkScope == &mCurMethodState->mHeadScope)
  10877. {
  10878. if (!mCurMethodState->mDIRetVal)
  10879. {
  10880. // 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
  10881. // be scoped to the physical method
  10882. /*if (deferCloseNode != NULL)
  10883. {
  10884. UpdateSrcPos(deferCloseNode);
  10885. }*/
  10886. CreateDIRetVal();
  10887. }
  10888. }
  10889. if (checkScope != mCurMethodState->mTailScope)
  10890. {
  10891. if (deferredHandler.mHandlerBlock.IsFake())
  10892. {
  10893. BF_ASSERT(mBfIRBuilder->mIgnoreWrites);
  10894. }
  10895. if (!mBfIRBuilder->mIgnoreWrites)
  10896. checkScope->mAtEndBlocks.push_back(deferredHandler.mHandlerBlock);
  10897. }
  10898. }
  10899. std::unordered_set<BfDeferredCallEntry*> handledSet;
  10900. BfDeferredCallEntry* deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  10901. while (deferredCallEntry != NULL)
  10902. {
  10903. BfDeferredCallEmitState deferredCallEmitState;
  10904. deferredCallEmitState.mCloseNode = deferCloseNode;
  10905. SetAndRestoreValue<BfDeferredCallEmitState*> prevDeferredCallEmitState(mCurMethodState->mDeferredCallEmitState, &deferredCallEmitState);
  10906. SetAndRestoreValue<bool> prevIgnoredWrites(mBfIRBuilder->mIgnoreWrites, deferredCallEntry->mIgnored);
  10907. if (deferCloseNode != NULL)
  10908. {
  10909. UpdateSrcPos(deferCloseNode);
  10910. }
  10911. if (wantsNop)
  10912. EmitEnsureInstructionAt();
  10913. wantsNop = false;
  10914. if (deferredCallEntry->mDeferredBlock != NULL)
  10915. {
  10916. auto itr = handledSet.insert(deferredCallEntry);
  10917. if (!itr.second)
  10918. {
  10919. // Already handled, can happen if we defer again within the block
  10920. deferredCallEntry = deferredCallEntry->mNext;
  10921. continue;
  10922. }
  10923. auto prevHead = checkScope->mDeferredCallEntries.mHead;
  10924. EmitDeferredCall(*deferredCallEntry);
  10925. if (prevHead != checkScope->mDeferredCallEntries.mHead)
  10926. {
  10927. // The list changed, start over and ignore anything we've already handled
  10928. deferredCallEntry = checkScope->mDeferredCallEntries.mHead;
  10929. }
  10930. else
  10931. deferredCallEntry = deferredCallEntry->mNext;
  10932. }
  10933. else
  10934. {
  10935. EmitDeferredCall(*deferredCallEntry);
  10936. deferredCallEntry = deferredCallEntry->mNext;
  10937. }
  10938. }
  10939. if (checkScope->mSavedStack)
  10940. {
  10941. checkScope->mSavedStackUses.Add(mBfIRBuilder->CreateStackRestore(checkScope->mSavedStack));
  10942. if (mCurMethodState->mDynStackRevIdx)
  10943. {
  10944. auto curValue = mBfIRBuilder->CreateLoad(mCurMethodState->mDynStackRevIdx);
  10945. auto newValue = mBfIRBuilder->CreateAdd(curValue, mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  10946. mBfIRBuilder->CreateStore(newValue, mCurMethodState->mDynStackRevIdx);
  10947. }
  10948. }
  10949. }
  10950. if (!checkScope->mIsScopeHead)
  10951. {
  10952. // We manually emit function-level lifetime ends after the 'ret' in ProcessMethod
  10953. if (!IsTargetingBeefBackend())
  10954. {
  10955. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  10956. {
  10957. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  10958. }
  10959. }
  10960. else
  10961. {
  10962. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  10963. {
  10964. deferredLifetimeEnds.Add(lifetimeEnd);
  10965. }
  10966. }
  10967. }
  10968. if (checkScope == scopeData)
  10969. break;
  10970. checkScope = checkScope->mPrevScope;
  10971. }
  10972. if ((doneBlock) && (scopeJumpBlock == NULL))
  10973. {
  10974. mBfIRBuilder->CreateBr(doneBlock);
  10975. mBfIRBuilder->ClearDebugLocation_Last();
  10976. }
  10977. // Keeping CreateLifetimeEnds until the end messes up when we chain to old mDeferredHandlers that
  10978. // may have been created when other scope lifetimes were available
  10979. _FlushLifetimeEnds();
  10980. // Emit lifetimeEnds after the branch for Beef
  10981. /*if (IsTargetingBeefBackend())
  10982. {
  10983. bool needsEnsureInst = (!doneBlock) && (scopeJumpBlock == NULL);
  10984. BfScopeData* checkScope = mCurMethodState->mCurScope;
  10985. while (checkScope != NULL)
  10986. {
  10987. if (checkScope == scopeJumpBlock)
  10988. break;
  10989. if (!checkScope->mIsScopeHead)
  10990. {
  10991. for (auto lifetimeEnd : checkScope->mDeferredLifetimeEnds)
  10992. {
  10993. if (needsEnsureInst)
  10994. {
  10995. needsEnsureInst = false;
  10996. }
  10997. mBfIRBuilder->CreateLifetimeEnd(lifetimeEnd);
  10998. }
  10999. }
  11000. if (checkScope == scopeData)
  11001. break;
  11002. checkScope = checkScope->mPrevScope;
  11003. }
  11004. }*/
  11005. }
  11006. void BfModule::MarkScopeLeft(BfScopeData* scopeData)
  11007. {
  11008. if (mCurMethodState->mDeferredLocalAssignData != NULL)
  11009. {
  11010. auto deferredLocalAssignData = mCurMethodState->mDeferredLocalAssignData;
  11011. while (deferredLocalAssignData != NULL)
  11012. {
  11013. if ((deferredLocalAssignData->mScopeData == NULL) || (deferredLocalAssignData->mScopeData->mScopeDepth < scopeData->mScopeDepth))
  11014. break;
  11015. if ((deferredLocalAssignData->mScopeData != NULL) && (deferredLocalAssignData->mScopeData->mScopeDepth == scopeData->mScopeDepth))
  11016. deferredLocalAssignData->mIsUnconditional = false;
  11017. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  11018. }
  11019. }
  11020. //for (int localIdx = scopeData->mLocalVarStart; localIdx < (int)mCurMethodState->mLocals.size(); localIdx++)
  11021. // We mark all unassigned variables as assigned now, for avoiding "may be unassigned" usage cases like:
  11022. // int b;
  11023. // if (cond) return;
  11024. // else b = 1;
  11025. // Use(b);
  11026. for (int localIdx = 0; localIdx < (int)mCurMethodState->mLocals.size(); localIdx++)
  11027. {
  11028. auto localDef = mCurMethodState->mLocals[localIdx];
  11029. if ((!localDef->mIsAssigned) && (!localDef->IsParam()))
  11030. mCurMethodState->LocalDefined(localDef);
  11031. }
  11032. }
  11033. void BfModule::CreateReturn(BfIRValue val)
  11034. {
  11035. if (mCurMethodInstance->mReturnType->IsComposite())
  11036. {
  11037. // Store to sret
  11038. BF_ASSERT(val);
  11039. mBfIRBuilder->CreateStore(val, mBfIRBuilder->GetArgument(0));
  11040. mBfIRBuilder->CreateRetVoid();
  11041. }
  11042. else
  11043. {
  11044. if (mCurMethodInstance->mReturnType->IsValuelessType())
  11045. {
  11046. mBfIRBuilder->CreateRetVoid();
  11047. }
  11048. else
  11049. {
  11050. BF_ASSERT(val);
  11051. mBfIRBuilder->CreateRet(val);
  11052. }
  11053. }
  11054. }
  11055. void BfModule::EmitReturn(BfIRValue val)
  11056. {
  11057. if (mCurMethodState->mIRExitBlock)
  11058. {
  11059. if (!mCurMethodInstance->mReturnType->IsValuelessType())
  11060. {
  11061. if (val) // We allow for val to be empty if we know we've already written the value to mRetVal
  11062. {
  11063. BfIRValue retVal = mCurMethodState->mRetVal.mValue;
  11064. if (!mCurMethodState->mRetVal)
  11065. retVal = mBfIRBuilder->CreateLoad(mCurMethodState->mRetValAddr);
  11066. mBfIRBuilder->CreateStore(val, retVal);
  11067. }
  11068. }
  11069. EmitDeferredScopeCalls(true, NULL, mCurMethodState->mIRExitBlock);
  11070. }
  11071. else
  11072. {
  11073. EmitDeferredScopeCalls(false, NULL);
  11074. if (mCurMethodInstance->mReturnType->IsValuelessType())
  11075. mBfIRBuilder->CreateRetVoid();
  11076. else
  11077. mBfIRBuilder->CreateRet(val);
  11078. }
  11079. mCurMethodState->SetHadReturn(true);
  11080. mCurMethodState->mLeftBlockUncond = true;
  11081. }
  11082. void BfModule::EmitDefaultReturn()
  11083. {
  11084. if (mCurMethodState->mInDeferredBlock)
  11085. return;
  11086. if (mCurMethodState->mIRExitBlock)
  11087. {
  11088. EmitDeferredScopeCalls(true, NULL, mCurMethodState->mIRExitBlock);
  11089. }
  11090. else
  11091. {
  11092. if (mCurMethodInstance->mReturnType->IsVoid())
  11093. mBfIRBuilder->CreateRetVoid();
  11094. else
  11095. mBfIRBuilder->CreateRet(GetDefaultValue(mCurMethodInstance->mReturnType));
  11096. }
  11097. mCurMethodState->SetHadReturn(true);
  11098. mCurMethodState->mLeftBlockUncond = true;
  11099. }
  11100. void BfModule::AssertErrorState()
  11101. {
  11102. if (mIgnoreErrors)
  11103. return;
  11104. if (mHadBuildError)
  11105. return;
  11106. if (mCurTypeInstance != NULL)
  11107. {
  11108. if (mCurTypeInstance->IsUnspecializedTypeVariation())
  11109. return;
  11110. }
  11111. if (mCurMethodInstance != NULL)
  11112. {
  11113. if (mCurMethodInstance->mIsUnspecializedVariation)
  11114. return;
  11115. }
  11116. // We want the module to be marked as failed even if it's just an error in the parser
  11117. if (mCurMethodInstance != NULL)
  11118. mCurMethodInstance->mHasFailed = true;
  11119. mHadBuildError = true;
  11120. // We check for either the parsing to have failed (possibly on a previous run), or for the current instance to have failed
  11121. if (mCurTypeInstance != NULL)
  11122. {
  11123. if (mCurTypeInstance->mTypeFailed)
  11124. return;
  11125. if (mCurTypeInstance->mTypeDef->mSource->mParsingFailed)
  11126. return;
  11127. }
  11128. if (mCurMethodInstance != NULL)
  11129. {
  11130. if ((mCurMethodInstance->mMethodDef->mDeclaringType != NULL) && (mCurMethodInstance->mMethodDef->mDeclaringType->mSource->mParsingFailed))
  11131. return;
  11132. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL) && (mCurMethodState->mMixinState->mMixinMethodInstance->mMethodDef->mDeclaringType->mSource->mParsingFailed))
  11133. return;
  11134. }
  11135. BF_ASSERT(mCompiler->mPassInstance->HasFailed());
  11136. }
  11137. void BfModule::AssertParseErrorState()
  11138. {
  11139. if (mCompiler->mRevision == 1)
  11140. AssertErrorState();
  11141. }
  11142. BfType* BfModule::GetDelegateReturnType(BfType* delegateType)
  11143. {
  11144. BF_ASSERT(delegateType->IsDelegate());
  11145. auto typeInst = delegateType->ToTypeInstance();
  11146. PopulateType(typeInst, BfPopulateType_DataAndMethods);
  11147. BfMethodInstance* invokeMethodInstance = GetRawMethodInstanceAtIdx(typeInst->ToTypeInstance(), 0, "Invoke");
  11148. return invokeMethodInstance->mReturnType;
  11149. }
  11150. BfMethodInstance* BfModule::GetDelegateInvokeMethod(BfTypeInstance* typeInstance)
  11151. {
  11152. return GetRawMethodInstanceAtIdx(typeInstance, 0, "Invoke");
  11153. }
  11154. void BfModule::CreateDelegateInvokeMethod()
  11155. {
  11156. // Clear out debug loc - otherwise we'll single step onto the delegate type declaration
  11157. //mBfIRBuilder->ClearDebugLocation();
  11158. SetIllegalSrcPos();
  11159. auto typeInstance = mCurTypeInstance;
  11160. auto memberFuncType = mBfIRBuilder->MapMethod(mCurMethodInstance);
  11161. SizedArray<BfIRType, 4> staticParamTypes;
  11162. SizedArray<BfIRValue, 4> staticFuncArgs;
  11163. SizedArray<BfIRValue, 4> memberFuncArgs;
  11164. auto multicastDelegateType = typeInstance->mBaseType;
  11165. if (multicastDelegateType->mFieldInstances.size() != 2)
  11166. {
  11167. AssertErrorState();
  11168. return;
  11169. }
  11170. auto multicastDelegate = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapType(multicastDelegateType));
  11171. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 2); // Load 'delegate.mTarget'
  11172. auto fieldVal = mBfIRBuilder->CreateLoad(fieldPtr);
  11173. BfExprEvaluator exprEvaluator(this);
  11174. SizedArray<BfIRType, 8> origParamTypes;
  11175. BfIRType origReturnType;
  11176. mCurMethodInstance->GetIRFunctionInfo(this, origReturnType, origParamTypes);
  11177. if (mCurMethodInstance->mReturnType->IsValueType())
  11178. mBfIRBuilder->PopulateType(mCurMethodInstance->mReturnType, BfIRPopulateType_Full);
  11179. int thisIdx = 0;
  11180. if (mCurMethodInstance->HasStructRet())
  11181. {
  11182. thisIdx = 1;
  11183. staticFuncArgs.push_back(mBfIRBuilder->GetArgument(0));
  11184. memberFuncArgs.push_back(mBfIRBuilder->GetArgument(0));
  11185. }
  11186. memberFuncArgs.push_back(BfIRValue()); // Push 'target'
  11187. mCurMethodInstance->GetIRFunctionInfo(this, origReturnType, staticParamTypes, true);
  11188. for (int i = 1; i < (int)mCurMethodState->mLocals.size(); i++)
  11189. {
  11190. BfTypedValue localVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[i], true);
  11191. exprEvaluator.PushArg(localVal, staticFuncArgs);
  11192. exprEvaluator.PushArg(localVal, memberFuncArgs);
  11193. }
  11194. auto staticFunc = mBfIRBuilder->CreateFunctionType(origReturnType, staticParamTypes, false);
  11195. auto staticFuncPtr = mBfIRBuilder->GetPointerTo(staticFunc);
  11196. auto staticFuncPtrPtr = mBfIRBuilder->GetPointerTo(staticFuncPtr);
  11197. auto trueBB = mBfIRBuilder->CreateBlock("if.then", true);
  11198. auto falseBB = mBfIRBuilder->CreateBlock("if.else");
  11199. auto doneBB = mBfIRBuilder->CreateBlock("done");
  11200. auto checkTargetNull = mBfIRBuilder->CreateIsNotNull(fieldVal);
  11201. mBfIRBuilder->CreateCondBr(checkTargetNull, trueBB, falseBB);
  11202. BfIRValue nonStaticResult;
  11203. BfIRValue staticResult;
  11204. auto callingConv = GetCallingConvention(mCurTypeInstance, mCurMethodInstance->mMethodDef);
  11205. /// Non-static invocation
  11206. {
  11207. auto memberFuncPtr = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapMethod(mCurMethodInstance));
  11208. auto memberFuncPtrPtr = mBfIRBuilder->GetPointerTo(memberFuncPtr);
  11209. mBfIRBuilder->SetInsertPoint(trueBB);
  11210. memberFuncArgs[thisIdx] = mBfIRBuilder->CreateBitCast(fieldVal, mBfIRBuilder->MapType(mCurTypeInstance));
  11211. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 1); // Load 'delegate.mFuncPtr'
  11212. auto funcPtrPtr = mBfIRBuilder->CreateBitCast(fieldPtr, memberFuncPtrPtr);
  11213. auto funcPtr = mBfIRBuilder->CreateLoad(funcPtrPtr);
  11214. nonStaticResult = mBfIRBuilder->CreateCall(funcPtr, memberFuncArgs);
  11215. if (callingConv != BfIRCallingConv_CDecl)
  11216. mBfIRBuilder->SetCallCallingConv(nonStaticResult, callingConv);
  11217. mCurMethodState->SetHadReturn(false);
  11218. mCurMethodState->mLeftBlockUncond = false;
  11219. mCurMethodState->mLeftBlockCond = false;
  11220. mBfIRBuilder->CreateBr(doneBB);
  11221. }
  11222. // Static invocation
  11223. {
  11224. mBfIRBuilder->AddBlock(falseBB);
  11225. mBfIRBuilder->SetInsertPoint(falseBB);
  11226. auto fieldPtr = mBfIRBuilder->CreateInBoundsGEP(multicastDelegate, 0, 1); // Load 'delegate.mFuncPtr'
  11227. auto funcPtrPtr = mBfIRBuilder->CreateBitCast(fieldPtr, staticFuncPtrPtr);
  11228. auto funcPtr = mBfIRBuilder->CreateLoad(funcPtrPtr);
  11229. staticResult = mBfIRBuilder->CreateCall(funcPtr, staticFuncArgs);
  11230. if (callingConv == BfIRCallingConv_ThisCall)
  11231. callingConv = BfIRCallingConv_CDecl;
  11232. if (callingConv != BfIRCallingConv_CDecl)
  11233. mBfIRBuilder->SetCallCallingConv(staticResult, callingConv);
  11234. // if (!mSystem->IsCompatibleCallingConvention(BfCallingConvention_Unspecified, mCurMethodInstance->mMethodDef->mCallingConvention))
  11235. // {
  11236. // if (mCurMethodInstance->mMethodDef->mCallingConvention == BfCallingConvention_Stdcall)
  11237. //
  11238. // }
  11239. mCurMethodState->SetHadReturn(false);
  11240. mCurMethodState->mLeftBlockUncond = false;
  11241. mCurMethodState->mLeftBlockCond = false;
  11242. mBfIRBuilder->CreateBr(doneBB);
  11243. }
  11244. mBfIRBuilder->AddBlock(doneBB);
  11245. mBfIRBuilder->SetInsertPoint(doneBB);
  11246. if ((mCurMethodInstance->mReturnType->IsValuelessType()) || (mCurMethodInstance->HasStructRet()))
  11247. {
  11248. mBfIRBuilder->CreateRetVoid();
  11249. }
  11250. else
  11251. {
  11252. auto phi = mBfIRBuilder->CreatePhi(mBfIRBuilder->MapType(mCurMethodInstance->mReturnType), 2);
  11253. mBfIRBuilder->AddPhiIncoming(phi, nonStaticResult, trueBB);
  11254. mBfIRBuilder->AddPhiIncoming(phi, staticResult, falseBB);
  11255. mBfIRBuilder->CreateRet(phi);
  11256. }
  11257. }
  11258. // "Interested" here means every method for a normal compile, and just the method the cursor is on for autocompletion
  11259. bool BfModule::IsInterestedInMethod(BfTypeInstance* typeInstance, BfMethodDef* methodDef)
  11260. {
  11261. auto typeDef = typeInstance->mTypeDef;
  11262. auto methodDeclaration = methodDef->mMethodDeclaration;
  11263. if (!mCompiler->mIsResolveOnly)
  11264. return true;
  11265. if (typeInstance->IsGenericTypeInstance())
  11266. {
  11267. // We only really want to process the unspecialized type for autocompletion
  11268. if ((!typeInstance->IsUnspecializedType()) || (typeInstance->IsUnspecializedTypeVariation()))
  11269. return false;
  11270. }
  11271. BfAstNode* checkNode = methodDeclaration;
  11272. if (methodDeclaration == NULL)
  11273. checkNode = methodDef->mBody;
  11274. if ((mCompiler->mResolvePassData->mParser != NULL) && (typeDef->mTypeDeclaration->IsFromParser(mCompiler->mResolvePassData->mParser)))
  11275. {
  11276. if (mCompiler->mResolvePassData->mAutoComplete == NULL)
  11277. return true;
  11278. }
  11279. return false;
  11280. }
  11281. void BfModule::CalcAppendAlign(BfMethodInstance* methodInst)
  11282. {
  11283. methodInst->mAppendAllocAlign = 1;
  11284. }
  11285. BfTypedValue BfModule::TryConstCalcAppend(BfMethodInstance* methodInst, SizedArrayImpl<BfIRValue>& args)
  11286. {
  11287. BP_ZONE("BfModule::TryConstCalcAppend");
  11288. if (mCompiler->mIsResolveOnly)
  11289. return BfTypedValue();
  11290. // We want to regenerate all ctor calls when the method internals change
  11291. {
  11292. auto checkTypeInst = methodInst->GetOwner();
  11293. while (checkTypeInst->mTypeDef->mHasAppendCtor)
  11294. {
  11295. AddDependency(checkTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_InlinedCall);
  11296. checkTypeInst = GetBaseType(checkTypeInst);
  11297. }
  11298. }
  11299. if (!methodInst->mMayBeConst)
  11300. return BfTypedValue();
  11301. // Do we need to iterate in order to resolve mAppendAllocAlign?
  11302. bool isFirstRun = methodInst->mAppendAllocAlign < 0;
  11303. bool wasAllConst = true;
  11304. int argIdx = 0;
  11305. int paramIdx = 0;
  11306. while (true)
  11307. {
  11308. if (argIdx >= (int)args.size())
  11309. break;
  11310. auto paramType = methodInst->GetParamType(paramIdx);
  11311. PopulateType(paramType);
  11312. int argCount = 0;
  11313. if (!paramType->IsValuelessType())
  11314. {
  11315. if (methodInst->GetParamIsSplat(paramIdx))
  11316. argCount = paramType->GetSplatCount();
  11317. else
  11318. argCount = 1;
  11319. for (int argOfs = 0; argOfs < argCount; argOfs++)
  11320. {
  11321. auto arg = args[argIdx + argOfs];
  11322. if (!arg.IsConst())
  11323. {
  11324. wasAllConst = false;
  11325. if (!isFirstRun)
  11326. {
  11327. auto& param = methodInst->mParams[argIdx];
  11328. if (param.mReferencedInConstPass)
  11329. {
  11330. // If this param is required as part of the const calculation then
  11331. // we require that it be const...
  11332. return BfTypedValue();
  11333. }
  11334. }
  11335. }
  11336. }
  11337. }
  11338. paramIdx++;
  11339. argIdx += argCount;
  11340. }
  11341. auto methodDef = methodInst->mMethodDef;
  11342. auto methodDecl = methodDef->GetMethodDeclaration();
  11343. auto methodDeclBlock = BfNodeDynCast<BfBlock>(methodDecl->mBody);
  11344. if (methodDeclBlock == NULL)
  11345. return BfTypedValue();
  11346. BfTypedValue constValue;
  11347. auto prevBlock = mBfIRBuilder->GetInsertBlock();
  11348. auto checkState = mCurMethodState->mConstResolveState;
  11349. while (checkState != NULL)
  11350. {
  11351. if (checkState->mMethodInstance == methodInst)
  11352. {
  11353. return BfTypedValue();
  11354. }
  11355. checkState = checkState->mPrevConstResolveState;
  11356. }
  11357. //auto accumValue = GetConstValue(0);
  11358. bool failed = false;
  11359. //
  11360. {
  11361. BfConstResolveState constResolveState;
  11362. constResolveState.mMethodInstance = methodInst;
  11363. constResolveState.mPrevConstResolveState = mCurMethodState->mConstResolveState;
  11364. SetAndRestoreValue<bool> ignoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  11365. BfMethodState methodState;
  11366. SetAndRestoreValue<BfTypeInstance*> prevTypeInst(mCurTypeInstance, methodInst->GetOwner());
  11367. SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mCurMethodInstance, methodInst);
  11368. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  11369. methodState.mTempKind = BfMethodState::TempKind_NonStatic;
  11370. methodState.mConstResolveState = &constResolveState;
  11371. int argIdx = 0;
  11372. for (int paramIdx = 0; paramIdx < methodInst->GetParamCount(); paramIdx++)
  11373. {
  11374. if (methodInst->GetParamKind(paramIdx) == BfParamKind_AppendIdx)
  11375. continue;
  11376. auto paramType = methodInst->GetParamType(paramIdx);
  11377. // Fix this after we allow structs to be consts
  11378. //BF_ASSERT(!paramType->IsSplattable());
  11379. BfLocalVariable* localVar = new BfLocalVariable();
  11380. localVar->mName = methodInst->GetParamName(paramIdx);
  11381. localVar->mResolvedType = paramType;
  11382. localVar->mConstValue = args[argIdx];
  11383. localVar->mParamIdx = paramIdx;
  11384. AddLocalVariableDef(localVar);
  11385. argIdx++;
  11386. }
  11387. AppendAllocVisitor appendAllocVisitor;
  11388. appendAllocVisitor.mConstAccum = GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr));
  11389. appendAllocVisitor.mIsFirstConstPass = isFirstRun;
  11390. BfTypedValue baseCtorAppendValue = CallBaseCtorCalc(true);
  11391. if (baseCtorAppendValue)
  11392. {
  11393. if (baseCtorAppendValue.mValue.IsFake())
  11394. appendAllocVisitor.mFailed = true;
  11395. else
  11396. appendAllocVisitor.mConstAccum = baseCtorAppendValue;
  11397. }
  11398. appendAllocVisitor.mModule = this;
  11399. appendAllocVisitor.VisitChild(methodDecl->mBody);
  11400. if (!appendAllocVisitor.mFailed)
  11401. constValue = appendAllocVisitor.mConstAccum;
  11402. if (isFirstRun)
  11403. mCurMethodInstance->mEndingAppendAllocAlign = appendAllocVisitor.mCurAppendAlign;
  11404. if (isFirstRun)
  11405. {
  11406. for (int paramIdx = 0; paramIdx < methodInst->GetParamCount(); paramIdx++)
  11407. {
  11408. auto localVar = mCurMethodState->mLocals[paramIdx];
  11409. if (localVar->mReadFromId != -1)
  11410. {
  11411. auto& param = methodInst->mParams[paramIdx];
  11412. param.mReferencedInConstPass = true;
  11413. }
  11414. }
  11415. }
  11416. }
  11417. mBfIRBuilder->SetInsertPoint(prevBlock);
  11418. if (!constValue)
  11419. {
  11420. // If we did a 'force' then some params may not have been const -- only clear mMayBeConst if we had
  11421. // all-const args
  11422. if (wasAllConst)
  11423. {
  11424. methodInst->mMayBeConst = false;
  11425. }
  11426. }
  11427. return constValue;
  11428. }
  11429. BfTypedValue BfModule::CallBaseCtorCalc(bool constOnly)
  11430. {
  11431. // Any errors should only be shown in the actual CTOR call
  11432. SetAndRestoreValue<bool> prevIgnoreWrites(mIgnoreErrors, true);
  11433. auto methodDef = mCurMethodInstance->mMethodDef;
  11434. BF_ASSERT((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend));
  11435. auto ctorDeclaration = (BfConstructorDeclaration*)methodDef->mMethodDeclaration;
  11436. BfTypeInstance* targetType = NULL;
  11437. if (ctorDeclaration->mInitializer != NULL)
  11438. {
  11439. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorDeclaration->mInitializer->mTarget);
  11440. targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  11441. }
  11442. else
  11443. targetType = mCurTypeInstance->mBaseType;
  11444. if ((targetType == NULL) || (targetType == mContext->mBfObjectType))
  11445. return NULL;
  11446. auto targetRefNode = methodDef->GetRefNode();
  11447. BfType* targetThisType = targetType;
  11448. BfTypedValue target(mBfIRBuilder->GetFakeVal(), targetThisType);
  11449. BfExprEvaluator exprEvaluator(this);
  11450. BfResolvedArgs argValues;
  11451. if ((ctorDeclaration != NULL) && (ctorDeclaration->mInitializer != NULL))
  11452. {
  11453. argValues.Init(&ctorDeclaration->mInitializer->mArguments);
  11454. }
  11455. //
  11456. {
  11457. }
  11458. BfFunctionBindResult bindResult;
  11459. bindResult.mSkipThis = true;
  11460. bindResult.mWantsArgs = true;
  11461. {
  11462. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  11463. exprEvaluator.ResolveArgValues(argValues, BfResolveArgFlag_DeferParamEval);
  11464. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(exprEvaluator.mFunctionBindResult, &bindResult);
  11465. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, true);
  11466. }
  11467. if (bindResult.mMethodInstance == NULL)
  11468. {
  11469. AssertErrorState();
  11470. return BfTypedValue();
  11471. }
  11472. if (!bindResult.mMethodInstance->mMethodDef->mHasAppend)
  11473. {
  11474. return BfTypedValue();
  11475. }
  11476. BF_ASSERT(bindResult.mIRArgs[0].IsFake());
  11477. bindResult.mIRArgs.RemoveAt(0);
  11478. auto calcAppendMethodModule = GetMethodInstanceAtIdx(bindResult.mMethodInstance->GetOwner(), bindResult.mMethodInstance->mMethodDef->mIdx + 1, BF_METHODNAME_CALCAPPEND);
  11479. BfTypedValue appendSizeTypedValue = TryConstCalcAppend(calcAppendMethodModule.mMethodInstance, bindResult.mIRArgs);
  11480. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mAppendAllocAlign >= 0);
  11481. mCurMethodInstance->mAppendAllocAlign = BF_MAX((int)mCurMethodInstance->mAppendAllocAlign, calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  11482. BF_ASSERT(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign > -1);
  11483. mCurMethodState->mCurAppendAlign = BF_MAX(calcAppendMethodModule.mMethodInstance->mEndingAppendAllocAlign, 0);
  11484. if (appendSizeTypedValue)
  11485. return appendSizeTypedValue;
  11486. if (constOnly)
  11487. return BfTypedValue(mBfIRBuilder->GetFakeVal(), GetPrimitiveType(BfTypeCode_IntPtr));
  11488. bool needsRecalc = false;
  11489. for (auto irArg : bindResult.mIRArgs)
  11490. {
  11491. if (irArg.IsFake())
  11492. needsRecalc = true;
  11493. }
  11494. auto calcAppendArgs = bindResult.mIRArgs;
  11495. if (needsRecalc)
  11496. {
  11497. // Do it again, but without mIgnoreWrites set
  11498. BfResolvedArgs argValues;
  11499. argValues.Init(&ctorDeclaration->mInitializer->mArguments);
  11500. exprEvaluator.ResolveArgValues(argValues, BfResolveArgFlag_DeferParamEval);
  11501. BfFunctionBindResult bindResult;
  11502. bindResult.mSkipThis = true;
  11503. bindResult.mWantsArgs = true;
  11504. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(exprEvaluator.mFunctionBindResult, &bindResult);
  11505. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, true);
  11506. BF_ASSERT(bindResult.mIRArgs[0].IsFake());
  11507. bindResult.mIRArgs.RemoveAt(0);
  11508. calcAppendArgs = bindResult.mIRArgs;
  11509. }
  11510. BF_ASSERT(calcAppendMethodModule.mFunc);
  11511. appendSizeTypedValue = exprEvaluator.CreateCall(calcAppendMethodModule.mMethodInstance, calcAppendMethodModule.mFunc, false, calcAppendArgs);
  11512. BF_ASSERT(appendSizeTypedValue.mType == GetPrimitiveType(BfTypeCode_IntPtr));
  11513. return appendSizeTypedValue;
  11514. }
  11515. // This method never throws errors - it relies on the proper ctor actually throwing the errors
  11516. void BfModule::EmitCtorCalcAppend()
  11517. {
  11518. if (mCompiler->mIsResolveOnly)
  11519. return;
  11520. auto methodDef = mCurMethodInstance->mMethodDef;
  11521. auto methodDecl = methodDef->GetMethodDeclaration();
  11522. Array<BfAstNode*> deferredNodeList;
  11523. auto methodDeclBlock = BfNodeDynCast<BfBlock>(methodDecl->mBody);
  11524. if (methodDeclBlock == NULL)
  11525. return;
  11526. AppendAllocVisitor appendAllocVisitor;
  11527. auto baseCalcAppend = CallBaseCtorCalc(false);
  11528. if (baseCalcAppend)
  11529. {
  11530. mBfIRBuilder->CreateStore(baseCalcAppend.mValue, mCurMethodState->mRetVal.mValue);
  11531. }
  11532. appendAllocVisitor.mModule = this;
  11533. appendAllocVisitor.VisitChild(methodDecl->mBody);
  11534. }
  11535. void BfModule::CreateStaticCtor()
  11536. {
  11537. auto typeDef = mCurTypeInstance->mTypeDef;
  11538. auto methodDef = mCurMethodInstance->mMethodDef;
  11539. BfIRBlock exitBB;
  11540. if ((HasCompiledOutput()) && (!mCurMethodInstance->mIsUnspecialized) && (mCurMethodInstance->mChainType != BfMethodChainType_ChainMember))
  11541. {
  11542. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  11543. auto didStaticInitVarAddr = mBfIRBuilder->CreateGlobalVariable(
  11544. mBfIRBuilder->MapType(boolType),
  11545. false,
  11546. BfIRLinkageType_Internal,
  11547. GetDefaultValue(boolType),
  11548. "didStaticInit");
  11549. auto initBB = mBfIRBuilder->CreateBlock("init", true);
  11550. mCurMethodState->mIRExitBlock = mBfIRBuilder->CreateBlock("exit", true);
  11551. auto didStaticInitVar = mBfIRBuilder->CreateLoad(didStaticInitVarAddr);
  11552. mBfIRBuilder->CreateCondBr(didStaticInitVar, mCurMethodState->mIRExitBlock, initBB);
  11553. mBfIRBuilder->SetInsertPoint(initBB);
  11554. mBfIRBuilder->CreateStore(GetConstValue(1, boolType), didStaticInitVarAddr);
  11555. }
  11556. // Do DLL imports
  11557. if (!mDllImportEntries.empty())
  11558. {
  11559. auto internalType = ResolveTypeDef(mCompiler->mInternalTypeDef);
  11560. PopulateType(internalType);
  11561. auto getSharedProcAddressInstance = GetMethodByName(internalType->ToTypeInstance(), "GetSharedProcAddress");
  11562. if (!getSharedProcAddressInstance)
  11563. {
  11564. if (!mCompiler->mPassInstance->HasFailed())
  11565. Fail("Internal error: System.Internal doesn't contain LoadSharedLibrary method");
  11566. }
  11567. }
  11568. // Fill in initializer values
  11569. if ((!mCompiler->mIsResolveOnly) || (mCompiler->mResolvePassData->mAutoComplete == NULL))
  11570. {
  11571. for (auto fieldDef : typeDef->mFields)
  11572. {
  11573. if ((!fieldDef->mIsConst) && (fieldDef->mIsStatic) && (fieldDef->mInitializer != NULL))
  11574. {
  11575. // For extensions, only handle these fields in the appropriate extension
  11576. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  11577. continue;
  11578. UpdateSrcPos(fieldDef->mInitializer);
  11579. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  11580. if (!fieldInst->mFieldIncluded)
  11581. continue;
  11582. if (fieldInst->mResolvedType->IsVar())
  11583. {
  11584. continue;
  11585. }
  11586. auto assignValue = GetFieldInitializerValue(fieldInst);
  11587. if (assignValue)
  11588. {
  11589. assignValue = LoadValue(assignValue);
  11590. if (!assignValue.mType->IsValuelessType())
  11591. {
  11592. auto staticVarRef = ReferenceStaticField(fieldInst).mValue;
  11593. mBfIRBuilder->CreateStore(assignValue.mValue, staticVarRef);
  11594. }
  11595. }
  11596. }
  11597. }
  11598. }
  11599. else
  11600. {
  11601. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  11602. {
  11603. if (tempTypeDef->mFullName == typeDef->mFullName)
  11604. {
  11605. for (auto fieldDef : tempTypeDef->mFields)
  11606. {
  11607. if ((fieldDef->mIsStatic) && (!fieldDef->mIsConst))
  11608. {
  11609. if (fieldDef->mInitializer != NULL)
  11610. {
  11611. if (mCompiler->mResolvePassData->mSourceClassifier != NULL)
  11612. {
  11613. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(fieldDef->mInitializer, BfSourceElementType_Normal);
  11614. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(fieldDef->mInitializer);
  11615. }
  11616. BfType* wantType = NULL;
  11617. if ((!BfNodeIsA<BfVarTypeReference>(fieldDef->mTypeRef)) && (!BfNodeIsA<BfLetTypeReference>(fieldDef->mTypeRef)))
  11618. {
  11619. wantType = ResolveTypeRef(fieldDef->mTypeRef);
  11620. }
  11621. CreateValueFromExpression(fieldDef->mInitializer, wantType, BfEvalExprFlags_FieldInitializer);
  11622. }
  11623. }
  11624. }
  11625. }
  11626. }
  11627. }
  11628. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  11629. CallChainedMethods(mCurMethodInstance, false);
  11630. }
  11631. void BfModule::EmitDtorBody()
  11632. {
  11633. if (mCurTypeInstance->IsClosure())
  11634. {
  11635. BfFieldInstance* fieldInstance = &mCurTypeInstance->mFieldInstances.back();
  11636. BF_ASSERT(fieldInstance->GetFieldDef()->mName == "__dtorThunk");
  11637. auto thisVal = GetThis();
  11638. auto dtorThunkPtr = mBfIRBuilder->CreateInBoundsGEP(thisVal.mValue, 0, fieldInstance->mDataIdx);
  11639. auto dtorThunk = mBfIRBuilder->CreateLoad(dtorThunkPtr);
  11640. auto funcPtrType = mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapMethod(mCurMethodInstance));
  11641. auto dtorPtr = mBfIRBuilder->CreateBitCast(dtorThunk, funcPtrType);
  11642. SizedArray<BfIRValue, 1> args;
  11643. args.push_back(thisVal.mValue);
  11644. auto result = mBfIRBuilder->CreateCall(dtorPtr, args);
  11645. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_CDecl);
  11646. // Fall through to Object::~this call
  11647. auto dtorFunc = GetMethodByName(mContext->mBfObjectType, "~this");
  11648. auto basePtr = mBfIRBuilder->CreateBitCast(thisVal.mValue, mBfIRBuilder->MapTypeInstPtr(mContext->mBfObjectType));
  11649. SizedArray<BfIRValue, 1> vals = { basePtr };
  11650. result = mBfIRBuilder->CreateCall(dtorFunc.mFunc, vals);
  11651. mBfIRBuilder->SetCallCallingConv(result, GetCallingConvention(dtorFunc.mMethodInstance));
  11652. mBfIRBuilder->SetTailCall(result);
  11653. return;
  11654. }
  11655. auto typeDef = mCurTypeInstance->mTypeDef;
  11656. auto methodDef = mCurMethodInstance->mMethodDef;
  11657. auto methodDeclaration = methodDef->GetMethodDeclaration();
  11658. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  11659. CallChainedMethods(mCurMethodInstance, true);
  11660. if (auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody))
  11661. {
  11662. VisitCodeBlock(bodyBlock);
  11663. if (bodyBlock->mCloseBrace != NULL)
  11664. {
  11665. UpdateSrcPos(bodyBlock->mCloseBrace);
  11666. }
  11667. }
  11668. else
  11669. {
  11670. if (methodDeclaration != NULL)
  11671. UpdateSrcPos(methodDeclaration);
  11672. else if (typeDef->mTypeDeclaration != NULL)
  11673. UpdateSrcPos(typeDef->mTypeDeclaration);
  11674. if ((methodDeclaration != NULL) && (methodDeclaration->mFatArrowToken != NULL))
  11675. {
  11676. Fail("Destructors cannot have expression bodies", methodDeclaration->mFatArrowToken);
  11677. }
  11678. }
  11679. if ((!mCompiler->mIsResolveOnly) || (mCompiler->mResolvePassData->mAutoComplete == NULL))
  11680. {
  11681. for (int fieldIdx = (int)mCurTypeInstance->mFieldInstances.size() - 1; fieldIdx >= 0; fieldIdx--)
  11682. {
  11683. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldIdx];
  11684. auto fieldDef = fieldInst->GetFieldDef();
  11685. if ((fieldDef != NULL) && (fieldDef->mIsStatic == methodDef->mIsStatic) && (fieldDef->mFieldDeclaration != NULL) && (fieldDef->mFieldDeclaration->mFieldDtor != NULL))
  11686. {
  11687. if ((!methodDef->mIsStatic) && (mCurTypeInstance->IsValueType()))
  11688. {
  11689. Fail("Structs cannot have field destructors", fieldDef->mFieldDeclaration->mFieldDtor->mTildeToken);
  11690. }
  11691. SetAndRestoreValue<BfFilePosition> prevFilePos(mCurFilePosition);
  11692. auto fieldDtor = fieldDef->mFieldDeclaration->mFieldDtor;
  11693. if ((fieldDef->mIsStatic) != (methodDef->mIsStatic))
  11694. continue;
  11695. UpdateSrcPos(fieldDtor);
  11696. BfScopeData scopeData;
  11697. mCurMethodState->AddScope(&scopeData);
  11698. NewScopeState();
  11699. UpdateSrcPos(fieldDtor);
  11700. bool hasDbgInfo = (!fieldDef->mIsConst);
  11701. if (hasDbgInfo)
  11702. {
  11703. mBfIRBuilder->SaveDebugLocation();
  11704. mBfIRBuilder->ClearDebugLocation();
  11705. }
  11706. BfIRValue value;
  11707. if (fieldDef->mIsStatic)
  11708. {
  11709. value = ReferenceStaticField(fieldInst).mValue;
  11710. }
  11711. else
  11712. {
  11713. if (!mCurTypeInstance->IsValueType())
  11714. {
  11715. auto thisValue = GetThis();
  11716. value = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInst->mDataIdx);
  11717. }
  11718. else
  11719. {
  11720. AssertErrorState();
  11721. value = mBfIRBuilder->CreateConstNull(mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(fieldInst->mResolvedType)));
  11722. }
  11723. }
  11724. BfIRValue staticVal;
  11725. if (hasDbgInfo)
  11726. {
  11727. BfIRValue dbgShowValue = value;
  11728. BfLocalVariable* localDef = new BfLocalVariable();
  11729. localDef->mName = "_";
  11730. localDef->mResolvedType = fieldInst->mResolvedType;
  11731. localDef->mAddr = value;
  11732. if ((mBfIRBuilder->DbgHasInfo()) && (!IsTargetingBeefBackend()))
  11733. {
  11734. // Create another pointer indirection, a ref to the gep
  11735. auto refFieldType = CreateRefType(fieldInst->mResolvedType);
  11736. auto allocaInst = CreateAlloca(refFieldType);
  11737. auto storeResult = mBfIRBuilder->CreateStore(value, allocaInst);
  11738. localDef->mResolvedType = refFieldType;
  11739. localDef->mAddr = allocaInst;
  11740. }
  11741. mBfIRBuilder->RestoreDebugLocation();
  11742. auto defLocalVar = AddLocalVariableDef(localDef, true);
  11743. // Put back so we actually modify the correct value*/
  11744. defLocalVar->mResolvedType = fieldInst->mResolvedType;
  11745. defLocalVar->mAddr = value;
  11746. }
  11747. while (fieldDtor != NULL)
  11748. {
  11749. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  11750. {
  11751. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(fieldDtor, BfSourceElementType_Normal);
  11752. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(fieldDtor);
  11753. }
  11754. UpdateSrcPos(fieldDtor);
  11755. VisitEmbeddedStatement(fieldDtor->mBody);
  11756. fieldDtor = fieldDtor->mNextFieldDtor;
  11757. }
  11758. RestoreScopeState();
  11759. }
  11760. }
  11761. if (!methodDef->mIsStatic)
  11762. {
  11763. auto checkBaseType = mCurTypeInstance->mBaseType;
  11764. while (checkBaseType != NULL)
  11765. {
  11766. if (auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody))
  11767. {
  11768. if (bodyBlock->mCloseBrace != NULL)
  11769. UpdateSrcPos(bodyBlock->mCloseBrace);
  11770. }
  11771. else
  11772. {
  11773. UpdateSrcPos(typeDef->mTypeDeclaration->mNameNode);
  11774. }
  11775. if (checkBaseType->mTypeDef->mDtorDef != NULL)
  11776. {
  11777. auto dtorMethodInstance = GetMethodInstance(checkBaseType, checkBaseType->mTypeDef->mDtorDef, BfTypeVector());
  11778. if (mCompiler->IsSkippingExtraResolveChecks())
  11779. {
  11780. // Nothing
  11781. }
  11782. else if (dtorMethodInstance.mMethodInstance->GetParamCount() == 0)
  11783. {
  11784. if ((!mCompiler->IsSkippingExtraResolveChecks()) && (!checkBaseType->IsUnspecializedType()))
  11785. {
  11786. auto basePtr = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapTypeInstPtr(checkBaseType));
  11787. SizedArray<BfIRValue, 1> vals = { basePtr };
  11788. auto callInst = mBfIRBuilder->CreateCall(dtorMethodInstance.mFunc, vals);
  11789. mBfIRBuilder->SetCallCallingConv(callInst, GetCallingConvention(dtorMethodInstance.mMethodInstance));
  11790. }
  11791. }
  11792. else
  11793. {
  11794. // Invalid base dtor declaration
  11795. AssertErrorState();
  11796. }
  11797. break;
  11798. }
  11799. checkBaseType = checkBaseType->mBaseType;
  11800. }
  11801. }
  11802. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  11803. }
  11804. else
  11805. {
  11806. // The reason we can't just do the 'normal' path for this is that the BfTypeInstance here is NOT the
  11807. // autocomplete type instance, so FieldInstance initializer values contain expressions from the full
  11808. // resolve pass, NOT the autocomplete expression
  11809. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  11810. {
  11811. if (tempTypeDef->mFullName == typeDef->mFullName)
  11812. {
  11813. for (auto fieldDef : tempTypeDef->mFields)
  11814. {
  11815. if ((fieldDef->mIsStatic == methodDef->mIsStatic) && (fieldDef->mFieldDeclaration != NULL) &&
  11816. (fieldDef->mFieldDeclaration->mFieldDtor != NULL) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  11817. {
  11818. BfType* fieldType = NULL;
  11819. for (int curFieldIdx = 0; curFieldIdx < (int)mCurTypeInstance->mFieldInstances.size(); curFieldIdx++)
  11820. {
  11821. auto curFieldInstance = &mCurTypeInstance->mFieldInstances[curFieldIdx];
  11822. auto curFieldDef = curFieldInstance->GetFieldDef();
  11823. if ((curFieldDef != NULL) && (fieldDef->mName == curFieldDef->mName))
  11824. fieldType = curFieldInstance->GetResolvedType();
  11825. }
  11826. auto fieldDtor = fieldDef->mFieldDeclaration->mFieldDtor;
  11827. BfScopeData scopeData;
  11828. mCurMethodState->AddScope(&scopeData);
  11829. NewScopeState();
  11830. // This is just for autocomplete, it doesn't matter that mAddr is incorrect
  11831. if (fieldType != NULL)
  11832. {
  11833. BfLocalVariable* localDef = new BfLocalVariable();
  11834. localDef->mName = "_";
  11835. localDef->mResolvedType = fieldType;
  11836. localDef->mAddr = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(fieldType));
  11837. localDef->mIsAssigned = true;
  11838. AddLocalVariableDef(localDef);
  11839. }
  11840. while (fieldDtor != NULL)
  11841. {
  11842. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(fieldDtor, BfSourceElementType_Normal);
  11843. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(fieldDtor);
  11844. UpdateSrcPos(fieldDtor);
  11845. VisitEmbeddedStatement(fieldDtor->mBody);
  11846. fieldDtor = fieldDtor->mNextFieldDtor;
  11847. }
  11848. RestoreScopeState();
  11849. }
  11850. }
  11851. }
  11852. }
  11853. }
  11854. }
  11855. BfIRValue BfModule::CreateDllImportGlobalVar(BfMethodInstance* methodInstance, bool define)
  11856. {
  11857. auto typeInstance = methodInstance->GetOwner();
  11858. bool foundDllImportAttr = false;
  11859. BfCallingConvention callingConvention = methodInstance->mMethodDef->mCallingConvention;
  11860. for (auto customAttr : methodInstance->GetCustomAttributes()->mAttributes)
  11861. {
  11862. if (customAttr.mType->mTypeDef->mFullName.ToString() == "System.ImportAttribute")
  11863. {
  11864. foundDllImportAttr = true;
  11865. }
  11866. }
  11867. if (!foundDllImportAttr)
  11868. {
  11869. AssertErrorState();
  11870. return BfIRValue();
  11871. }
  11872. String name = "bf_hs_preserve@";
  11873. BfMangler::Mangle(name, mCompiler->GetMangleKind(), methodInstance);
  11874. name += "__imp";
  11875. BfIRType returnType;
  11876. SizedArray<BfIRType, 8> paramTypes;
  11877. methodInstance->GetIRFunctionInfo(this, returnType, paramTypes);
  11878. BfIRFunctionType externFunctionType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes, false);
  11879. auto ptrType = mBfIRBuilder->GetPointerTo(externFunctionType);
  11880. BfIRValue initVal;
  11881. if (define)
  11882. {
  11883. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  11884. initVal = mBfIRBuilder->CreateConstNull(ptrType);
  11885. }
  11886. auto globalVar = mBfIRBuilder->CreateGlobalVariable(ptrType, false, BfIRLinkageType_External, initVal, name);
  11887. if ((define) && (mBfIRBuilder->DbgHasInfo()))
  11888. {
  11889. auto voidType = GetPrimitiveType(BfTypeCode_None);
  11890. auto ptrType = CreatePointerType(voidType);
  11891. mBfIRBuilder->DbgCreateGlobalVariable(mDICompileUnit, name, name, BfIRMDNode(), 0, mBfIRBuilder->DbgGetType(ptrType), false, globalVar);
  11892. }
  11893. return globalVar;
  11894. }
  11895. void BfModule::CreateDllImportMethod()
  11896. {
  11897. if (mBfIRBuilder->mIgnoreWrites)
  11898. return;
  11899. auto globalVar = mFuncReferences[mCurMethodInstance];
  11900. if (!globalVar)
  11901. return;
  11902. bool allowTailCall = true;
  11903. mBfIRBuilder->ClearDebugLocation();
  11904. bool isHotCompile = mCompiler->IsHotCompile();
  11905. // If we are hot swapping, we need to have this stub because we may need to call the LoadSharedLibraries on demand
  11906. if (isHotCompile)
  11907. {
  11908. auto loadSharedLibsFunc = GetBuiltInFunc(BfBuiltInFuncType_LoadSharedLibraries);
  11909. mBfIRBuilder->CreateCall(loadSharedLibsFunc, SizedArray<BfIRValue, 0>());
  11910. }
  11911. auto callingConvention = GetCallingConvention(mCurTypeInstance, mCurMethodInstance->mMethodDef);
  11912. BfIRType returnType;
  11913. SizedArray<BfIRType, 8> paramTypes;
  11914. mCurMethodInstance->GetIRFunctionInfo(this, returnType, paramTypes);
  11915. SizedArray<BfIRValue, 8> args;
  11916. for (int i = 0; i < (int)paramTypes.size(); i++)
  11917. args.push_back(mBfIRBuilder->GetArgument(i));
  11918. BfIRFunctionType externFunctionType = mBfIRBuilder->CreateFunctionType(returnType, paramTypes, false);
  11919. if (isHotCompile)
  11920. {
  11921. BfIRValue funcVal = mBfIRBuilder->CreateLoad(globalVar);
  11922. auto result = mBfIRBuilder->CreateCall(funcVal, args);
  11923. if (callingConvention == BfIRCallingConv_StdCall)
  11924. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_StdCall);
  11925. else
  11926. mBfIRBuilder->SetCallCallingConv(result, BfIRCallingConv_CDecl);
  11927. if (allowTailCall)
  11928. mBfIRBuilder->SetTailCall(result);
  11929. CreateReturn(result);
  11930. mCurMethodState->mHadReturn = true;
  11931. }
  11932. if (HasCompiledOutput())
  11933. {
  11934. BfDllImportEntry dllImportEntry;
  11935. dllImportEntry.mFuncVar = globalVar;
  11936. dllImportEntry.mMethodInstance = mCurMethodInstance;
  11937. mDllImportEntries.push_back(dllImportEntry);
  11938. }
  11939. }
  11940. BfIRCallingConv BfModule::GetCallingConvention(BfTypeInstance* typeInst, BfMethodDef* methodDef)
  11941. {
  11942. if ((mCompiler->mOptions.mMachineType != BfMachineType_x86) || (mCompiler->mOptions.mPlatformType != BfPlatformType_Windows))
  11943. return BfIRCallingConv_CDecl;
  11944. if (methodDef->mCallingConvention == BfCallingConvention_Stdcall)
  11945. return BfIRCallingConv_StdCall;
  11946. if ((!methodDef->mIsStatic) && (!typeInst->IsValuelessType()) &&
  11947. ((!typeInst->IsSplattable()) || (methodDef->HasNoThisSplat())))
  11948. return BfIRCallingConv_ThisCall;
  11949. return BfIRCallingConv_CDecl;
  11950. }
  11951. BfIRCallingConv BfModule::GetCallingConvention(BfMethodInstance* methodInstance)
  11952. {
  11953. return GetCallingConvention(methodInstance->GetOwner(), methodInstance->mMethodDef);
  11954. }
  11955. void BfModule::SetupIRMethod(BfMethodInstance* methodInstance, BfIRFunction func, bool isInlined)
  11956. {
  11957. BfMethodDef* methodDef = NULL;
  11958. if (methodInstance != NULL)
  11959. methodDef = methodInstance->mMethodDef;
  11960. if (!func)
  11961. return;
  11962. if (mCompiler->mOptions.mNoFramePointerElim)
  11963. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_NoFramePointerElim);
  11964. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_NoUnwind);
  11965. if (mSystem->mPtrSize == 8) // We need unwind info for debugging
  11966. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_UWTable);
  11967. if (methodInstance == NULL)
  11968. return;
  11969. if (methodDef->mImportKind == BfImportKind_Export)
  11970. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_DllExport);
  11971. if (methodDef->mNoReturn)
  11972. mBfIRBuilder->Func_AddAttribute(func, -1, BfIRAttribute_NoReturn);
  11973. auto callingConv = GetCallingConvention(methodInstance->GetOwner(), methodDef);
  11974. if (callingConv != BfIRCallingConv_CDecl)
  11975. mBfIRBuilder->SetFuncCallingConv(func, callingConv);
  11976. if (isInlined)
  11977. {
  11978. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_AlwaysInline);
  11979. }
  11980. int argIdx = 0;
  11981. int paramIdx = 0;
  11982. if (methodInstance->HasThis())
  11983. {
  11984. paramIdx = -1;
  11985. }
  11986. int argCount = methodInstance->GetIRFunctionParamCount(this);
  11987. if (methodInstance->HasStructRet())
  11988. {
  11989. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_NoAlias);
  11990. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_StructRet);
  11991. argIdx++;
  11992. }
  11993. while (argIdx < argCount)
  11994. {
  11995. while ((paramIdx != -1) && (methodInstance->IsParamSkipped(paramIdx)))
  11996. paramIdx++;
  11997. BfType* resolvedTypeRef = NULL;
  11998. String paramName;
  11999. bool isSplattable = false;
  12000. bool isThis = paramIdx == -1;
  12001. if (isThis)
  12002. {
  12003. paramName = "this";
  12004. if (methodInstance->mIsClosure)
  12005. resolvedTypeRef = mCurMethodState->mClosureState->mClosureType;
  12006. else
  12007. resolvedTypeRef = methodInstance->GetOwner();
  12008. isSplattable = (resolvedTypeRef->IsSplattable()) && (!methodDef->HasNoThisSplat());
  12009. }
  12010. else if (!methodDef->mNoSplat)
  12011. {
  12012. paramName = methodInstance->GetParamName(paramIdx);
  12013. resolvedTypeRef = methodInstance->GetParamType(paramIdx);
  12014. if (resolvedTypeRef->IsMethodRef())
  12015. isSplattable = true;
  12016. else if (resolvedTypeRef->IsSplattable())
  12017. {
  12018. if (resolvedTypeRef->GetSplatCount() + argIdx <= mCompiler->mOptions.mMaxSplatRegs)
  12019. isSplattable = true;
  12020. }
  12021. }
  12022. //
  12023. {
  12024. auto loweredTypeCode = resolvedTypeRef->GetLoweredType();
  12025. if (loweredTypeCode != BfTypeCode_None)
  12026. resolvedTypeRef = GetPrimitiveType(loweredTypeCode);
  12027. }
  12028. auto _SetupParam = [&](const StringImpl& paramName, BfType* resolvedTypeRef)
  12029. {
  12030. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, paramName);
  12031. int addDeref = -1;
  12032. if (resolvedTypeRef->IsRef())
  12033. {
  12034. auto refType = (BfRefType*)resolvedTypeRef;
  12035. auto elementType = refType->mElementType;
  12036. PopulateType(elementType, BfPopulateType_Data);
  12037. addDeref = elementType->mSize;
  12038. if ((addDeref <= 0) && (!elementType->IsValuelessType()))
  12039. AssertErrorState();
  12040. }
  12041. if ((resolvedTypeRef->IsComposite()) && (!resolvedTypeRef->IsTypedPrimitive()))
  12042. {
  12043. if (mCompiler->mOptions.mAllowStructByVal)
  12044. {
  12045. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_ByVal);
  12046. }
  12047. else
  12048. {
  12049. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_NoCapture);
  12050. PopulateType(resolvedTypeRef, BfPopulateType_Data);
  12051. addDeref = resolvedTypeRef->mSize;
  12052. }
  12053. }
  12054. else if (resolvedTypeRef->IsPrimitiveType())
  12055. {
  12056. auto primType = (BfPrimitiveType*)resolvedTypeRef;
  12057. if (primType->mTypeDef->mTypeCode == BfTypeCode_Boolean)
  12058. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_ZExt);
  12059. }
  12060. if (addDeref >= 0)
  12061. mBfIRBuilder->Func_AddAttribute(func, argIdx + 1, BfIRAttribute_Dereferencable, addDeref);
  12062. argIdx++;
  12063. };
  12064. if (isSplattable)
  12065. {
  12066. std::function<void(BfType*, const StringImpl&)> checkTypeLambda = [&](BfType* checkType, const StringImpl& curName)
  12067. {
  12068. if (checkType->IsStruct())
  12069. {
  12070. auto checkTypeInstance = checkType->ToTypeInstance();
  12071. if (checkTypeInstance->mBaseType != NULL)
  12072. checkTypeLambda(checkTypeInstance->mBaseType, curName);
  12073. if (checkTypeInstance->mIsUnion)
  12074. {
  12075. BfType* unionInnerType = checkTypeInstance->GetUnionInnerType();
  12076. checkTypeLambda(unionInnerType, curName + "_data");
  12077. }
  12078. else
  12079. {
  12080. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  12081. {
  12082. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  12083. auto fieldDef = fieldInstance->GetFieldDef();
  12084. if (fieldInstance->mDataIdx >= 0)
  12085. {
  12086. checkTypeLambda(fieldInstance->GetResolvedType(), curName + "_" + fieldInstance->GetFieldDef()->mName);
  12087. }
  12088. }
  12089. }
  12090. if (checkTypeInstance->IsEnum())
  12091. {
  12092. mBfIRBuilder->Func_SetParamName(func, argIdx + 1, curName + "_dscr");
  12093. argIdx++;
  12094. }
  12095. }
  12096. else if (checkType->IsMethodRef())
  12097. {
  12098. auto methodRefType = (BfMethodRefType*)checkType;
  12099. BfMethodInstance* methodRefMethodInst = methodRefType->mMethodRef;
  12100. for (int dataIdx = 0; dataIdx < (int)methodRefType->GetCaptureDataCount(); dataIdx++)
  12101. {
  12102. int methodRefParamIdx = methodRefType->GetParamIdxFromDataIdx(dataIdx);
  12103. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  12104. {
  12105. checkTypeLambda(methodRefType->GetCaptureType(dataIdx), curName + "_" + methodRefMethodInst->GetParamName(methodRefParamIdx));
  12106. }
  12107. else
  12108. {
  12109. _SetupParam(curName + "_" + methodRefMethodInst->GetParamName(methodRefParamIdx), methodRefType->GetCaptureType(dataIdx));
  12110. }
  12111. }
  12112. }
  12113. else if (!checkType->IsValuelessType())
  12114. {
  12115. _SetupParam(curName, checkType);
  12116. }
  12117. };
  12118. checkTypeLambda(resolvedTypeRef, paramName);
  12119. paramIdx++;
  12120. continue;
  12121. }
  12122. _SetupParam(paramName, resolvedTypeRef);
  12123. //argIdx++;
  12124. paramIdx++;
  12125. }
  12126. }
  12127. void BfModule::EmitCtorBody(bool& skipBody)
  12128. {
  12129. auto methodInstance = mCurMethodInstance;
  12130. auto methodDef = methodInstance->mMethodDef;
  12131. auto methodDeclaration = methodDef->mMethodDeclaration;
  12132. auto ctorDeclaration = (BfConstructorDeclaration*)methodDef->mMethodDeclaration;
  12133. auto typeDef = mCurTypeInstance->mTypeDef;
  12134. // Prologue
  12135. mBfIRBuilder->ClearDebugLocation();
  12136. bool hadThisInitializer = false;
  12137. if ((ctorDeclaration != NULL) && (ctorDeclaration->mInitializer != NULL))
  12138. {
  12139. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorDeclaration->mInitializer->mTarget);
  12140. auto targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  12141. if (targetToken->GetToken() == BfToken_This)
  12142. {
  12143. hadThisInitializer = true;
  12144. // Since we call a 'this', it's that other ctor's responsibility to fully assign the fields
  12145. mCurMethodState->LocalDefined(GetThisVariable());
  12146. }
  12147. }
  12148. // Zero out memory for default ctor
  12149. if ((methodDeclaration == NULL) && (mCurTypeInstance->IsStruct()))
  12150. {
  12151. if (mCurTypeInstance->IsTypedPrimitive())
  12152. {
  12153. auto thisRef = mCurMethodState->mLocals[0]->mValue;
  12154. mBfIRBuilder->CreateStore(GetDefaultValue(mCurTypeInstance), thisRef);
  12155. }
  12156. else if (mCurTypeInstance->mInstSize > 0)
  12157. {
  12158. BfIRValue fillValue = GetConstValue8(0);
  12159. BfIRValue sizeValue = GetConstValue(mCurTypeInstance->mInstSize);
  12160. auto thisRef = mCurMethodState->mLocals[0]->mValue;
  12161. BfIRValue destBits = mBfIRBuilder->CreateBitCast(thisRef, mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr));
  12162. mBfIRBuilder->CreateMemSet(destBits, fillValue, sizeValue, mCurTypeInstance->mAlign);
  12163. }
  12164. }
  12165. BfAstNode* baseCtorNode = NULL;
  12166. if ((ctorDeclaration != NULL) && (ctorDeclaration->mInitializer != NULL) && (ctorDeclaration->mInitializer->mTarget != NULL))
  12167. baseCtorNode = ctorDeclaration->mInitializer->mTarget;
  12168. else if (methodDef->mBody != NULL)
  12169. baseCtorNode = methodDef->mBody;
  12170. else if (ctorDeclaration != NULL)
  12171. baseCtorNode = ctorDeclaration;
  12172. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  12173. baseCtorNode = mCurTypeInstance->mTypeDef->mTypeDeclaration->mNameNode;
  12174. else if ((mCurTypeInstance->mBaseType != NULL) && (mCurTypeInstance->mBaseType->mTypeDef->mTypeDeclaration != NULL))
  12175. baseCtorNode = mCurTypeInstance->mBaseType->mTypeDef->mTypeDeclaration;
  12176. else
  12177. baseCtorNode = mContext->mBfObjectType->mTypeDef->mTypeDeclaration;
  12178. if ((!mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType == BfMethodType_Ctor))
  12179. {
  12180. // Call the root type's default ctor (with no body) to initialize its fields and call the chained ctors
  12181. if (methodDef->mDeclaringType->mTypeCode == BfTypeCode_Extension)
  12182. {
  12183. BfMethodDef* defaultCtor = NULL;
  12184. for (auto methodDef : mCurTypeInstance->mTypeDef->mMethods)
  12185. {
  12186. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) && (methodDef->mDeclaringType->mTypeCode != BfTypeCode_Extension))
  12187. {
  12188. defaultCtor = methodDef;
  12189. }
  12190. }
  12191. if (defaultCtor != NULL)
  12192. {
  12193. UpdateSrcPos(mCurTypeInstance->mTypeDef->GetRefNode());
  12194. SetIllegalSrcPos();
  12195. auto moduleMethodInstance = GetMethodInstance(mCurTypeInstance, defaultCtor, BfTypeVector());
  12196. BfExprEvaluator exprEvaluator(this);
  12197. SizedArray<BfIRValue, 1> irArgs;
  12198. exprEvaluator.PushThis(NULL, GetThis(), moduleMethodInstance.mMethodInstance, irArgs);
  12199. exprEvaluator.CreateCall(moduleMethodInstance.mMethodInstance, moduleMethodInstance.mFunc, false, irArgs);
  12200. }
  12201. }
  12202. }
  12203. // Initialize fields (if applicable)
  12204. if (mCurTypeInstance->IsBoxed())
  12205. {
  12206. skipBody = true;
  12207. }
  12208. else if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mDeclaringType->mTypeCode == BfTypeCode_Extension))
  12209. {
  12210. // Field initializers occur in CtorNoBody methods for extensions
  12211. }
  12212. else if (!hadThisInitializer)
  12213. {
  12214. // If we had a 'this' initializer, that other ctor will have initialized our fields
  12215. if ((!mCompiler->mIsResolveOnly) ||
  12216. (mCompiler->mResolvePassData->mAutoComplete == NULL) ||
  12217. (mCompiler->mResolvePassData->mAutoComplete->mResolveType == BfResolveType_ShowFileSymbolReferences))
  12218. {
  12219. bool hadInlineInitBlock = false;
  12220. BfScopeData scopeData;
  12221. for (auto fieldDef : typeDef->mFields)
  12222. {
  12223. // For extensions, only handle these fields in the appropriate extension
  12224. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  12225. continue;
  12226. if ((!fieldDef->mIsConst) && (!fieldDef->mIsStatic))
  12227. {
  12228. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  12229. if (!fieldInst->mFieldIncluded)
  12230. continue;
  12231. if (fieldInst->mDataIdx < 0)
  12232. continue;
  12233. if (fieldDef->mInitializer == NULL)
  12234. {
  12235. if (fieldDef->mProtection != BfProtection_Hidden)
  12236. continue;
  12237. if (mCurTypeInstance->IsObject()) // Already zeroed out
  12238. continue;
  12239. }
  12240. if (fieldInst->mResolvedType == NULL)
  12241. {
  12242. BF_ASSERT(mHadBuildError);
  12243. continue;
  12244. }
  12245. if (fieldDef->mInitializer != NULL)
  12246. {
  12247. if (!hadInlineInitBlock)
  12248. {
  12249. if ((mBfIRBuilder->DbgHasInfo()) && (!mCurTypeInstance->IsUnspecializedType()) && (mHasFullDebugInfo))
  12250. {
  12251. UpdateSrcPos(baseCtorNode);
  12252. // 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
  12253. EmitEnsureInstructionAt();
  12254. BfType* thisType = mCurTypeInstance;
  12255. if (thisType->IsValueType())
  12256. thisType = CreateRefType(thisType);
  12257. SizedArray<BfIRMDNode, 1> diParamTypes;
  12258. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParamTypes);
  12259. mCurMethodState->AddScope(&scopeData);
  12260. NewScopeState();
  12261. int flags = 0;
  12262. mCurMethodState->mCurScope->mDIInlinedAt = mBfIRBuilder->DbgGetCurrentLocation();
  12263. BF_ASSERT(mCurMethodState->mCurScope->mDIInlinedAt);
  12264. // mCurMethodState->mCurScope->mDIInlinedAt may still be null ifwe don't have an explicit ctor
  12265. mCurMethodState->mCurScope->mDIScope = mBfIRBuilder->DbgCreateFunction(mBfIRBuilder->DbgGetTypeInst(mCurTypeInstance), "this$initFields", "", mCurFilePosition.mFileInstance->mDIFile,
  12266. mCurFilePosition.mCurLine + 1, diFuncType, false, true, mCurFilePosition.mCurLine + 1, flags, false, BfIRValue());
  12267. UpdateSrcPos(fieldDef->mInitializer);
  12268. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  12269. "this", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(thisType));
  12270. //
  12271. {
  12272. auto loadedThis = GetThis();
  12273. // LLVM can't handle two variables pointing to the same value
  12274. BfIRValue copiedThisPtr;
  12275. copiedThisPtr = CreateAlloca(thisType);
  12276. auto storeInst = mBfIRBuilder->CreateStore(loadedThis.mValue, copiedThisPtr);
  12277. mBfIRBuilder->ClearDebugLocation(storeInst);
  12278. mBfIRBuilder->DbgInsertDeclare(copiedThisPtr, diVariable);
  12279. }
  12280. hadInlineInitBlock = true;
  12281. }
  12282. }
  12283. UpdateSrcPos(fieldDef->mInitializer);
  12284. }
  12285. BfIRValue fieldAddr;
  12286. if ((!mCurTypeInstance->IsTypedPrimitive()) && (!fieldInst->mResolvedType->IsVar()))
  12287. {
  12288. fieldAddr = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, fieldInst->mDataIdx /*, fieldDef->mName*/);
  12289. }
  12290. else
  12291. {
  12292. AssertErrorState();
  12293. }
  12294. auto assignValue = GetFieldInitializerValue(fieldInst);
  12295. if ((fieldAddr) && (assignValue))
  12296. mBfIRBuilder->CreateStore(assignValue.mValue, fieldAddr);
  12297. }
  12298. }
  12299. if (hadInlineInitBlock)
  12300. {
  12301. RestoreScopeState();
  12302. // This gets set to false because of AddScope but we actually are still in the head block
  12303. mCurMethodState->mInHeadScope = true;
  12304. }
  12305. }
  12306. else // Autocomplete case
  12307. {
  12308. // The reason we can't just do the 'normal' path for this is that the BfTypeInstance here is NOT the
  12309. // autocomplete type instance, so FieldInstance initializer values contain expressions from the full
  12310. // resolve pass, NOT the autocomplete expression
  12311. for (auto tempTypeDef : mCompiler->mResolvePassData->mAutoCompleteTempTypes)
  12312. {
  12313. if (tempTypeDef->mFullName == typeDef->mFullName)
  12314. {
  12315. for (auto fieldDef : tempTypeDef->mFields)
  12316. {
  12317. if ((!fieldDef->mIsStatic) && (fieldDef->mInitializer != NULL) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  12318. {
  12319. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(fieldDef->mInitializer, BfSourceElementType_Normal);
  12320. mCompiler->mResolvePassData->mSourceClassifier->VisitChild(fieldDef->mInitializer);
  12321. auto wantType = ResolveTypeRef(fieldDef->mTypeRef);
  12322. if ((wantType != NULL) &&
  12323. ((wantType->IsVar()) || (wantType->IsLet()) || (wantType->IsRef())))
  12324. wantType = NULL;
  12325. CreateValueFromExpression(fieldDef->mInitializer, wantType, BfEvalExprFlags_FieldInitializer);
  12326. }
  12327. }
  12328. }
  12329. }
  12330. // Mark fields from full type with initializers as initialized, to give proper initialization errors within ctor
  12331. for (auto fieldDef : typeDef->mFields)
  12332. {
  12333. if ((!fieldDef->mIsConst) && (!fieldDef->mIsStatic) && (fieldDef->mInitializer != NULL))
  12334. {
  12335. auto fieldInst = &mCurTypeInstance->mFieldInstances[fieldDef->mIdx];
  12336. if (fieldDef->mInitializer != NULL)
  12337. MarkFieldInitialized(fieldInst);
  12338. }
  12339. }
  12340. }
  12341. }
  12342. // Call base ctor (if applicable)
  12343. BfTypeInstance* targetType = NULL;
  12344. BfAstNode* targetRefNode = NULL;
  12345. if (ctorDeclaration != NULL)
  12346. targetRefNode = ctorDeclaration->mInitializer;
  12347. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(targetRefNode))
  12348. targetRefNode = invocationExpr->mTarget;
  12349. if (baseCtorNode != NULL)
  12350. {
  12351. UpdateSrcPos(baseCtorNode);
  12352. }
  12353. if ((ctorDeclaration != NULL) && (ctorDeclaration->mInitializer != NULL))
  12354. {
  12355. auto targetToken = BfNodeDynCast<BfTokenNode>(ctorDeclaration->mInitializer->mTarget);
  12356. targetType = (targetToken->GetToken() == BfToken_This) ? mCurTypeInstance : mCurTypeInstance->mBaseType;
  12357. }
  12358. else if ((mCurTypeInstance->mBaseType != NULL) && (!mCurTypeInstance->IsUnspecializedType()))
  12359. {
  12360. auto baseType = mCurTypeInstance->mBaseType;
  12361. if ((!mCurTypeInstance->IsTypedPrimitive()) &&
  12362. (baseType->mTypeDef != mCompiler->mValueTypeTypeDef) &&
  12363. (baseType->mTypeDef != mCompiler->mBfObjectTypeDef))
  12364. {
  12365. // Try to find a ctor without any params first
  12366. bool foundBaseCtor = false;
  12367. bool hadCtorWithAllDefaults = false;
  12368. for (int pass = 0; pass < 2; pass++)
  12369. {
  12370. for (auto checkMethodDef : baseType->mTypeDef->mMethods)
  12371. {
  12372. bool allowPriv = checkMethodDef->mProtection != BfProtection_Private;
  12373. // Allow calling of the default base ctor if it is implicitly defined
  12374. if ((checkMethodDef->mMethodDeclaration == NULL) && (pass == 1) && (!hadCtorWithAllDefaults))
  12375. allowPriv = true;
  12376. if ((checkMethodDef->mMethodType == BfMethodType_Ctor) && (!checkMethodDef->mIsStatic) && (allowPriv))
  12377. {
  12378. if (checkMethodDef->mParams.size() == 0)
  12379. {
  12380. foundBaseCtor = true;
  12381. if (HasCompiledOutput())
  12382. {
  12383. SizedArray<BfIRValue, 1> args;
  12384. auto ctorBodyMethodInstance = GetMethodInstance(mCurTypeInstance->mBaseType, checkMethodDef, BfTypeVector());
  12385. if (!mCurTypeInstance->mBaseType->IsValuelessType())
  12386. {
  12387. auto basePtr = mBfIRBuilder->CreateBitCast(mCurMethodState->mLocals[0]->mValue, mBfIRBuilder->MapTypeInstPtr(mCurTypeInstance->mBaseType));
  12388. args.push_back(basePtr);
  12389. }
  12390. AddCallDependency(ctorBodyMethodInstance.mMethodInstance, true);
  12391. auto callInst = mBfIRBuilder->CreateCall(ctorBodyMethodInstance.mFunc, args);
  12392. auto callingConv = GetCallingConvention(ctorBodyMethodInstance.mMethodInstance->GetOwner(), ctorBodyMethodInstance.mMethodInstance->mMethodDef);
  12393. if (callingConv != BfIRCallingConv_CDecl)
  12394. mBfIRBuilder->SetCallCallingConv(callInst, callingConv);
  12395. // if (!mCurTypeInstance->mBaseType->IsValuelessType())
  12396. // mBfIRBuilder->SetCallCallingConv(callInst, BfIRCallingConv_ThisCall);
  12397. break;
  12398. }
  12399. }
  12400. else if ((checkMethodDef->mParams[0]->mParamDeclaration != NULL) && (checkMethodDef->mParams[0]->mParamDeclaration->mInitializer != NULL))
  12401. hadCtorWithAllDefaults = true;
  12402. }
  12403. }
  12404. if (foundBaseCtor)
  12405. break;
  12406. }
  12407. if (!foundBaseCtor)
  12408. {
  12409. targetType = mCurTypeInstance->mBaseType;
  12410. if (ctorDeclaration != NULL)
  12411. targetRefNode = ctorDeclaration->mThisToken;
  12412. else if (typeDef->mTypeDeclaration != NULL)
  12413. targetRefNode = typeDef->mTypeDeclaration->mNameNode;
  12414. }
  12415. }
  12416. }
  12417. if (methodDef->mHasAppend)
  12418. {
  12419. mCurMethodState->mCurAppendAlign = methodInstance->mAppendAllocAlign;
  12420. }
  12421. if (targetType != NULL)
  12422. {
  12423. auto autoComplete = mCompiler->GetAutoComplete();
  12424. auto wasCapturingMethodInfo = (autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo);
  12425. if ((autoComplete != NULL) && (ctorDeclaration != NULL) && (ctorDeclaration->mInitializer != NULL))
  12426. {
  12427. auto invocationExpr = ctorDeclaration->mInitializer;
  12428. autoComplete->CheckInvocation(invocationExpr, invocationExpr->mOpenParen, invocationExpr->mCloseParen, invocationExpr->mCommas);
  12429. }
  12430. BfType* targetThisType = targetType;
  12431. auto target = Cast(targetRefNode, GetThis(), targetThisType);
  12432. BfExprEvaluator exprEvaluator(this);
  12433. BfResolvedArgs argValues;
  12434. if ((ctorDeclaration != NULL) && (ctorDeclaration->mInitializer != NULL))
  12435. {
  12436. argValues.Init(&ctorDeclaration->mInitializer->mArguments);
  12437. if (gDebugStuff)
  12438. {
  12439. OutputDebugStrF("Expr: %@ %d\n", argValues.mArguments->mVals, argValues.mArguments->mSize);
  12440. }
  12441. }
  12442. exprEvaluator.ResolveArgValues(argValues, BfResolveArgFlag_DeferParamEval);
  12443. BfTypedValue appendIdxVal;
  12444. if (methodDef->mHasAppend)
  12445. {
  12446. auto localVar = mCurMethodState->GetRootMethodState()->mLocals[1];
  12447. BF_ASSERT(localVar->mName == "appendIdx");
  12448. auto intRefType = CreateRefType(localVar->mResolvedType);
  12449. appendIdxVal = BfTypedValue(localVar->mValue, intRefType);
  12450. mCurMethodState->mCurAppendAlign = 1; // Don't make any assumptions about how the base leaves the alignment
  12451. }
  12452. exprEvaluator.MatchConstructor(targetRefNode, NULL, target, targetType, argValues, true, methodDef->mHasAppend, &appendIdxVal);
  12453. if (autoComplete != NULL)
  12454. {
  12455. if ((wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo))
  12456. {
  12457. if (autoComplete->mMethodMatchInfo != NULL)
  12458. autoComplete->mIsCapturingMethodMatchInfo = true;
  12459. else
  12460. autoComplete->mIsCapturingMethodMatchInfo = false;
  12461. }
  12462. else
  12463. autoComplete->mIsCapturingMethodMatchInfo = false;
  12464. }
  12465. }
  12466. }
  12467. void BfModule::EmitEnumToStringBody()
  12468. {
  12469. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  12470. auto strVal = CreateAlloca(stringType);
  12471. auto int64StructType = GetPrimitiveStructType(BfTypeCode_Int64);
  12472. BfExprEvaluator exprEvaluator(this);
  12473. auto stringDestAddr = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  12474. BfIRBlock appendBlock = mBfIRBuilder->CreateBlock("append");
  12475. BfIRBlock noMatchBlock = mBfIRBuilder->CreateBlock("noMatch");
  12476. BfIRBlock endBlock = mBfIRBuilder->CreateBlock("end");
  12477. BfType* discriminatorType = NULL;
  12478. BfTypedValue rawPayload;
  12479. BfIRValue enumVal;
  12480. if (mCurTypeInstance->IsPayloadEnum())
  12481. {
  12482. discriminatorType = mCurTypeInstance->GetDiscriminatorType();
  12483. auto enumTypedValue = ExtractValue(GetThis(), NULL, 2);
  12484. enumTypedValue = LoadValue(enumTypedValue);
  12485. enumVal = enumTypedValue.mValue;
  12486. rawPayload = ExtractValue(GetThis(), NULL, 1);
  12487. }
  12488. else
  12489. enumVal = mBfIRBuilder->GetArgument(0);
  12490. Array<BfType*> paramTypes;
  12491. paramTypes.Add(stringType);
  12492. auto appendModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  12493. auto switchVal = mBfIRBuilder->CreateSwitch(enumVal, noMatchBlock, (int)mCurTypeInstance->mFieldInstances.size());
  12494. HashSet<int64> handledCases;
  12495. for (auto& fieldInstance : mCurTypeInstance->mFieldInstances)
  12496. {
  12497. if (fieldInstance.mIsEnumPayloadCase)
  12498. {
  12499. int tagId = -fieldInstance.mDataIdx - 1;
  12500. BfIRBlock caseBlock = mBfIRBuilder->CreateBlock("case");
  12501. mBfIRBuilder->AddBlock(caseBlock);
  12502. mBfIRBuilder->SetInsertPoint(caseBlock);
  12503. BF_ASSERT(discriminatorType->IsPrimitiveType());
  12504. auto constVal = mBfIRBuilder->CreateConst(((BfPrimitiveType*)discriminatorType)->mTypeDef->mTypeCode, tagId);
  12505. mBfIRBuilder->AddSwitchCase(switchVal, constVal, caseBlock);
  12506. auto caseStr = GetStringObjectValue(fieldInstance.GetFieldDef()->mName);
  12507. auto stringDestVal = LoadValue(stringDestAddr);
  12508. SizedArray<BfIRValue, 2> args;
  12509. args.Add(stringDestVal.mValue);
  12510. args.Add(caseStr);
  12511. exprEvaluator.CreateCall(appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  12512. auto payloadType = fieldInstance.mResolvedType->ToTypeInstance();
  12513. BF_ASSERT(payloadType->IsTuple());
  12514. if (payloadType->mFieldInstances.size() != 0)
  12515. {
  12516. auto payload = rawPayload;
  12517. if (payload.mType != payloadType)
  12518. {
  12519. payload = Cast(NULL, payload, payloadType, BfCastFlags_Force);
  12520. }
  12521. auto toStringMethod = GetMethodByName(payloadType->ToTypeInstance(), "ToString");
  12522. SizedArray<BfIRValue, 2> irArgs;
  12523. exprEvaluator.PushThis(NULL, payload, toStringMethod.mMethodInstance, irArgs);
  12524. stringDestVal = LoadValue(stringDestAddr);
  12525. irArgs.Add(stringDestVal.mValue);
  12526. exprEvaluator.CreateCall(toStringMethod.mMethodInstance, toStringMethod.mFunc, true, irArgs);
  12527. }
  12528. mBfIRBuilder->CreateBr(endBlock);
  12529. continue;
  12530. }
  12531. if (fieldInstance.mConstIdx == -1)
  12532. continue;
  12533. auto constant = mCurTypeInstance->mConstHolder->GetConstantById(fieldInstance.mConstIdx);
  12534. if (!handledCases.TryAdd(constant->mInt64, NULL))
  12535. {
  12536. // Duplicate
  12537. continue;
  12538. }
  12539. BfIRBlock caseBlock = mBfIRBuilder->CreateBlock("case");
  12540. mBfIRBuilder->AddBlock(caseBlock);
  12541. mBfIRBuilder->SetInsertPoint(caseBlock);
  12542. BfIRValue constVal = ConstantToCurrent(constant, mCurTypeInstance->mConstHolder, mCurTypeInstance);
  12543. mBfIRBuilder->AddSwitchCase(switchVal, constVal, caseBlock);
  12544. auto caseStr = GetStringObjectValue(fieldInstance.GetFieldDef()->mName);
  12545. mBfIRBuilder->CreateStore(caseStr, strVal);
  12546. mBfIRBuilder->CreateBr(appendBlock);
  12547. }
  12548. mBfIRBuilder->AddBlock(appendBlock);
  12549. mBfIRBuilder->SetInsertPoint(appendBlock);
  12550. SizedArray<BfIRValue, 2> args;
  12551. auto stringDestVal = LoadValue(stringDestAddr);
  12552. args.Add(stringDestVal.mValue);
  12553. args.Add(mBfIRBuilder->CreateLoad(strVal));
  12554. exprEvaluator.CreateCall(appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  12555. mBfIRBuilder->CreateBr(endBlock);
  12556. mBfIRBuilder->AddBlock(noMatchBlock);
  12557. mBfIRBuilder->SetInsertPoint(noMatchBlock);
  12558. auto int64Val = mBfIRBuilder->CreateNumericCast(enumVal, false, BfTypeCode_Int64);
  12559. auto toStringModuleMethodInstance = GetMethodByName(int64StructType, "ToString", 1);
  12560. args.clear();
  12561. args.Add(int64Val);
  12562. stringDestVal = LoadValue(stringDestAddr);
  12563. args.Add(stringDestVal.mValue);
  12564. exprEvaluator.CreateCall(toStringModuleMethodInstance.mMethodInstance, toStringModuleMethodInstance.mFunc, false, args);
  12565. mBfIRBuilder->CreateBr(endBlock);
  12566. mBfIRBuilder->AddBlock(endBlock);
  12567. mBfIRBuilder->SetInsertPoint(endBlock);
  12568. }
  12569. void BfModule::EmitTupleToStringBody()
  12570. {
  12571. auto stringType = ResolveTypeDef(mCompiler->mStringTypeDef);
  12572. BfExprEvaluator exprEvaluator(this);
  12573. auto stringDestRef = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  12574. Array<BfType*> paramTypes;
  12575. paramTypes.Add(GetPrimitiveType(BfTypeCode_Char8));
  12576. auto appendCharModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  12577. paramTypes.Clear();
  12578. paramTypes.Add(stringType);
  12579. auto appendModuleMethodInstance = GetMethodByName(stringType->ToTypeInstance(), "Append", paramTypes);
  12580. auto _AppendChar = [&](char c)
  12581. {
  12582. SizedArray<BfIRValue, 2> args;
  12583. auto stringDestVal = LoadValue(stringDestRef);
  12584. args.Add(stringDestVal.mValue);
  12585. args.Add(mBfIRBuilder->CreateConst(BfTypeCode_Char8, (int)c));
  12586. exprEvaluator.CreateCall(appendCharModuleMethodInstance.mMethodInstance, appendCharModuleMethodInstance.mFunc, false, args);
  12587. };
  12588. int fieldIdx = 0;
  12589. auto thisValue = GetThis();
  12590. auto toStringModuleMethodInstance = GetMethodByName(mContext->mBfObjectType, "ToString", 1);
  12591. auto toStringSafeModuleMethodInstance = GetMethodByName(mContext->mBfObjectType, "ToString", 2);
  12592. BfIRValue commaStr;
  12593. auto iPrintableType = ResolveTypeDef(mCompiler->mIPrintableTypeDef)->ToTypeInstance();
  12594. auto printModuleMethodInstance = GetMethodByName(iPrintableType, "Print");
  12595. _AppendChar('(');
  12596. for (auto& fieldInstance : mCurTypeInstance->mFieldInstances)
  12597. {
  12598. if (fieldInstance.mDataIdx == -1)
  12599. continue;
  12600. if (fieldIdx > 0)
  12601. {
  12602. if (!commaStr)
  12603. commaStr = GetStringObjectValue(", ");
  12604. SizedArray<BfIRValue, 2> args;
  12605. auto stringDestVal = LoadValue(stringDestRef);
  12606. args.Add(stringDestVal.mValue);
  12607. args.Add(commaStr);
  12608. exprEvaluator.CreateCall(appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  12609. }
  12610. fieldIdx++;
  12611. if (fieldInstance.mResolvedType->IsValuelessType())
  12612. continue;
  12613. BfTypedValue fieldValue = ExtractValue(thisValue, &fieldInstance, fieldInstance.mDataIdx);
  12614. if (fieldValue.mType->IsPrimitiveType())
  12615. {
  12616. fieldValue.mType = GetPrimitiveStructType(((BfPrimitiveType*)fieldValue.mType)->mTypeDef->mTypeCode);
  12617. }
  12618. auto typeInstance = fieldValue.mType->ToTypeInstance();
  12619. if ((typeInstance != NULL) && (TypeIsSubTypeOf(typeInstance, iPrintableType, false)))
  12620. {
  12621. BfExprEvaluator exprEvaluator(this);
  12622. SizedArray<BfResolvedArg, 0> resolvedArgs;
  12623. BfMethodMatcher methodMatcher(NULL, this, printModuleMethodInstance.mMethodInstance, resolvedArgs);
  12624. methodMatcher.mBestMethodDef = printModuleMethodInstance.mMethodInstance->mMethodDef;
  12625. methodMatcher.mBestMethodTypeInstance = iPrintableType;
  12626. methodMatcher.TryDevirtualizeCall(fieldValue);
  12627. BfTypedValue callVal = Cast(NULL, fieldValue, methodMatcher.mBestMethodTypeInstance);
  12628. BfResolvedArg resolvedArg;
  12629. auto stringDestVal = LoadValue(stringDestRef);
  12630. resolvedArg.mTypedValue = stringDestVal;
  12631. resolvedArg.mResolvedType = stringDestVal.mType;
  12632. resolvedArgs.Add(resolvedArg);
  12633. exprEvaluator.CreateCall(&methodMatcher, callVal);
  12634. continue;
  12635. }
  12636. if (fieldValue.mType->IsObjectOrInterface())
  12637. {
  12638. BF_ASSERT(!fieldValue.IsAddr());
  12639. SizedArray<BfIRValue, 2> args;
  12640. args.Add(mBfIRBuilder->CreateBitCast(fieldValue.mValue, mBfIRBuilder->MapType(mContext->mBfObjectType)));
  12641. auto stringDestVal = exprEvaluator.LoadLocal(mCurMethodState->mLocals[1]);
  12642. stringDestVal = LoadValue(stringDestVal);
  12643. args.Add(stringDestVal.mValue);
  12644. exprEvaluator.CreateCall(toStringSafeModuleMethodInstance.mMethodInstance, toStringSafeModuleMethodInstance.mFunc, false, args);
  12645. continue;
  12646. }
  12647. BfExprEvaluator exprEvaluator(this);
  12648. SizedArray<BfResolvedArg, 0> resolvedArgs;
  12649. BfMethodMatcher methodMatcher(NULL, this, toStringModuleMethodInstance.mMethodInstance, resolvedArgs);
  12650. methodMatcher.mBestMethodDef = toStringModuleMethodInstance.mMethodInstance->mMethodDef;
  12651. methodMatcher.mBestMethodTypeInstance = mContext->mBfObjectType;
  12652. methodMatcher.TryDevirtualizeCall(fieldValue);
  12653. if (methodMatcher.mBestMethodTypeInstance == mContext->mBfObjectType)
  12654. {
  12655. AddCallDependency(appendModuleMethodInstance.mMethodInstance);
  12656. AddDependency(fieldValue.mType, mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  12657. // Just append the type name
  12658. String typeName = TypeToString(fieldInstance.mResolvedType);
  12659. auto strVal = GetStringObjectValue(typeName);
  12660. SizedArray<BfIRValue, 2> args;
  12661. auto stringDestVal = LoadValue(stringDestRef);
  12662. args.Add(stringDestVal.mValue);
  12663. args.Add(strVal);
  12664. exprEvaluator.CreateCall(appendModuleMethodInstance.mMethodInstance, appendModuleMethodInstance.mFunc, false, args);
  12665. continue;
  12666. }
  12667. BfTypedValue callVal = Cast(NULL, fieldValue, methodMatcher.mBestMethodTypeInstance);
  12668. BfResolvedArg resolvedArg;
  12669. auto stringDestVal = LoadValue(stringDestRef);
  12670. resolvedArg.mTypedValue = stringDestVal;
  12671. resolvedArg.mResolvedType = stringDestVal.mType;
  12672. resolvedArgs.Add(resolvedArg);
  12673. exprEvaluator.CreateCall(&methodMatcher, callVal);
  12674. }
  12675. _AppendChar(')');
  12676. }
  12677. void BfModule::EmitIteratorBlock(bool& skipBody)
  12678. {
  12679. auto methodInstance = mCurMethodInstance;
  12680. auto methodDef = methodInstance->mMethodDef;
  12681. auto methodDeclaration = methodDef->GetMethodDeclaration();
  12682. auto typeDef = mCurTypeInstance->mTypeDef;
  12683. BfType* innerRetType = NULL;
  12684. BfTypeInstance* usingInterface = NULL;
  12685. auto retTypeInst = mCurMethodInstance->mReturnType->ToGenericTypeInstance();
  12686. if (retTypeInst != NULL)
  12687. {
  12688. if ((retTypeInst->mTypeDef == mCompiler->mGenericIEnumerableTypeDef) ||
  12689. (retTypeInst->mTypeDef == mCompiler->mGenericIEnumeratorTypeDef))
  12690. {
  12691. innerRetType = retTypeInst->mTypeGenericArguments[0];
  12692. }
  12693. }
  12694. if (innerRetType == NULL)
  12695. {
  12696. Fail("Methods with yields must return either System.IEnumerable<T> or System.IEnumerator<T>", methodDeclaration->mReturnType);
  12697. return;
  12698. }
  12699. auto blockBody = BfNodeDynCast<BfBlock>(methodDeclaration->mBody);
  12700. if (blockBody == NULL)
  12701. return;
  12702. }
  12703. void BfModule::EmitGCMarkValue(BfTypedValue markVal, BfModuleMethodInstance markFromGCThreadMethodInstance)
  12704. {
  12705. auto fieldTypeInst = markVal.mType->ToTypeInstance();
  12706. if (fieldTypeInst == NULL)
  12707. return;
  12708. if (!markVal.mType->IsComposite())
  12709. markVal = LoadValue(markVal);
  12710. BfExprEvaluator exprEvaluator(this);
  12711. PopulateType(markVal.mType, BfPopulateType_Data);
  12712. if (markVal.mType->IsObjectOrInterface())
  12713. {
  12714. BfIRValue val = markVal.mValue;
  12715. val = mBfIRBuilder->CreateBitCast(val, mBfIRBuilder->MapType(mContext->mBfObjectType));
  12716. SizedArray<BfIRValue, 1> args;
  12717. args.push_back(val);
  12718. exprEvaluator.CreateCall(markFromGCThreadMethodInstance.mMethodInstance, markFromGCThreadMethodInstance.mFunc, false, args);
  12719. }
  12720. else if ((fieldTypeInst->IsComposite()) && (!fieldTypeInst->IsTypedPrimitive()))
  12721. {
  12722. auto markMemberMethodInstance = GetMethodByName(fieldTypeInst, BF_METHODNAME_MARKMEMBERS, 0, true);
  12723. if (markMemberMethodInstance)
  12724. {
  12725. SizedArray<BfIRValue, 1> args;
  12726. //(1, markVal.mValue);
  12727. //exprEvaluator.PushArg(markVal, args);
  12728. exprEvaluator.PushThis(NULL, markVal, markMemberMethodInstance.mMethodInstance, args);
  12729. exprEvaluator.CreateCall(markMemberMethodInstance.mMethodInstance, markMemberMethodInstance.mFunc, false, args);
  12730. }
  12731. }
  12732. }
  12733. void BfModule::CallChainedMethods(BfMethodInstance* methodInstance, bool reverse)
  12734. {
  12735. Array<BfMethodInstance*> methodInstances;
  12736. for (int methodIdx = 0; methodIdx < (int)mCurTypeInstance->mMethodInstanceGroups.size(); methodIdx++)
  12737. {
  12738. auto& methodInstGroup = mCurTypeInstance->mMethodInstanceGroups[methodIdx];
  12739. auto chainedMethodInst = methodInstGroup.mDefault;
  12740. if ((chainedMethodInst != NULL) && (chainedMethodInst->mChainType == BfMethodChainType_ChainMember))
  12741. {
  12742. if ((chainedMethodInst->mMethodDef->mIsStatic == methodInstance->mMethodDef->mIsStatic) &&
  12743. (CompareMethodSignatures(methodInstance, chainedMethodInst)))
  12744. {
  12745. methodInstances.push_back(chainedMethodInst);
  12746. }
  12747. }
  12748. }
  12749. std::stable_sort(methodInstances.begin(), methodInstances.end(),
  12750. [&](BfMethodInstance* lhs, BfMethodInstance* rhs)
  12751. {
  12752. bool isBetter;
  12753. bool isWorse;
  12754. CompareDeclTypes(lhs->mMethodDef->mDeclaringType, rhs->mMethodDef->mDeclaringType, isBetter, isWorse);
  12755. if (isBetter == isWorse)
  12756. {
  12757. return false;
  12758. }
  12759. return isWorse;
  12760. });
  12761. if (reverse)
  12762. std::reverse(methodInstances.begin(), methodInstances.end());
  12763. for (auto chainedMethodInst : methodInstances)
  12764. {
  12765. auto declModule = this;
  12766. BfGetMethodInstanceFlags flags = BfGetMethodInstanceFlag_None;
  12767. auto moduleMethodInst = declModule->GetMethodInstance(mCurTypeInstance, chainedMethodInst->mMethodDef, BfTypeVector(), flags);
  12768. BfExprEvaluator exprEvaluator(this);
  12769. SizedArray<BfIRValue, 1> args;
  12770. exprEvaluator.PushThis(chainedMethodInst->mMethodDef->GetRefNode(), GetThis(), chainedMethodInst, args);
  12771. exprEvaluator.CreateCall(moduleMethodInst.mMethodInstance, moduleMethodInst.mFunc, true, args);
  12772. }
  12773. }
  12774. void BfModule::AddHotDataReferences(BfHotDataReferenceBuilder* builder)
  12775. {
  12776. BF_ASSERT(mCurMethodInstance->mIsReified);
  12777. if (mCurTypeInstance->mHotTypeData == NULL)
  12778. mCurTypeInstance->mHotTypeData = new BfHotTypeData();
  12779. auto hotMethod = mCurMethodInstance->mHotMethod;
  12780. for (auto depData : hotMethod->mReferences)
  12781. {
  12782. // Only virtual decls are allowed to already be there
  12783. BF_ASSERT((depData->mDataKind == BfHotDepDataKind_VirtualDecl) || (depData->mDataKind == BfHotDepDataKind_DupMethod));
  12784. }
  12785. BF_ASSERT(hotMethod->mSrcTypeVersion != NULL);
  12786. int prevSize = (int)hotMethod->mReferences.size();
  12787. int refCount = (int)(prevSize + builder->mUsedData.size() + builder->mCalledMethods.size() + builder->mDevirtualizedCalledMethods.size());
  12788. if (!mCurMethodInstance->mMethodDef->mIsStatic)
  12789. refCount++;
  12790. hotMethod->mReferences.Reserve(refCount);
  12791. if (!mCurMethodInstance->mMethodDef->mIsStatic)
  12792. {
  12793. auto hotThis = mCompiler->mHotData->GetThisType(mCurMethodInstance->GetOwner()->mHotTypeData->GetLatestVersion());
  12794. hotThis->mRefCount++;
  12795. hotMethod->mReferences.Insert(0, hotThis);
  12796. prevSize++;
  12797. }
  12798. for (auto val : builder->mAllocatedData)
  12799. {
  12800. auto hotAllocation = mCompiler->mHotData->GetAllocation(val);
  12801. hotMethod->mReferences.Add(hotAllocation);
  12802. }
  12803. for (auto val : builder->mUsedData)
  12804. hotMethod->mReferences.Add(val);
  12805. for (auto val : builder->mCalledMethods)
  12806. hotMethod->mReferences.Add(val);
  12807. for (auto val : builder->mDevirtualizedCalledMethods)
  12808. {
  12809. auto devirtualizedMethod = mCompiler->mHotData->GetDevirtualizedMethod(val);
  12810. hotMethod->mReferences.Add(devirtualizedMethod);
  12811. }
  12812. for (auto val : builder->mFunctionPtrs)
  12813. {
  12814. auto funcRef = mCompiler->mHotData->GetFunctionReference(val);
  12815. hotMethod->mReferences.Add(funcRef);
  12816. }
  12817. for (auto val : builder->mInnerMethods)
  12818. {
  12819. auto innerMethod = mCompiler->mHotData->GetInnerMethod(val);
  12820. hotMethod->mReferences.Add(innerMethod);
  12821. }
  12822. for (int refIdx = prevSize; refIdx < (int)hotMethod->mReferences.size(); refIdx++)
  12823. {
  12824. auto depData = hotMethod->mReferences[refIdx];
  12825. BF_ASSERT(depData != NULL);
  12826. depData->mRefCount++;
  12827. }
  12828. //hotMethod->mReferences.Sort([](BfHotDepData* lhs, BfHotDepData* rhs) { return lhs < rhs; });
  12829. }
  12830. void BfModule::ProcessMethod_SetupParams(BfMethodInstance* methodInstance, BfType* thisType, bool wantsDIData, SizedArrayImpl<BfIRMDNode>* diParams)
  12831. {
  12832. auto methodDef = methodInstance->mMethodDef;
  12833. auto methodDeclaration = methodDef->mMethodDeclaration;
  12834. bool isThisStruct = false;
  12835. if (thisType != NULL)
  12836. isThisStruct = thisType->IsStruct() && !thisType->IsTypedPrimitive();
  12837. int argIdx = 0;
  12838. if (methodInstance->HasStructRet())
  12839. argIdx++;
  12840. if (!methodDef->mIsStatic)
  12841. {
  12842. BfLocalVariable* paramVar = new BfLocalVariable();
  12843. paramVar->mResolvedType = thisType;
  12844. paramVar->mName = "this";
  12845. if (!thisType->IsValuelessType())
  12846. paramVar->mValue = mBfIRBuilder->GetArgument(argIdx);
  12847. else
  12848. paramVar->mValue = mBfIRBuilder->GetFakeVal();
  12849. if ((thisType->IsComposite()) && (!methodDef->HasNoThisSplat()))
  12850. {
  12851. if (thisType->IsSplattable())
  12852. paramVar->mIsSplat = true;
  12853. else
  12854. paramVar->mIsLowered = thisType->GetLoweredType() != BfTypeCode_None;
  12855. }
  12856. auto thisTypeInst = thisType->ToTypeInstance();
  12857. paramVar->mIsStruct = isThisStruct;
  12858. paramVar->mAddr = BfIRValue();
  12859. paramVar->mIsThis = true;
  12860. paramVar->mParamIdx = -1;
  12861. if ((methodDef->mMethodType == BfMethodType_Ctor) && (mCurTypeInstance->IsStruct()))
  12862. {
  12863. paramVar->mIsAssigned = false;
  12864. }
  12865. else
  12866. {
  12867. paramVar->mIsAssigned = true;
  12868. }
  12869. paramVar->mReadFromId = -1;
  12870. paramVar->Init();
  12871. if (methodDeclaration == NULL)
  12872. UseDefaultSrcPos();
  12873. AddLocalVariableDef(paramVar);
  12874. if (!thisType->IsValuelessType())
  12875. {
  12876. if (wantsDIData)
  12877. {
  12878. BfType* thisPtrType = thisType;
  12879. auto diType = mBfIRBuilder->DbgGetType(thisPtrType);
  12880. if (!thisType->IsValueType())
  12881. diType = mBfIRBuilder->DbgCreateArtificialType(diType);
  12882. diParams->push_back(diType);
  12883. }
  12884. if (paramVar->mIsSplat)
  12885. {
  12886. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  12887. }
  12888. else
  12889. {
  12890. argIdx++;
  12891. }
  12892. }
  12893. }
  12894. bool hadParams = false;
  12895. bool hasDefault = false;
  12896. int compositeVariableIdx = -1;
  12897. int paramIdx = 0;
  12898. for (paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  12899. {
  12900. // We already issues a type error for this param if we had one in declaration processing
  12901. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  12902. BfLocalVariable* paramVar = new BfLocalVariable();
  12903. bool isParamSkipped = methodInstance->IsParamSkipped(paramIdx);
  12904. BfType* unresolvedType = methodInstance->GetParamType(paramIdx, false);
  12905. if (unresolvedType == NULL)
  12906. {
  12907. AssertErrorState();
  12908. unresolvedType = mContext->mBfObjectType;
  12909. paramVar->mParamFailed = true;
  12910. }
  12911. auto resolvedType = methodInstance->GetParamType(paramIdx, true);
  12912. prevIgnoreErrors.Restore();
  12913. PopulateType(resolvedType, BfPopulateType_Declaration);
  12914. paramVar->mResolvedType = resolvedType;
  12915. paramVar->mName = methodInstance->GetParamName(paramIdx);
  12916. paramVar->mNameNode = methodInstance->GetParamNameNode(paramIdx);
  12917. if (!isParamSkipped)
  12918. {
  12919. paramVar->mValue = mBfIRBuilder->GetArgument(argIdx);
  12920. if (resolvedType->IsMethodRef())
  12921. {
  12922. paramVar->mIsSplat = true;
  12923. }
  12924. else if (resolvedType->IsComposite() && resolvedType->IsSplattable())
  12925. {
  12926. int splatCount = resolvedType->GetSplatCount();
  12927. if (argIdx + splatCount <= mCompiler->mOptions.mMaxSplatRegs)
  12928. paramVar->mIsSplat = true;
  12929. }
  12930. }
  12931. else
  12932. {
  12933. paramVar->mIsSplat = true; // Treat skipped (valueless) as a splat
  12934. paramVar->mValue = mBfIRBuilder->GetFakeVal();
  12935. }
  12936. paramVar->mIsLowered = resolvedType->GetLoweredType() != BfTypeCode_None;
  12937. paramVar->mIsStruct = resolvedType->IsComposite() && !resolvedType->IsTypedPrimitive();
  12938. paramVar->mParamIdx = paramIdx;
  12939. paramVar->mIsImplicitParam = methodInstance->IsImplicitCapture(paramIdx);
  12940. paramVar->mReadFromId = 0;
  12941. if (resolvedType->IsRef())
  12942. {
  12943. auto refType = (BfRefType*)resolvedType;
  12944. paramVar->mIsAssigned = refType->mRefKind != BfRefType::RefKind_Out;
  12945. }
  12946. else
  12947. {
  12948. paramVar->mIsAssigned = true;
  12949. if (methodDef->mMethodType != BfMethodType_Mixin)
  12950. paramVar->mIsReadOnly = true;
  12951. }
  12952. if (paramVar->mResolvedType->IsGenericParam())
  12953. {
  12954. auto genericParamInst = GetGenericParamInstance((BfGenericParamType*)paramVar->mResolvedType);
  12955. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  12956. {
  12957. auto typedVal = GetDefaultTypedValue(genericParamInst->mTypeConstraint, false, BfDefaultValueKind_Undef);
  12958. paramVar->mResolvedType = typedVal.mType;
  12959. paramVar->mConstValue = typedVal.mValue;
  12960. }
  12961. }
  12962. if (paramVar->mResolvedType->IsConstExprValue())
  12963. {
  12964. BfConstExprValueType* constExprValueType = (BfConstExprValueType*)paramVar->mResolvedType;
  12965. auto unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance);
  12966. auto unspecParamType = unspecializedMethodInstance->GetParamType(paramIdx);
  12967. BF_ASSERT(unspecParamType->IsGenericParam());
  12968. if (unspecParamType->IsGenericParam())
  12969. {
  12970. BfGenericParamType* genericParamType = (BfGenericParamType*)unspecParamType;
  12971. if (genericParamType->mGenericParamKind == BfGenericParamKind_Method)
  12972. {
  12973. auto genericParamInst = unspecializedMethodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  12974. if (genericParamInst->mTypeConstraint != NULL)
  12975. {
  12976. BfExprEvaluator exprEvaluator(this);
  12977. exprEvaluator.mExpectingType = genericParamInst->mTypeConstraint;
  12978. exprEvaluator.GetLiteral(NULL, constExprValueType->mValue);
  12979. auto checkType = genericParamInst->mTypeConstraint;
  12980. if (checkType->IsTypedPrimitive())
  12981. checkType = checkType->GetUnderlyingType();
  12982. if (exprEvaluator.mResult.mType == checkType)
  12983. {
  12984. paramVar->mResolvedType = genericParamInst->mTypeConstraint;
  12985. paramVar->mConstValue = exprEvaluator.mResult.mValue;
  12986. BF_ASSERT(paramVar->mConstValue.IsConst());
  12987. }
  12988. else
  12989. {
  12990. AssertErrorState();
  12991. paramVar->mResolvedType = genericParamInst->mTypeConstraint;
  12992. paramVar->mConstValue = GetDefaultValue(genericParamInst->mTypeConstraint);
  12993. }
  12994. }
  12995. }
  12996. }
  12997. //BF_ASSERT(!paramVar->mResolvedType->IsConstExprValue());
  12998. if (paramVar->mResolvedType->IsConstExprValue())
  12999. {
  13000. Fail("Invalid use of constant expression", methodInstance->GetParamTypeRef(paramIdx));
  13001. //AssertErrorState();
  13002. paramVar->mResolvedType = GetPrimitiveType(BfTypeCode_IntPtr);
  13003. paramVar->mConstValue = GetDefaultValue(paramVar->mResolvedType);
  13004. }
  13005. }
  13006. if (methodInstance->GetParamKind(paramIdx) == BfParamKind_DelegateParam)
  13007. {
  13008. if (compositeVariableIdx == -1)
  13009. {
  13010. compositeVariableIdx = (int)mCurMethodState->mLocals.size();
  13011. BfLocalVariable* localVar = new BfLocalVariable();
  13012. auto paramInst = &methodInstance->mParams[paramIdx];
  13013. auto paramDef = methodDef->mParams[paramInst->mParamDefIdx];
  13014. localVar->mName = paramDef->mName;
  13015. localVar->mResolvedType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_NoResolveGenericParam);
  13016. localVar->mCompositeCount = 0;
  13017. DoAddLocalVariable(localVar);
  13018. }
  13019. mCurMethodState->mLocals[compositeVariableIdx]->mCompositeCount++;
  13020. }
  13021. CheckVariableDef(paramVar);
  13022. paramVar->Init();
  13023. AddLocalVariableDef(paramVar);
  13024. if (!isParamSkipped)
  13025. {
  13026. if (wantsDIData)
  13027. diParams->push_back(mBfIRBuilder->DbgGetType(resolvedType));
  13028. if (paramVar->mIsSplat)
  13029. {
  13030. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  13031. }
  13032. else
  13033. {
  13034. argIdx++;
  13035. }
  13036. }
  13037. }
  13038. // Try to find an ending delegate params composite
  13039. if ((compositeVariableIdx == -1) && (methodDef->mParams.size() > 0))
  13040. {
  13041. auto paramDef = methodDef->mParams.back();
  13042. if (paramDef->mParamKind == BfParamKind_Params)
  13043. {
  13044. auto paramsType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_NoResolveGenericParam);
  13045. if (paramsType == NULL)
  13046. {
  13047. AssertErrorState();
  13048. }
  13049. else if (paramsType->IsGenericParam())
  13050. {
  13051. auto genericParamInstance = GetGenericParamInstance((BfGenericParamType*)paramsType);
  13052. if (genericParamInstance->mTypeConstraint != NULL)
  13053. {
  13054. auto typeInstConstraint = genericParamInstance->mTypeConstraint->ToTypeInstance();
  13055. if ((genericParamInstance->mTypeConstraint->IsDelegate()) || (genericParamInstance->mTypeConstraint->IsFunction()) ||
  13056. ((typeInstConstraint != NULL) &&
  13057. ((typeInstConstraint->mTypeDef == mCompiler->mDelegateTypeDef) || (typeInstConstraint->mTypeDef == mCompiler->mFunctionTypeDef))))
  13058. {
  13059. BfLocalVariable* localVar = new BfLocalVariable();
  13060. localVar->mName = paramDef->mName;
  13061. localVar->mResolvedType = paramsType;
  13062. localVar->mCompositeCount = 0;
  13063. DoAddLocalVariable(localVar);
  13064. }
  13065. }
  13066. }
  13067. else if (paramsType->IsDelegate())
  13068. {
  13069. BfMethodInstance* invokeMethodInstance = GetRawMethodInstanceAtIdx(paramsType->ToTypeInstance(), 0, "Invoke");
  13070. if (invokeMethodInstance != NULL)
  13071. {
  13072. // This is only for the case where the delegate didn't actually have any params so the composite is zero-sized
  13073. // and wasn't cleared by the preceding loop
  13074. BF_ASSERT(invokeMethodInstance->GetParamCount() == 0);
  13075. BfLocalVariable* localVar = new BfLocalVariable();
  13076. localVar->mName = paramDef->mName;
  13077. localVar->mResolvedType = paramsType;
  13078. localVar->mCompositeCount = 0;
  13079. DoAddLocalVariable(localVar);
  13080. }
  13081. }
  13082. }
  13083. }
  13084. }
  13085. void BfModule::ProcessMethod_ProcessDeferredLocals(int startIdx)
  13086. {
  13087. // if (mCurMethodState->mPrevMethodState != NULL) // Re-entry
  13088. // return;
  13089. auto _ClearState = [&]()
  13090. {
  13091. mCurMethodState->mLocalMethods.Clear();
  13092. for (auto& local : mCurMethodState->mLocals)
  13093. delete local;
  13094. mCurMethodState->mLocals.Clear();
  13095. mCurMethodState->mLocalVarSet.Clear();
  13096. };
  13097. // 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
  13098. // we show errors in the capture phase. If we somehow pass the capture phase without error then this method WILL show any errors here,
  13099. // however (compiler bug), so this is the safest way
  13100. if (!mCurMethodState->mDeferredLocalMethods.IsEmpty())
  13101. {
  13102. for (int deferredLocalMethodIdx = 0; deferredLocalMethodIdx < (int)mCurMethodState->mDeferredLocalMethods.size(); deferredLocalMethodIdx++)
  13103. {
  13104. auto deferredLocalMethod = mCurMethodState->mDeferredLocalMethods[deferredLocalMethodIdx];
  13105. BfLogSysM("Processing deferred local method %p\n", deferredLocalMethod);
  13106. if (!mHadBuildError)
  13107. {
  13108. // Process as a closure - that allows us to look back and see the const locals and stuff
  13109. BfClosureState closureState;
  13110. mCurMethodState->mClosureState = &closureState;
  13111. closureState.mConstLocals = deferredLocalMethod->mConstLocals;
  13112. closureState.mReturnType = deferredLocalMethod->mMethodInstance->mReturnType;
  13113. closureState.mActiveDeferredLocalMethod = deferredLocalMethod;
  13114. closureState.mLocalMethod = deferredLocalMethod->mLocalMethod;
  13115. if (deferredLocalMethod->mMethodInstance->mMethodInfoEx != NULL)
  13116. closureState.mClosureInstanceInfo = deferredLocalMethod->mMethodInstance->mMethodInfoEx->mClosureInstanceInfo;
  13117. mCurMethodState->mMixinState = deferredLocalMethod->mLocalMethod->mDeclMixinState;
  13118. _ClearState();
  13119. for (auto& constLocal : deferredLocalMethod->mConstLocals)
  13120. {
  13121. auto localVar = new BfLocalVariable();
  13122. *localVar = constLocal;
  13123. DoAddLocalVariable(localVar);
  13124. }
  13125. mCurMethodState->mLocalMethods = deferredLocalMethod->mLocalMethods;
  13126. bool doProcess = !mCompiler->mCanceling;
  13127. if (doProcess)
  13128. {
  13129. BP_ZONE_F("ProcessMethod local %s", deferredLocalMethod->mMethodInstance->mMethodDef->mName.c_str());
  13130. ProcessMethod(deferredLocalMethod->mMethodInstance);
  13131. }
  13132. }
  13133. delete deferredLocalMethod;
  13134. mSystem->CheckLockYield();
  13135. }
  13136. }
  13137. for (auto& kv : mCurMethodState->mLocalMethodCache)
  13138. {
  13139. BF_ASSERT((kv.mValue->mMethodDef == NULL) || (kv.mKey == kv.mValue->mMethodDef->mName));
  13140. }
  13141. if ((!mCurMethodState->mDeferredLambdaInstances.IsEmpty()) && (!mHadBuildError))
  13142. {
  13143. for (int deferredLambdaIdx = 0; deferredLambdaIdx < (int)mCurMethodState->mDeferredLambdaInstances.size(); deferredLambdaIdx++)
  13144. {
  13145. auto lambdaInstance = mCurMethodState->mDeferredLambdaInstances[deferredLambdaIdx];
  13146. BfLogSysM("Processing deferred lambdaInstance %p\n", lambdaInstance);
  13147. BfClosureState closureState;
  13148. mCurMethodState->mClosureState = &closureState;
  13149. //closureState.mConstLocals = deferredLocalMethod->mConstLocals;
  13150. closureState.mReturnType = lambdaInstance->mMethodInstance->mReturnType;
  13151. if (lambdaInstance->mClosureTypeInstance != NULL)
  13152. closureState.mClosureType = lambdaInstance->mClosureTypeInstance;
  13153. else
  13154. closureState.mClosureType = lambdaInstance->mDelegateTypeInstance;
  13155. closureState.mClosureInstanceInfo = lambdaInstance->mMethodInstance->mMethodInfoEx->mClosureInstanceInfo;
  13156. mCurMethodState->mMixinState = lambdaInstance->mDeclMixinState;
  13157. _ClearState();
  13158. for (auto& constLocal : lambdaInstance->mConstLocals)
  13159. {
  13160. //if (constLocal.mIsThis)
  13161. {
  13162. // Valueless 'this'
  13163. closureState.mConstLocals.Add(constLocal);
  13164. }
  13165. /*else
  13166. {
  13167. auto localVar = new BfLocalVariable();
  13168. *localVar = constLocal;
  13169. DoAddLocalVariable(localVar);
  13170. }*/
  13171. }
  13172. BfMethodInstanceGroup methodInstanceGroup;
  13173. methodInstanceGroup.mOwner = mCurTypeInstance;
  13174. methodInstanceGroup.mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  13175. bool doProcess = !mCompiler->mCanceling;
  13176. if (doProcess)
  13177. {
  13178. BP_ZONE_F("ProcessMethod lambdaInstance %s", lambdaInstance->mMethodInstance->mMethodDef->mName.c_str());
  13179. lambdaInstance->mMethodInstance->mMethodInstanceGroup = &methodInstanceGroup;
  13180. ProcessMethod(lambdaInstance->mMethodInstance);
  13181. if (lambdaInstance->mDtorMethodInstance != NULL)
  13182. {
  13183. lambdaInstance->mDtorMethodInstance->mMethodInstanceGroup = &methodInstanceGroup;
  13184. ProcessMethod(lambdaInstance->mDtorMethodInstance);
  13185. }
  13186. }
  13187. }
  13188. mSystem->CheckLockYield();
  13189. }
  13190. }
  13191. void BfModule::EmitGCMarkValue(BfTypedValue& thisValue, BfType* checkType, int memberDepth, int curOffset, HashSet<int>& objectOffsets, BfModuleMethodInstance markFromGCThreadMethodInstance)
  13192. {
  13193. if (checkType->IsComposite())
  13194. PopulateType(checkType, BfPopulateType_Data);
  13195. if (!checkType->WantsGCMarking())
  13196. return;
  13197. auto typeInstance = checkType->ToTypeInstance();
  13198. bool callMarkMethod = false;
  13199. // Call the actual marking method
  13200. if (memberDepth == 0)
  13201. {
  13202. // Don't call marking method on self
  13203. }
  13204. else if (checkType->IsObjectOrInterface())
  13205. {
  13206. if (!objectOffsets.Add(curOffset))
  13207. {
  13208. return;
  13209. }
  13210. callMarkMethod = true;
  13211. }
  13212. else if (checkType->IsSizedArray())
  13213. {
  13214. callMarkMethod = true;
  13215. }
  13216. else if (typeInstance != NULL)
  13217. {
  13218. typeInstance->mTypeDef->PopulateMemberSets();
  13219. BfMemberSetEntry* entry = NULL;
  13220. BfMethodDef* methodDef = NULL;
  13221. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(String(BF_METHODNAME_MARKMEMBERS), &entry))
  13222. {
  13223. methodDef = (BfMethodDef*)entry->mMemberDef;
  13224. if (methodDef->HasBody())
  13225. {
  13226. callMarkMethod = true;
  13227. }
  13228. }
  13229. }
  13230. if (callMarkMethod)
  13231. {
  13232. BfTypedValue markValue;
  13233. auto memberType = checkType;
  13234. if (memberType->IsObjectOrInterface())
  13235. memberType = mContext->mBfObjectType; // Just to avoid that extra cast for the call itself
  13236. auto memberPtrType = CreatePointerType(memberType);
  13237. if (curOffset == 0)
  13238. {
  13239. markValue = BfTypedValue(mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(memberPtrType)), memberType, true);
  13240. }
  13241. else
  13242. {
  13243. if (!thisValue.mType->IsPointer())
  13244. {
  13245. auto int8Type = GetPrimitiveType(BfTypeCode_UInt8);
  13246. auto int8PtrType = CreatePointerType(int8Type);
  13247. thisValue = BfTypedValue(mBfIRBuilder->CreateBitCast(thisValue.mValue, mBfIRBuilder->MapType(int8PtrType)), int8PtrType);
  13248. }
  13249. auto offsetValue = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, curOffset);
  13250. markValue = BfTypedValue(mBfIRBuilder->CreateBitCast(offsetValue, mBfIRBuilder->MapType(memberPtrType)), memberType, true);
  13251. }
  13252. EmitGCMarkValue(markValue, markFromGCThreadMethodInstance);
  13253. return;
  13254. }
  13255. auto methodDef = mCurMethodInstance->mMethodDef;
  13256. if (checkType->IsPayloadEnum())
  13257. {
  13258. for (auto& fieldInst : typeInstance->mFieldInstances)
  13259. {
  13260. if (!fieldInst.mIsEnumPayloadCase)
  13261. continue;
  13262. auto fieldDef = fieldInst.GetFieldDef();
  13263. EmitGCMarkValue(thisValue, fieldInst.mResolvedType, memberDepth + 1, curOffset, objectOffsets, markFromGCThreadMethodInstance);
  13264. }
  13265. return;
  13266. }
  13267. if (typeInstance == NULL)
  13268. return;
  13269. for (auto& fieldInst : typeInstance->mFieldInstances)
  13270. {
  13271. auto fieldDef = fieldInst.GetFieldDef();
  13272. if (fieldDef == NULL)
  13273. continue;
  13274. if (fieldDef->mIsStatic)
  13275. continue;
  13276. if (typeInstance == mCurTypeInstance)
  13277. {
  13278. // Note: we don't do method chaining when we are marking members of members. Theoretically this means
  13279. // we may be marking member values that can never contain a value anyway, but this is benign
  13280. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  13281. continue;
  13282. }
  13283. EmitGCMarkValue(thisValue, fieldInst.mResolvedType, memberDepth + 1, curOffset + fieldInst.mDataOffset, objectOffsets, markFromGCThreadMethodInstance);
  13284. }
  13285. if ((typeInstance->mBaseType != NULL) && (typeInstance->mBaseType != mContext->mBfObjectType))
  13286. {
  13287. EmitGCMarkValue(thisValue, typeInstance->mBaseType, memberDepth, curOffset, objectOffsets, markFromGCThreadMethodInstance);
  13288. }
  13289. }
  13290. void BfModule::EmitGCMarkMembers()
  13291. {
  13292. auto methodDef = mCurMethodInstance->mMethodDef;
  13293. auto gcType = ResolveTypeDef(mCompiler->mGCTypeDef, BfPopulateType_DataAndMethods);
  13294. BfModuleMethodInstance markFromGCThreadMethodInstance;
  13295. if (gcType != NULL)
  13296. markFromGCThreadMethodInstance = GetMethodByName(gcType->ToTypeInstance(), "Mark", 1);
  13297. if ((markFromGCThreadMethodInstance.mMethodInstance != NULL) && (!mCurMethodInstance->mIsUnspecialized))
  13298. {
  13299. if (mCurTypeInstance->IsBoxed())
  13300. {
  13301. // This already gets filled in by the normal boxed forwarding
  13302. }
  13303. else
  13304. {
  13305. auto thisValue = GetThis();
  13306. if (thisValue.IsSplat())
  13307. {
  13308. BfIRFunction func = mCurMethodInstance->mIRFunction;
  13309. int argIdx = 0;
  13310. std::function<void(BfType*)> checkTypeLambda = [&](BfType* checkType)
  13311. {
  13312. if (checkType->IsStruct())
  13313. {
  13314. auto checkTypeInstance = checkType->ToTypeInstance();
  13315. if (checkTypeInstance->mBaseType != NULL)
  13316. checkTypeLambda(checkTypeInstance->mBaseType);
  13317. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  13318. {
  13319. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  13320. if (fieldInstance->mDataIdx >= 0)
  13321. checkTypeLambda(fieldInstance->GetResolvedType());
  13322. }
  13323. }
  13324. else if (checkType->IsMethodRef())
  13325. {
  13326. BF_FATAL("Not handled");
  13327. }
  13328. else if (checkType->WantsGCMarking())
  13329. {
  13330. BfTypedValue markValue(mBfIRBuilder->GetArgument(argIdx), checkType);
  13331. EmitGCMarkValue(markValue, markFromGCThreadMethodInstance);
  13332. argIdx++;
  13333. }
  13334. };
  13335. checkTypeLambda(thisValue.mType);
  13336. }
  13337. else if (!methodDef->mIsStatic)
  13338. {
  13339. if ((mCurTypeInstance->mBaseType != NULL) && (!mCurTypeInstance->IsTypedPrimitive()) && (mCurTypeInstance->mBaseType->WantsGCMarking()))
  13340. {
  13341. BfModuleMethodInstance moduleMethodInst = GetMethodByName(mCurTypeInstance->mBaseType, BF_METHODNAME_MARKMEMBERS, 0, true);
  13342. if (moduleMethodInst)
  13343. {
  13344. auto methodBaseType = moduleMethodInst.mMethodInstance->GetOwner();
  13345. if (methodBaseType != mContext->mBfObjectType)
  13346. {
  13347. auto thisValue = GetThis();
  13348. auto baseValue = Cast(NULL, thisValue, methodBaseType, BfCastFlags_Explicit);
  13349. SizedArray<BfIRValue, 1> args;
  13350. if (moduleMethodInst.mMethodInstance->GetParamIsSplat(-1))
  13351. {
  13352. BfExprEvaluator exprEvaluator(this);
  13353. exprEvaluator.SplatArgs(baseValue, args);
  13354. }
  13355. else
  13356. {
  13357. args.push_back(baseValue.mValue);
  13358. }
  13359. mBfIRBuilder->CreateCall(moduleMethodInst.mFunc, args);
  13360. }
  13361. }
  13362. }
  13363. }
  13364. if (!methodDef->mIsStatic)
  13365. {
  13366. HashSet<int> objectOffsets;
  13367. EmitGCMarkValue(thisValue, mCurTypeInstance, 0, 0, objectOffsets, markFromGCThreadMethodInstance);
  13368. }
  13369. else
  13370. {
  13371. for (auto& fieldInst : mCurTypeInstance->mFieldInstances)
  13372. {
  13373. if (thisValue.IsSplat())
  13374. break;
  13375. auto fieldDef = fieldInst.GetFieldDef();
  13376. if (fieldDef == NULL)
  13377. continue;
  13378. if (fieldInst.mIsThreadLocal)
  13379. continue;
  13380. if (fieldDef->mIsStatic == methodDef->mIsStatic)
  13381. {
  13382. // For extensions, only handle these fields in the appropriate extension
  13383. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  13384. continue;
  13385. if (!fieldInst.mFieldIncluded)
  13386. continue;
  13387. auto fieldTypeInst = fieldInst.mResolvedType->ToTypeInstance();
  13388. if (fieldTypeInst != NULL)
  13389. {
  13390. auto fieldDef = fieldInst.GetFieldDef();
  13391. BfTypedValue markVal;
  13392. if (fieldDef->mIsConst)
  13393. continue;
  13394. if ((!fieldTypeInst->IsObjectOrInterface()) && (!fieldTypeInst->IsComposite()))
  13395. continue;
  13396. mBfIRBuilder->PopulateType(fieldTypeInst);
  13397. if (fieldTypeInst->IsValuelessType())
  13398. continue;
  13399. if ((fieldDef->mIsStatic) && (!fieldDef->mIsConst))
  13400. {
  13401. markVal = ReferenceStaticField(&fieldInst);
  13402. }
  13403. else if (!fieldDef->mIsStatic)
  13404. {
  13405. markVal = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInst.mDataIdx/*, fieldDef->mName*/), fieldInst.mResolvedType, true);
  13406. }
  13407. if (markVal)
  13408. EmitGCMarkValue(markVal, markFromGCThreadMethodInstance);
  13409. }
  13410. }
  13411. }
  13412. }
  13413. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  13414. CallChainedMethods(mCurMethodInstance, false);
  13415. }
  13416. }
  13417. }
  13418. void BfModule::EmitGCFindTLSMembers()
  13419. {
  13420. auto methodDef = mCurMethodInstance->mMethodDef;
  13421. auto gcTypeInst = ResolveTypeDef(mCompiler->mGCTypeDef)->ToTypeInstance();
  13422. auto reportTLSMark = GetMethodByName(gcTypeInst, "ReportTLSMember", 2);
  13423. BF_ASSERT(reportTLSMark);
  13424. for (auto& fieldInst : mCurTypeInstance->mFieldInstances)
  13425. {
  13426. auto fieldDef = fieldInst.GetFieldDef();
  13427. if (fieldDef == NULL)
  13428. continue;
  13429. if (!fieldInst.mIsThreadLocal)
  13430. continue;
  13431. // For extensions, only handle these fields in the appropriate extension
  13432. if ((fieldDef->mDeclaringType->mTypeDeclaration != methodDef->mDeclaringType->mTypeDeclaration))
  13433. continue;
  13434. if (!fieldInst.mFieldIncluded)
  13435. continue;
  13436. if (fieldDef->mIsConst)
  13437. continue;
  13438. auto fieldType = fieldInst.mResolvedType;
  13439. if ((!fieldType->IsObjectOrInterface()) && (!fieldType->IsComposite()))
  13440. continue;
  13441. if (fieldType->IsValuelessType())
  13442. continue;
  13443. BfTypedValue markVal = ReferenceStaticField(&fieldInst);
  13444. if (markVal)
  13445. {
  13446. BfIRValue fieldRefPtr = mBfIRBuilder->CreateBitCast(markVal.mValue, mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_NullPtr)));
  13447. BfIRValue markFuncPtr = GetMarkFuncPtr(fieldType);
  13448. SizedArray<BfIRValue, 2> llvmArgs;
  13449. llvmArgs.push_back(fieldRefPtr);
  13450. llvmArgs.push_back(markFuncPtr);
  13451. mBfIRBuilder->CreateCall(reportTLSMark.mFunc, llvmArgs);
  13452. }
  13453. }
  13454. if (mCurMethodInstance->mChainType == BfMethodChainType_ChainHead)
  13455. CallChainedMethods(mCurMethodInstance, false);
  13456. }
  13457. void BfModule::ProcessMethod(BfMethodInstance* methodInstance, bool isInlineDup)
  13458. {
  13459. BP_ZONE_F("BfModule::ProcessMethod %s", BP_DYN_STR(methodInstance->mMethodDef->mName.c_str()));
  13460. if (mAwaitingInitFinish)
  13461. FinishInit();
  13462. if (!methodInstance->mIsReified)
  13463. BF_ASSERT(!mIsReified);
  13464. if (methodInstance->mMethodInfoEx != NULL)
  13465. {
  13466. for (auto methodGenericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  13467. {
  13468. if (methodGenericArg->IsMethodRef())
  13469. {
  13470. auto methodRefType = (BfMethodRefType*)methodGenericArg;
  13471. BF_ASSERT(methodRefType->mOwnerRevision == methodRefType->mOwner->mRevision);
  13472. }
  13473. }
  13474. }
  13475. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mWantsIRIgnoreWrites || methodInstance->mIsUnspecialized);
  13476. bool ignoreWrites = mBfIRBuilder->mIgnoreWrites;
  13477. if ((HasCompiledOutput()) && (!mBfIRBuilder->mIgnoreWrites))
  13478. {
  13479. BF_ASSERT(!methodInstance->mIRFunction.IsFake() || (methodInstance->GetImportCallKind() != BfImportCallKind_None));
  13480. }
  13481. SetAndRestoreValue<BfSourceClassifier*> prevSourceClassifier;
  13482. if (((methodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend) || (methodInstance->mIsForeignMethodDef) || (methodInstance->IsSpecializedGenericMethod())) &&
  13483. (mCompiler->mResolvePassData != NULL))
  13484. {
  13485. // Don't classify on the CtorCalcAppend, just on the actual Ctor
  13486. prevSourceClassifier.Init(mCompiler->mResolvePassData->mSourceClassifier, NULL);
  13487. }
  13488. if (methodInstance->mHasBeenProcessed)
  13489. {
  13490. BfLogSysM("ProcessMethod %p HasBeenProcessed\n", methodInstance);
  13491. return;
  13492. }
  13493. if (methodInstance->mFailedConstraints)
  13494. {
  13495. // The only way this should be able to happen is if we fail our generic param check
  13496. BF_ASSERT(methodInstance->IsSpecializedGenericMethod());
  13497. BfLogSysM("Method instance marked as 'failed' at start of ProcessMethod %p\n", methodInstance);
  13498. methodInstance->mHasBeenProcessed = true;
  13499. return;
  13500. }
  13501. BfMethodInstance* defaultMethodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  13502. BF_ASSERT(methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_NotSet);
  13503. if ((methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_AlwaysInclude) &&
  13504. (methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_Referenced))
  13505. {
  13506. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Referenced;
  13507. auto owningModule = methodInstance->GetOwner()->mModule;
  13508. if (owningModule->mIsScratchModule)
  13509. {
  13510. BF_ASSERT(owningModule->mOnDemandMethodCount == 0);
  13511. }
  13512. else
  13513. {
  13514. BF_ASSERT((owningModule->mOnDemandMethodCount > 0) || (!HasCompiledOutput()) || (owningModule->mExtensionCount > 0));
  13515. if (owningModule->mOnDemandMethodCount > 0)
  13516. owningModule->mOnDemandMethodCount--;
  13517. }
  13518. }
  13519. // We set mHasBeenProcessed to true immediately -- this helps avoid stack overflow during recursion for things like
  13520. // self-referencing append allocations in ctor@calcAppend
  13521. methodInstance->mHasBeenProcessed = true;
  13522. mIncompleteMethodCount--;
  13523. BF_ASSERT((mIsSpecialModule) || (mIncompleteMethodCount >= 0));
  13524. auto typeDef = methodInstance->mMethodInstanceGroup->mOwner->mTypeDef;
  13525. auto methodDef = methodInstance->mMethodDef;
  13526. auto methodDeclaration = methodDef->GetMethodDeclaration();
  13527. if ((methodInstance->mIsReified) && (methodInstance->mVirtualTableIdx != -1))
  13528. {
  13529. // If we reify a virtual method in a HotCompile then we need to make sure the type data gets written out
  13530. // so we get the new vdata for it
  13531. methodInstance->GetOwner()->mDirty = true;
  13532. }
  13533. int dependentGenericStartIdx = 0;
  13534. if (methodDef->mIsLocalMethod) // See DoMethodDeclaration for an explaination of dependentGenericStartIdx
  13535. dependentGenericStartIdx = (int)mCurMethodState->GetRootMethodState()->mMethodInstance->GetNumGenericArguments();
  13536. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  13537. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, methodInstance->mMethodInstanceGroup->mOwner);
  13538. SetAndRestoreValue<BfFilePosition> prevFilePos(mCurFilePosition);
  13539. SetAndRestoreValue<bool> prevHadBuildError(mHadBuildError, false);
  13540. SetAndRestoreValue<bool> prevHadWarning(mHadBuildWarning, false);
  13541. SetAndRestoreValue<bool> prevIgnoreWarnings(mIgnoreWarnings, false);
  13542. if ((methodInstance->mIsReified) &&
  13543. ((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorNoBody)))
  13544. {
  13545. mCurTypeInstance->mHasBeenInstantiated = true;
  13546. }
  13547. // Warnings are shown in the capture phase
  13548. if ((methodDef->mIsLocalMethod) || (mCurTypeInstance->IsClosure()))
  13549. mIgnoreWarnings = true;
  13550. if ((methodDeclaration == NULL) && (mCurMethodState == NULL))
  13551. UseDefaultSrcPos();
  13552. // We may not actually be populated in relatively rare autocompelte cases
  13553. PopulateType(mCurTypeInstance, BfPopulateType_DataAndMethods);
  13554. mBfIRBuilder->PopulateType(mCurTypeInstance, BfIRPopulateType_Full);
  13555. BfAstNode* nameNode = NULL;
  13556. if (methodDeclaration != NULL)
  13557. {
  13558. nameNode = methodDeclaration->mNameNode;
  13559. if (nameNode == NULL)
  13560. {
  13561. if (auto ctorDeclaration = BfNodeDynCast<BfConstructorDeclaration>(methodDeclaration))
  13562. nameNode = ctorDeclaration->mThisToken;
  13563. }
  13564. }
  13565. if ((mCompiler->mResolvePassData != NULL) && (methodDeclaration != NULL) && (nameNode != NULL) &&
  13566. (mCompiler->mResolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Method) && (methodDef->mIdx >= 0))
  13567. {
  13568. if (methodInstance->GetExplicitInterface() == NULL)
  13569. mCompiler->mResolvePassData->HandleMethodReference(nameNode, typeDef, methodDef);
  13570. else
  13571. {
  13572. for (auto& ifaceEntry : mCurTypeInstance->mInterfaces)
  13573. {
  13574. auto ifaceInst = ifaceEntry.mInterfaceType;
  13575. int startIdx = ifaceEntry.mStartInterfaceTableIdx;
  13576. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  13577. if (methodInstance->GetExplicitInterface() != ifaceInst)
  13578. continue;
  13579. ifaceInst->mTypeDef->PopulateMemberSets();
  13580. BfMethodDef* nextMethod = NULL;
  13581. BfMemberSetEntry* entry = NULL;
  13582. if (ifaceInst->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  13583. nextMethod = (BfMethodDef*)entry->mMemberDef;
  13584. while (nextMethod != NULL)
  13585. {
  13586. auto checkMethod = nextMethod;
  13587. nextMethod = nextMethod->mNextWithSameName;
  13588. BfMethodInstance* implMethodInst = mCurTypeInstance->mInterfaceMethodTable[startIdx + checkMethod->mIdx].mMethodRef;
  13589. if (implMethodInst == methodInstance)
  13590. {
  13591. auto ifaceMethodDef = ifaceInst->mTypeDef->mMethods[checkMethod->mIdx];
  13592. mCompiler->mResolvePassData->HandleMethodReference(nameNode, ifaceInst->mTypeDef, ifaceMethodDef);
  13593. }
  13594. }
  13595. }
  13596. }
  13597. if (methodDef->mIsOverride)
  13598. {
  13599. for (int virtIdx = 0; virtIdx < (int)mCurTypeInstance->mVirtualMethodTable.size(); virtIdx++)
  13600. {
  13601. auto& ventry = mCurTypeInstance->mVirtualMethodTable[virtIdx];
  13602. if (ventry.mDeclaringMethod.mMethodNum == -1)
  13603. continue;
  13604. BfMethodInstance* virtMethod = ventry.mImplementingMethod;
  13605. if (virtMethod != NULL)
  13606. {
  13607. if (virtMethod == methodInstance)
  13608. {
  13609. // Is matching method
  13610. if (virtIdx < (int)mCurTypeInstance->mBaseType->mVirtualMethodTable.size())
  13611. {
  13612. auto baseType = mCurTypeInstance->mBaseType;
  13613. if (baseType != NULL)
  13614. {
  13615. while ((baseType->mBaseType != NULL) && (virtIdx < baseType->mBaseType->mVirtualMethodTableSize))
  13616. baseType = baseType->mBaseType;
  13617. BfMethodInstance* baseVirtMethod = baseType->mVirtualMethodTable[virtIdx].mImplementingMethod;
  13618. mCompiler->mResolvePassData->HandleMethodReference(nameNode, baseType->mTypeDef, baseVirtMethod->mMethodDef);
  13619. }
  13620. }
  13621. break;
  13622. }
  13623. }
  13624. }
  13625. }
  13626. }
  13627. BfLogSysM("ProcessMethod %p Unspecialized: %d Module: %p IRFunction: %d Reified: %d\n", methodInstance, mCurTypeInstance->IsUnspecializedType(), this, methodInstance->mIRFunction.mId, methodInstance->mIsReified);
  13628. if (methodInstance->GetImportCallKind() != BfImportCallKind_None)
  13629. {
  13630. if (mBfIRBuilder->mIgnoreWrites)
  13631. return;
  13632. BfLogSysM("DllImportGlobalVar processing %p\n", methodInstance);
  13633. if (!methodInstance->mIRFunction)
  13634. {
  13635. BfIRValue dllImportGlobalVar = CreateDllImportGlobalVar(methodInstance, true);
  13636. methodInstance->mIRFunction = mBfIRBuilder->GetFakeVal();
  13637. mFuncReferences[mCurMethodInstance] = dllImportGlobalVar;
  13638. }
  13639. if (HasCompiledOutput())
  13640. {
  13641. BfDllImportEntry dllImportEntry;
  13642. dllImportEntry.mFuncVar = methodInstance->mIRFunction;
  13643. dllImportEntry.mMethodInstance = mCurMethodInstance;
  13644. mDllImportEntries.push_back(dllImportEntry);
  13645. }
  13646. return;
  13647. }
  13648. StringT<128> mangledName;
  13649. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  13650. if (!methodInstance->mIRFunction)
  13651. {
  13652. bool isIntrinsic = false;
  13653. SetupIRFunction(methodInstance, mangledName, false, &isIntrinsic);
  13654. }
  13655. if (methodInstance->mIsIntrinsic)
  13656. return;
  13657. auto prevActiveFunction = mBfIRBuilder->GetActiveFunction();
  13658. mBfIRBuilder->SetActiveFunction(mCurMethodInstance->mIRFunction);
  13659. if (methodDef->mBody != NULL)
  13660. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  13661. else if (methodDeclaration != NULL)
  13662. UpdateSrcPos(methodDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  13663. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  13664. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  13665. if (mCurMethodState == NULL) // Only do initial classify for the 'outer' method state, not any local methods or lambdas
  13666. {
  13667. if ((mCompiler->mIsResolveOnly) && (methodDef->mBody != NULL) && (!mCurTypeInstance->IsBoxed()) &&
  13668. (methodDef->mBody->IsFromParser(mCompiler->mResolvePassData->mParser)) && (mCompiler->mResolvePassData->mSourceClassifier != NULL))
  13669. {
  13670. mCompiler->mResolvePassData->mSourceClassifier->VisitChildNoRef(methodDef->mBody);
  13671. }
  13672. }
  13673. BfHotDataReferenceBuilder hotDataReferenceBuilder;
  13674. BfMethodState methodState;
  13675. if (mCurMethodState != NULL)
  13676. methodState.mClosureState = mCurMethodState->mClosureState;
  13677. if ((mCompiler->mOptions.mAllowHotSwapping) && (methodInstance->mIsReified) && (!methodInstance->mIsUnspecialized) && (!isInlineDup))
  13678. {
  13679. //BF_ASSERT(methodInstance->mHotMethod != NULL);
  13680. if (methodInstance->mHotMethod == NULL)
  13681. CheckHotMethod(methodInstance, mangledName);
  13682. methodState.mHotDataReferenceBuilder = &hotDataReferenceBuilder;
  13683. }
  13684. methodState.mPrevMethodState = mCurMethodState;
  13685. methodState.mMethodInstance = methodInstance;
  13686. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  13687. if (methodInstance->GetCustomAttributes() != NULL)
  13688. {
  13689. int typeOptionsIdx = GenerateTypeOptions(methodInstance->GetCustomAttributes(), mCurTypeInstance, false);
  13690. if (typeOptionsIdx != -1)
  13691. methodState.mMethodTypeOptions = mSystem->GetTypeOptions(typeOptionsIdx);
  13692. }
  13693. BfTypeState typeState(mCurTypeInstance);
  13694. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  13695. bool isGenericVariation = (methodInstance->mIsUnspecializedVariation) || (mCurTypeInstance->IsUnspecializedTypeVariation());
  13696. BfMethodInstance* unspecializedMethodInstance = NULL;
  13697. if ((prevMethodState.mPrevVal != NULL) &&
  13698. ((methodState.mClosureState == NULL) || (methodState.mClosureState->mActiveDeferredLocalMethod == NULL)))
  13699. {
  13700. // This is 'inner' (probably a closure) - use binding from outer function
  13701. methodState.mGenericTypeBindings = prevMethodState.mPrevVal->mGenericTypeBindings;
  13702. }
  13703. else if ((methodInstance->mIsUnspecialized) ||
  13704. ((mCurTypeInstance->IsUnspecializedType()) && (!isGenericVariation)))
  13705. {
  13706. methodState.mGenericTypeBindings = &methodInstance->GetMethodInfoEx()->mGenericTypeBindings;
  13707. }
  13708. else if ((((methodInstance->mMethodInfoEx != NULL) && ((int)methodInstance->mMethodInfoEx->mMethodGenericArguments.size() > dependentGenericStartIdx)) ||
  13709. ((mCurTypeInstance->IsGenericTypeInstance()) && (!isGenericVariation))))
  13710. {
  13711. unspecializedMethodInstance = GetUnspecializedMethodInstance(methodInstance);
  13712. BF_ASSERT(unspecializedMethodInstance != methodInstance);
  13713. if (!unspecializedMethodInstance->mHasBeenProcessed)
  13714. {
  13715. // Make sure the unspecialized method is processed so we can take its bindings
  13716. // Clear mCurMethodState so we don't think we're in a local method
  13717. SetAndRestoreValue<BfMethodState*> prevMethodState_Unspec(mCurMethodState, prevMethodState.mPrevVal);
  13718. mContext->ProcessMethod(unspecializedMethodInstance);
  13719. }
  13720. methodState.mGenericTypeBindings = &unspecializedMethodInstance->GetMethodInfoEx()->mGenericTypeBindings;
  13721. }
  13722. if (methodDef->mMethodType == BfMethodType_Operator)
  13723. {
  13724. auto operatorDef = (BfOperatorDef*) methodDef;
  13725. BfAstNode* refNode = operatorDef->mOperatorDeclaration->mOperatorToken;
  13726. auto paramErrorRefNode = refNode;
  13727. if (operatorDef->mOperatorDeclaration->mOpenParen != NULL)
  13728. paramErrorRefNode = operatorDef->mOperatorDeclaration->mOpenParen;
  13729. if ((mCurMethodInstance->GetParamCount() > 0) && (mCurMethodInstance->GetParamTypeRef(0) != NULL))
  13730. paramErrorRefNode = mCurMethodInstance->GetParamTypeRef(0);
  13731. if (operatorDef->mOperatorDeclaration->mBinOp != BfBinaryOp_None)
  13732. {
  13733. if (methodDef->mParams.size() != 2)
  13734. {
  13735. Fail("Binary operators must declare two parameters", paramErrorRefNode);
  13736. }
  13737. else
  13738. {
  13739. if ((mCurMethodInstance->GetParamType(0) != mCurTypeInstance) && (!mCurMethodInstance->GetParamType(0)->IsSelf()) &&
  13740. (mCurMethodInstance->GetParamType(1) != mCurTypeInstance) && (!mCurMethodInstance->GetParamType(1)->IsSelf()))
  13741. {
  13742. Fail("At least one of the parameters of a binary operator must be the containing type", paramErrorRefNode);
  13743. }
  13744. }
  13745. BfType* wantType = NULL;
  13746. if (operatorDef->mOperatorDeclaration->mBinOp == BfBinaryOp_Compare)
  13747. {
  13748. wantType = GetPrimitiveType(BfTypeCode_IntPtr);
  13749. }
  13750. if ((wantType != NULL) && (methodInstance->mReturnType != wantType))
  13751. Fail(StrFormat("The return type for the '%s' operator must be '%s'", BfGetOpName(operatorDef->mOperatorDeclaration->mBinOp),
  13752. TypeToString(wantType).c_str()), operatorDef->mOperatorDeclaration->mReturnType);
  13753. }
  13754. else if (operatorDef->mOperatorDeclaration->mUnaryOp != BfUnaryOp_None)
  13755. {
  13756. if (methodDef->mParams.size() != 1)
  13757. {
  13758. Fail("Unary operators must declare one parameter", paramErrorRefNode);
  13759. }
  13760. else if ((mCurMethodInstance->GetParamType(0) != mCurTypeInstance) && (!mCurMethodInstance->GetParamType(0)->IsSelf()))
  13761. {
  13762. Fail("The parameter of a unary operator must be the containing type", paramErrorRefNode);
  13763. }
  13764. if (((operatorDef->mOperatorDeclaration->mUnaryOp == BfUnaryOp_Increment) ||
  13765. (operatorDef->mOperatorDeclaration->mUnaryOp == BfUnaryOp_Decrement)) &&
  13766. (!TypeIsSubTypeOf(mCurMethodInstance->mReturnType->ToTypeInstance(), mCurTypeInstance)))
  13767. {
  13768. Fail("The return type for the '++' or '--' operator must match the parameter type or be derived from the parameter type", operatorDef->mOperatorDeclaration->mReturnType);
  13769. }
  13770. }
  13771. else if (operatorDef->mOperatorDeclaration->mAssignOp != BfAssignmentOp_None)
  13772. {
  13773. if (methodDef->mParams.size() != 1)
  13774. {
  13775. Fail("Assignment operators must declare one parameter", paramErrorRefNode);
  13776. }
  13777. if (mCurMethodInstance->mReturnType->IsVoid())
  13778. {
  13779. Fail("The return type for assignment operator must be 'void'", operatorDef->mOperatorDeclaration->mReturnType);
  13780. }
  13781. }
  13782. else // Conversion
  13783. {
  13784. if (!operatorDef->mOperatorDeclaration->mIsConvOperator)
  13785. {
  13786. if (operatorDef->mOperatorDeclaration->mReturnType != NULL)
  13787. Fail("Conversion operators must declare their target type after the 'operator' token, not before", operatorDef->mOperatorDeclaration->mReturnType);
  13788. }
  13789. if (methodDef->mParams.size() != 1)
  13790. {
  13791. auto refNode = paramErrorRefNode;
  13792. if (!operatorDef->mOperatorDeclaration->mCommas.empty())
  13793. refNode = operatorDef->mOperatorDeclaration->mCommas[0];
  13794. Fail("Conversion operators must declare one parameter", refNode);
  13795. }
  13796. else
  13797. {
  13798. if ((mCurMethodInstance->GetParamType(0) != mCurTypeInstance) && (!mCurMethodInstance->GetParamType(0)->IsSelf()) &&
  13799. (mCurMethodInstance->mReturnType != mCurTypeInstance) && (!mCurMethodInstance->mReturnType->IsSelf()))
  13800. Fail("User-defined conversion must convert to or from the enclosing type", paramErrorRefNode);
  13801. if (mCurMethodInstance->GetParamType(0) == mCurMethodInstance->mReturnType)
  13802. Fail("User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type", operatorDef->mOperatorDeclaration->mReturnType);
  13803. // On type lookup error we default to 'object', so don't do the 'base class' error if that may have
  13804. // happened here
  13805. if ((!mHadBuildError) || ((mCurMethodInstance->mReturnType != mContext->mBfObjectType) && (mCurMethodInstance->GetParamType(0) != mContext->mBfObjectType)))
  13806. {
  13807. auto isToBase = TypeIsSubTypeOf(mCurTypeInstance->mBaseType, mCurMethodInstance->mReturnType->ToTypeInstance());
  13808. bool isFromBase = TypeIsSubTypeOf(mCurTypeInstance->mBaseType, mCurMethodInstance->GetParamType(0)->ToTypeInstance());
  13809. if ((mCurTypeInstance->IsObject()) && (isToBase || isFromBase))
  13810. Fail("User-defined conversions to or from a base class are not allowed", paramErrorRefNode);
  13811. else if ((mCurTypeInstance->IsStruct()) && (isToBase))
  13812. Fail("User-defined conversions to a base struct are not allowed", paramErrorRefNode);
  13813. }
  13814. }
  13815. }
  13816. }
  13817. bool wantsDIData = (mBfIRBuilder->DbgHasInfo()) && (!methodDef->IsEmptyPartial()) && (!mCurMethodInstance->mIsUnspecialized) && (mHasFullDebugInfo);
  13818. if (methodDef->mMethodType == BfMethodType_Mixin)
  13819. wantsDIData = false;
  13820. if ((mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType != BfMethodType_Ctor))
  13821. wantsDIData = false;
  13822. bool wantsDIVariables = wantsDIData;
  13823. if (methodDef->mIsExtern)
  13824. wantsDIVariables = false;
  13825. SizedArray<BfIRMDNode, 8> diParams;
  13826. diParams.push_back(mBfIRBuilder->DbgGetType(methodInstance->mReturnType));
  13827. bool isThisStruct = mCurTypeInstance->IsStruct() && !mCurTypeInstance->IsTypedPrimitive();
  13828. BfType* thisType = NULL;
  13829. if (!methodDef->mIsStatic)
  13830. {
  13831. if ((methodState.mClosureState != NULL) && (methodState.mClosureState->mClosureType != NULL))
  13832. thisType = methodState.mClosureState->mClosureType;
  13833. else
  13834. thisType = mCurTypeInstance;
  13835. }
  13836. PopulateType(methodInstance->mReturnType, BfPopulateType_Data);
  13837. ProcessMethod_SetupParams(methodInstance, thisType, wantsDIData, &diParams);
  13838. //////////////////////////////////////////////////////////////////////////
  13839. //
  13840. {
  13841. if (methodDeclaration != NULL)
  13842. UpdateSrcPos(methodDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  13843. else if (methodDef->mBody != NULL)
  13844. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  13845. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  13846. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration, BfSrcPosFlag_NoSetDebugLoc);
  13847. }
  13848. BfIRMDNode diFunction;
  13849. if (wantsDIData)
  13850. {
  13851. BP_ZONE("BfModule::BfMethodDeclaration.DISetup");
  13852. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParams);
  13853. int defLine = mCurFilePosition.mCurLine;
  13854. if (mDICompileUnit)
  13855. {
  13856. int flags = 0;
  13857. BfIRMDNode funcScope = mBfIRBuilder->DbgGetTypeInst(mCurTypeInstance);
  13858. if (methodDef->mProtection == BfProtection_Public)
  13859. flags = llvm::DINode::FlagPublic;
  13860. else if (methodDef->mProtection == BfProtection_Protected)
  13861. flags = llvm::DINode::FlagProtected;
  13862. else
  13863. flags = llvm::DINode::FlagPrivate;
  13864. if (methodDef->mIsOverride)
  13865. {
  13866. //flags |= llvm::DINode::FlagVirtual;
  13867. }
  13868. else if (methodDef->mIsVirtual)
  13869. flags |= llvm::DINode::FlagIntroducedVirtual;
  13870. if ((methodDef->mIsStatic) || (methodDef->mMethodType == BfMethodType_Mixin))
  13871. flags |= llvm::DINode::FlagStaticMember;
  13872. else
  13873. {
  13874. if ((mCurTypeInstance->IsValuelessType()) || (mCurTypeInstance->IsSplattable()))
  13875. flags |= llvm::DINode::FlagStaticMember;
  13876. }
  13877. flags |= llvm::DINode::FlagPrototyped;
  13878. if (methodDef->mMethodType == BfMethodType_Ctor)
  13879. {
  13880. flags |= llvm::DINode::FlagArtificial;
  13881. }
  13882. auto llvmFunction = methodInstance->mIRFunction;
  13883. SizedArray<BfIRMDNode, 1> genericArgs;
  13884. SizedArray<BfIRValue, 1> genericConstValueArgs;
  13885. String methodName;
  13886. if (methodInstance->GetForeignType() != NULL)
  13887. {
  13888. methodName += TypeToString(methodInstance->GetForeignType());
  13889. methodName += ".";
  13890. }
  13891. if (methodInstance->GetExplicitInterface() != NULL)
  13892. {
  13893. methodName += TypeToString(methodInstance->GetExplicitInterface());
  13894. methodName += ".";
  13895. }
  13896. methodName += methodDef->mName;
  13897. if (methodInstance->GetNumGenericArguments() != 0)
  13898. {
  13899. for (auto genericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  13900. {
  13901. if (genericArg->IsConstExprValue())
  13902. {
  13903. BfConstExprValueType* constExprValueType = (BfConstExprValueType*)genericArg;
  13904. while (genericConstValueArgs.size() < genericArgs.size())
  13905. genericConstValueArgs.push_back(BfIRValue());
  13906. genericConstValueArgs.push_back(mBfIRBuilder->CreateConst(BfTypeCode_UInt64, constExprValueType->mValue.mUInt64));
  13907. genericArgs.push_back(mBfIRBuilder->DbgGetType(GetPrimitiveType(BfTypeCode_Int64)));
  13908. }
  13909. else
  13910. genericArgs.push_back(mBfIRBuilder->DbgGetType(genericArg));
  13911. }
  13912. methodName += "<";
  13913. for (int i = 0; i < (int)methodInstance->mMethodInfoEx->mMethodGenericArguments.size(); i++)
  13914. {
  13915. if (i > 0)
  13916. methodName += ", ";
  13917. BfType* type = methodInstance->mMethodInfoEx->mMethodGenericArguments[i];
  13918. methodName += TypeToString(type);
  13919. }
  13920. methodName += ">";
  13921. }
  13922. if ((methodName.empty()) && (methodDeclaration != NULL))
  13923. {
  13924. if (auto operatorDecl = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  13925. {
  13926. methodName += "operator";
  13927. if (operatorDecl->mIsConvOperator)
  13928. {
  13929. methodName += " ";
  13930. methodName += TypeToString(methodInstance->mReturnType);
  13931. }
  13932. else if (operatorDecl->mOpTypeToken != NULL)
  13933. methodName += operatorDecl->mOpTypeToken->ToString();
  13934. }
  13935. }
  13936. methodState.mDIFile = mCurFilePosition.mFileInstance->mDIFile;
  13937. // diFunction = mBfIRBuilder->DbgCreateMethod(funcScope, methodName, mangledName, methodState.mDIFile,
  13938. // defLine + 1, diFuncType, false, true,
  13939. // (methodInstance->mVirtualTableIdx != -1) ? llvm::dwarf::DW_VIRTUALITY_virtual : llvm::dwarf::DW_VIRTUALITY_none,
  13940. // (methodInstance->mVirtualTableIdx != -1) ? methodInstance->DbgGetVirtualMethodNum() : 0,
  13941. // nullptr, flags, IsOptimized(), llvmFunction, genericArgs, genericConstValueArgs);
  13942. diFunction = mBfIRBuilder->DbgCreateMethod(funcScope, methodName, mangledName, methodState.mDIFile,
  13943. defLine + 1, diFuncType, false, true,
  13944. llvm::dwarf::DW_VIRTUALITY_none,
  13945. 0,
  13946. nullptr, flags, IsOptimized(), llvmFunction, genericArgs, genericConstValueArgs);
  13947. }
  13948. }
  13949. //////////////////////////////////////////////////////////////////////////
  13950. // Head and Init get rolled into Entry afterwards.
  13951. methodState.mIRFunction = methodInstance->mIRFunction;
  13952. methodState.mIRHeadBlock = mBfIRBuilder->CreateBlock("head", true);
  13953. methodState.mIRInitBlock = mBfIRBuilder->CreateBlock("init", true);
  13954. methodState.mIREntryBlock = mBfIRBuilder->CreateBlock("entry", true);
  13955. methodState.mCurScope->mDIScope = diFunction;
  13956. auto llvmEntryBlock = methodState.mIREntryBlock;
  13957. mBfIRBuilder->SetInsertPoint(llvmEntryBlock);
  13958. if (methodDef->mBody != NULL)
  13959. {
  13960. UpdateSrcPos(methodDef->mBody, BfSrcPosFlag_NoSetDebugLoc);
  13961. }
  13962. else if ((mHasFullDebugInfo) && (diFunction) && (typeDef->mTypeDeclaration != NULL))
  13963. {
  13964. // We want to be able to step into delegate invokes -- we actually step over them
  13965. if (methodDef->mName != "Invoke")
  13966. {
  13967. UpdateSrcPos(typeDef->mTypeDeclaration);
  13968. mBfIRBuilder->DbgCreateAnnotation(diFunction, "StepOver", GetConstValue32(1));
  13969. }
  13970. }
  13971. // Clear out DebugLoc - to mark the ".addr" code as part of prologue
  13972. mBfIRBuilder->ClearDebugLocation();
  13973. bool isTypedPrimitiveFunc = mCurTypeInstance->IsTypedPrimitive() && (methodDef->mMethodType != BfMethodType_Ctor);
  13974. int irParamCount = methodInstance->GetIRFunctionParamCount(this);
  13975. if (methodDef->mImportKind != BfImportKind_Dynamic)
  13976. {
  13977. int localIdx = 0;
  13978. int argIdx = 0;
  13979. if (methodInstance->HasStructRet())
  13980. argIdx++;
  13981. //
  13982. bool doDbgAgg = false;
  13983. Array<BfIRValue> splatAddrValues;
  13984. for ( ; argIdx < irParamCount; localIdx++)
  13985. {
  13986. bool isThis = ((localIdx == 0) && (!mCurMethodInstance->mMethodDef->mIsStatic));
  13987. if ((isThis) && (thisType->IsValuelessType()))
  13988. isThis = false;
  13989. BfLocalVariable* paramVar = NULL;
  13990. while (true)
  13991. {
  13992. BF_ASSERT(localIdx < methodState.mLocals.size());
  13993. paramVar = methodState.mLocals[localIdx];
  13994. if ((paramVar->mCompositeCount == -1) &&
  13995. ((!paramVar->mResolvedType->IsValuelessType()) || (paramVar->mResolvedType->IsMethodRef())))
  13996. break;
  13997. localIdx++;
  13998. }
  13999. if ((isThis) && (mCurTypeInstance->IsValueType()) && (methodDef->mMethodType != BfMethodType_Ctor) && (!methodDef->HasNoThisSplat()))
  14000. {
  14001. paramVar->mIsReadOnly = true;
  14002. }
  14003. bool wantsAddr = (wantsDIVariables) || (!paramVar->mIsReadOnly) || (paramVar->mResolvedType->GetLoweredType() != BfTypeCode_None);
  14004. if (paramVar->mResolvedType->IsMethodRef())
  14005. wantsAddr = false;
  14006. // if ((methodDef->mHasAppend) && (argIdx == 1))
  14007. // {
  14008. // BF_ASSERT(paramVar->mName == "appendIdx");
  14009. // wantsAddr = true;
  14010. // }
  14011. if ((!doDbgAgg) && (paramVar->mIsSplat))
  14012. {
  14013. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  14014. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  14015. BfTypeUtils::SplatIterate([&](BfType* checkType)
  14016. {
  14017. BfIRType splatIRType;
  14018. if (checkType->IsComposite())
  14019. splatIRType = mBfIRBuilder->MapType(CreatePointerType(checkType));
  14020. else
  14021. splatIRType = mBfIRBuilder->MapType(checkType);
  14022. auto allocaInst = mBfIRBuilder->CreateAlloca(splatIRType);
  14023. mBfIRBuilder->SetAllocaAlignment(allocaInst, checkType->mAlign);
  14024. if (!paramVar->mAddr)
  14025. paramVar->mAddr = allocaInst;
  14026. if (WantsLifetimes())
  14027. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  14028. splatAddrValues.push_back(allocaInst);
  14029. }, paramVar->mResolvedType);
  14030. mBfIRBuilder->SetInsertPoint(prevInsert);
  14031. }
  14032. else if (isThis)
  14033. {
  14034. if (wantsAddr)
  14035. {
  14036. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  14037. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  14038. BfIRType thisAddrType = mBfIRBuilder->MapType(thisType);
  14039. if (paramVar->mIsSplat)
  14040. {
  14041. if (doDbgAgg)
  14042. {
  14043. auto allocaInst = mBfIRBuilder->CreateAlloca(thisAddrType);
  14044. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  14045. mBfIRBuilder->SetAllocaAlignment(allocaInst, thisType->mAlign);
  14046. paramVar->mAddr = allocaInst;
  14047. if (WantsLifetimes())
  14048. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  14049. }
  14050. }
  14051. else
  14052. {
  14053. bool wantPtr = (thisType->IsComposite()) && (!paramVar->mIsLowered);
  14054. if ((thisType->IsTypedPrimitive()) && (methodDef->HasNoThisSplat()))
  14055. wantPtr = true;
  14056. if (wantPtr)
  14057. {
  14058. thisAddrType = mBfIRBuilder->MapTypeInstPtr(thisType->ToTypeInstance());
  14059. }
  14060. auto allocaInst = mBfIRBuilder->CreateAlloca(thisAddrType);
  14061. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  14062. mBfIRBuilder->SetAllocaAlignment(allocaInst, mSystem->mPtrSize);
  14063. paramVar->mAddr = allocaInst;
  14064. if (WantsLifetimes())
  14065. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  14066. }
  14067. mBfIRBuilder->SetInsertPoint(prevInsert);
  14068. }
  14069. }
  14070. else if ((!isThis) && ((paramVar->mIsStruct) || (paramVar->mResolvedType->IsRef())))
  14071. {
  14072. // Address doesn't change so we don't have to alloca it
  14073. BfIRType allocType;
  14074. int alignSize = mSystem->mPtrSize;
  14075. if (paramVar->mResolvedType->IsRef())
  14076. {
  14077. allocType = mBfIRBuilder->MapType(paramVar->mResolvedType);
  14078. }
  14079. else if ((paramVar->mIsSplat) || (paramVar->mIsLowered))
  14080. {
  14081. allocType = mBfIRBuilder->MapType(paramVar->mResolvedType);
  14082. alignSize = paramVar->mResolvedType->mAlign;
  14083. }
  14084. else
  14085. {
  14086. paramVar->mHasLocalStructBacking = true;
  14087. auto typeInst = paramVar->mResolvedType->ToTypeInstance();
  14088. if (typeInst != NULL)
  14089. allocType = mBfIRBuilder->MapTypeInstPtr(paramVar->mResolvedType->ToTypeInstance());
  14090. else
  14091. allocType = mBfIRBuilder->MapType(CreatePointerType(paramVar->mResolvedType));
  14092. }
  14093. if (wantsAddr)
  14094. {
  14095. auto prevInsert = mBfIRBuilder->GetInsertBlock();
  14096. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRHeadBlock);
  14097. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  14098. auto allocaInst = mBfIRBuilder->CreateAlloca(allocType);
  14099. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  14100. mBfIRBuilder->SetAllocaAlignment(allocaInst, alignSize);
  14101. paramVar->mAddr = allocaInst;
  14102. mBfIRBuilder->SetInsertPoint(prevInsert);
  14103. if (WantsLifetimes())
  14104. mCurMethodState->mCurScope->mDeferredLifetimeEnds.push_back(allocaInst);
  14105. }
  14106. }
  14107. else if (wantsAddr)
  14108. {
  14109. auto allocaInst = CreateAlloca(paramVar->mResolvedType);
  14110. mBfIRBuilder->SetName(allocaInst, paramVar->mName + ".addr");
  14111. paramVar->mAddr = allocaInst;
  14112. }
  14113. if (paramVar->mIsSplat)
  14114. {
  14115. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  14116. }
  14117. else
  14118. {
  14119. argIdx++;
  14120. }
  14121. }
  14122. if (methodDef->mBody != NULL)
  14123. UpdateSrcPos(methodDef->mBody);
  14124. else if (mCurTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  14125. UpdateSrcPos(mCurTypeInstance->mTypeDef->mTypeDeclaration);
  14126. int declArgIdx = 0;
  14127. localIdx = 0;
  14128. argIdx = 0;
  14129. if (methodInstance->HasStructRet())
  14130. argIdx++;
  14131. int splatAddrIdx = 0;
  14132. while (localIdx < (int)methodState.mLocals.size())
  14133. {
  14134. int curLocalIdx = localIdx++;
  14135. BfLocalVariable* paramVar = methodState.mLocals[curLocalIdx];
  14136. if (!paramVar->IsParam())
  14137. continue;
  14138. if (paramVar->mCompositeCount != -1)
  14139. continue;
  14140. bool isThis = ((curLocalIdx == 0) && (!mCurMethodInstance->mMethodDef->mIsStatic));
  14141. if ((isThis) && (thisType->IsValuelessType()))
  14142. isThis = false;
  14143. BfIRMDNode diVariable;
  14144. if (wantsDIData)
  14145. {
  14146. String paramName = paramVar->mName;
  14147. BfIRMDNode diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  14148. if (isThis)
  14149. {
  14150. if ((mCurMethodState->mClosureState != NULL) && (mCurMethodState->mClosureState->mClosureType != NULL))
  14151. paramName = "__closure";
  14152. if ((paramVar->mResolvedType->IsValueType()) && (!paramVar->mIsSplat) && (!paramVar->mIsLowered))
  14153. {
  14154. diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  14155. bool wantRef = paramVar->mResolvedType->IsComposite();
  14156. if ((paramVar->mResolvedType->IsTypedPrimitive()) && (methodDef->HasNoThisSplat()))
  14157. wantRef = true;
  14158. if (wantRef)
  14159. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  14160. }
  14161. else if (!paramVar->mResolvedType->IsValueType())
  14162. {
  14163. diType = mBfIRBuilder->DbgCreateArtificialType(diType);
  14164. }
  14165. }
  14166. else
  14167. {
  14168. if ((paramVar->mResolvedType->IsComposite()) && (!paramVar->mIsSplat) && (!paramVar->mIsLowered))
  14169. {
  14170. diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  14171. diType = mBfIRBuilder->DbgCreateReferenceType(diType);
  14172. diType = mBfIRBuilder->DbgCreateConstType(diType);
  14173. }
  14174. }
  14175. if ((!paramVar->mIsSplat) || (doDbgAgg))
  14176. {
  14177. if (paramVar->mResolvedType->IsValuelessType())
  14178. {
  14179. diVariable = mBfIRBuilder->DbgCreateAutoVariable(diFunction,
  14180. paramName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  14181. }
  14182. else if (paramVar->mIsImplicitParam)
  14183. {
  14184. // Annotate this specially?
  14185. diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  14186. paramName, argIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, true, 0);
  14187. }
  14188. else
  14189. {
  14190. diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  14191. paramName, argIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType, true, 0);
  14192. }
  14193. paramVar->mDbgVarInst = diVariable;
  14194. }
  14195. else if ((paramVar->mIsSplat) && (paramVar->mResolvedType->GetSplatCount() == 0))
  14196. {
  14197. // if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables))
  14198. // {
  14199. // // Only add this placeholder if we don't have any values
  14200. // auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  14201. // paramName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  14202. // mBfIRBuilder->DbgInsertValueIntrinsic(GetConstValue(0), diVariable);
  14203. // }
  14204. }
  14205. }
  14206. bool isTypedPrimCtor = mCurTypeInstance->IsTypedPrimitive() && (methodDef->mMethodType == BfMethodType_Ctor);
  14207. if ((!paramVar->mParamFailed) && (paramVar->mAddr))
  14208. {
  14209. // Write our argument value into the .addr
  14210. mBfIRBuilder->ClearDebugLocation();
  14211. if (paramVar->mIsSplat)
  14212. {
  14213. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  14214. if (doDbgAgg)
  14215. {
  14216. auto curArgIdx = argIdx;
  14217. std::function<void(BfType*, BfIRValue)> checkTypeLambda = [&](BfType* checkType, BfIRValue curDestAddr)
  14218. {
  14219. if (checkType->IsStruct())
  14220. {
  14221. auto checkTypeInstance = checkType->ToTypeInstance();
  14222. if (checkTypeInstance->mBaseType != NULL)
  14223. {
  14224. auto baseDestAddr = mBfIRBuilder->CreateBitCast(curDestAddr, mBfIRBuilder->MapTypeInstPtr(checkTypeInstance->mBaseType));
  14225. checkTypeLambda(checkTypeInstance->mBaseType, baseDestAddr);
  14226. }
  14227. if (checkTypeInstance->mIsUnion)
  14228. {
  14229. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  14230. if (!unionInnerType->IsValuelessType())
  14231. {
  14232. auto newDestAddr = mBfIRBuilder->CreateInBoundsGEP(curDestAddr, 0, 1);
  14233. checkTypeLambda(unionInnerType, newDestAddr);
  14234. }
  14235. if (checkTypeInstance->IsEnum())
  14236. {
  14237. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  14238. auto newDestAddr = mBfIRBuilder->CreateInBoundsGEP(curDestAddr, 0, 2);
  14239. checkTypeLambda(dscrType, newDestAddr);
  14240. }
  14241. }
  14242. else
  14243. {
  14244. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  14245. {
  14246. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  14247. if (fieldInstance->mDataIdx >= 0)
  14248. {
  14249. auto newDestAddr = mBfIRBuilder->CreateInBoundsGEP(curDestAddr, 0, fieldInstance->mDataIdx);
  14250. checkTypeLambda(fieldInstance->GetResolvedType(), newDestAddr);
  14251. }
  14252. }
  14253. }
  14254. }
  14255. else if (checkType->IsMethodRef())
  14256. {
  14257. BF_FATAL("Unimplemented");
  14258. // BfMethodRefType* methodRefType = (BfMethodRefType*)checkType;
  14259. // for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  14260. // {
  14261. // checkTypeLambda->
  14262. // }
  14263. }
  14264. else if (!checkType->IsValuelessType())
  14265. {
  14266. mBfIRBuilder->CreateAlignedStore(mBfIRBuilder->GetArgument(curArgIdx), curDestAddr, paramVar->mResolvedType->mAlign);
  14267. curArgIdx++;
  14268. }
  14269. };
  14270. checkTypeLambda(paramVar->mResolvedType, paramVar->mAddr);
  14271. }
  14272. }
  14273. else
  14274. {
  14275. bool handled = false;
  14276. //if ((!isThis) || (!methodDef->mIsMutating && !methodDef->mNoSplat))
  14277. if (paramVar->mIsLowered)
  14278. {
  14279. auto loweredTypeCode = paramVar->mResolvedType->GetLoweredType();
  14280. BF_ASSERT(loweredTypeCode != BfTypeCode_None);
  14281. if (loweredTypeCode != BfTypeCode_None)
  14282. {
  14283. // We have a lowered type coming in, so we have to cast the .addr before storing
  14284. auto primType = GetPrimitiveType(loweredTypeCode);
  14285. auto primPtrType = CreatePointerType(primType);
  14286. auto primPtrVal = mBfIRBuilder->CreateBitCast(paramVar->mAddr, mBfIRBuilder->MapType(primPtrType));
  14287. mBfIRBuilder->CreateAlignedStore(paramVar->mValue, primPtrVal, paramVar->mResolvedType->mSize);
  14288. // We don't want to allow directly using value
  14289. paramVar->mValue = BfIRValue();
  14290. handled = true;
  14291. }
  14292. }
  14293. if (!handled)
  14294. mBfIRBuilder->CreateAlignedStore(paramVar->mValue, paramVar->mAddr, paramVar->mResolvedType->mAlign);
  14295. }
  14296. }
  14297. if (!isThis)
  14298. declArgIdx++;
  14299. if (methodDef->mBody != NULL)
  14300. UpdateSrcPos(methodDef->mBody);
  14301. else if (methodDef->mDeclaringType->mTypeDeclaration != NULL)
  14302. UpdateSrcPos(methodDef->mDeclaringType->mTypeDeclaration);
  14303. else if (methodDeclaration == NULL)
  14304. UseDefaultSrcPos();
  14305. // Write our argument value into the .addr
  14306. if ((!doDbgAgg) && (paramVar->mIsSplat))
  14307. {
  14308. int splatComponentIdx = 0;
  14309. auto curArgIdx = argIdx;
  14310. auto _FinishSplats = [&] (BfType* checkType, const StringImpl& name)
  14311. {
  14312. BfIRValue splatAddrValue = splatAddrValues[splatAddrIdx++];
  14313. methodState.mSplatDecompAddrs.push_back(splatAddrValue);
  14314. auto storeInst = mBfIRBuilder->CreateAlignedStore(mBfIRBuilder->GetArgument(curArgIdx), splatAddrValue, checkType->mAlign);
  14315. mBfIRBuilder->ClearDebugLocation(storeInst);
  14316. if (wantsDIData)
  14317. {
  14318. BfIRMDNode diType;
  14319. if (checkType->IsComposite())
  14320. diType = mBfIRBuilder->DbgGetType(CreateRefType(checkType));
  14321. else
  14322. diType = mBfIRBuilder->DbgGetType(checkType);
  14323. auto diVariable = mBfIRBuilder->DbgCreateParameterVariable(diFunction,
  14324. name, curArgIdx + 1, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  14325. if (wantsDIVariables)
  14326. {
  14327. mBfIRBuilder->DbgInsertDeclare(splatAddrValue, diVariable);
  14328. }
  14329. }
  14330. curArgIdx++;
  14331. splatComponentIdx++;
  14332. };
  14333. std::function<void(BfType*, const StringImpl&)> _FinishSplatsIterate = [&](BfType* checkType, const StringImpl& name)
  14334. {
  14335. if (checkType->IsStruct())
  14336. {
  14337. auto checkTypeInstance = checkType->ToTypeInstance();
  14338. if (checkTypeInstance->mBaseType != NULL)
  14339. {
  14340. _FinishSplatsIterate(checkTypeInstance->mBaseType, name + "$b");
  14341. }
  14342. if (checkTypeInstance->mIsUnion)
  14343. {
  14344. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  14345. if (!unionInnerType->IsValuelessType())
  14346. {
  14347. _FinishSplatsIterate(unionInnerType, name + "$u");
  14348. }
  14349. if (checkTypeInstance->IsEnum())
  14350. {
  14351. auto dscrType = checkTypeInstance->GetDiscriminatorType();
  14352. _FinishSplatsIterate(dscrType, name + "$d");
  14353. }
  14354. }
  14355. else
  14356. {
  14357. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  14358. {
  14359. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  14360. auto fieldDef = fieldInstance->GetFieldDef();
  14361. if (fieldInstance->mDataIdx >= 0)
  14362. {
  14363. _FinishSplatsIterate(fieldInstance->GetResolvedType(), name + "$m$" + fieldDef->mName);
  14364. }
  14365. }
  14366. }
  14367. }
  14368. else if (checkType->IsMethodRef())
  14369. {
  14370. auto methodRefType = (BfMethodRefType*)checkType;
  14371. BfMethodInstance* methodInstance = methodRefType->mMethodRef;
  14372. // int implicitParamCount = methodInstance->GetImplicitParamCount();
  14373. // for (int implicitParamIdx = methodInstance->HasThis() ? -1 : 0; implicitParamIdx < implicitParamCount; implicitParamIdx++)
  14374. // {
  14375. // auto paramType = methodInstance->GetParamType(implicitParamIdx);
  14376. // if (!paramType->IsValuelessType())
  14377. // _FinishSplats(paramType, name + "$m$" + methodInstance->GetParamName(implicitParamIdx));
  14378. // }
  14379. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  14380. {
  14381. int paramIdx = methodRefType->GetParamIdxFromDataIdx(dataIdx);
  14382. String paramName = methodInstance->GetParamName(paramIdx);
  14383. if (paramName == "this")
  14384. paramName = "__this";
  14385. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  14386. {
  14387. _FinishSplatsIterate(methodRefType->GetCaptureType(dataIdx), name + "$m$" + paramName);
  14388. }
  14389. else
  14390. {
  14391. _FinishSplats(methodRefType->GetCaptureType(dataIdx), name + "$m$" + paramName);
  14392. }
  14393. }
  14394. }
  14395. else if (!checkType->IsValuelessType())
  14396. {
  14397. _FinishSplats(checkType, name);
  14398. }
  14399. };
  14400. mBfIRBuilder->PopulateType(paramVar->mResolvedType);
  14401. if (!paramVar->mConstValue)
  14402. _FinishSplatsIterate(paramVar->mResolvedType, "$" + paramVar->mName);
  14403. }
  14404. BfIRValue declareCall;
  14405. if (diVariable)
  14406. {
  14407. if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables))
  14408. {
  14409. if (!paramVar->mAddr)
  14410. {
  14411. if ((!paramVar->mValue) || (paramVar->mValue.IsFake()))
  14412. {
  14413. if ((!paramVar->mIsThis) && (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU)) // DWARF chokes on this:
  14414. {
  14415. // We don't need to set the location for this
  14416. mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  14417. }
  14418. }
  14419. else
  14420. declareCall = mBfIRBuilder->DbgInsertDeclare(paramVar->mValue, diVariable);
  14421. }
  14422. else
  14423. {
  14424. declareCall = mBfIRBuilder->DbgInsertDeclare(paramVar->mAddr, diVariable);
  14425. }
  14426. }
  14427. }
  14428. if ((isThis) && (!paramVar->mIsSplat) && (paramVar->mAddr))
  14429. {
  14430. // We don't allow actually assignment to "this", so we just do a single load
  14431. // Keep in mind we don't use the ACTUAL mValue value because that's a register, but
  14432. // we need to store it in the stack frame for debugging purposes
  14433. auto loadedThis = mBfIRBuilder->CreateLoad(paramVar->mAddr/*, "this"*/);
  14434. mBfIRBuilder->ClearDebugLocation(loadedThis);
  14435. paramVar->mValue = loadedThis;
  14436. }
  14437. if ((wantsDIData) && (declareCall))
  14438. mBfIRBuilder->UpdateDebugLocation(declareCall);
  14439. if (paramVar->mIsSplat)
  14440. {
  14441. BfTypeUtils::SplatIterate([&](BfType* checkType) { argIdx++; }, paramVar->mResolvedType);
  14442. }
  14443. else if (!paramVar->mResolvedType->IsValuelessType())
  14444. {
  14445. argIdx++;
  14446. }
  14447. }
  14448. if (wantsDIData)
  14449. {
  14450. BF_ASSERT(splatAddrIdx == (int)splatAddrValues.size());
  14451. }
  14452. }
  14453. for (int varIdx = 0; varIdx < (int)mCurMethodState->mLocals.size(); varIdx++)
  14454. {
  14455. auto paramVar = mCurMethodState->mLocals[varIdx];
  14456. // 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
  14457. // splat member. If the "splat" is valueless then we do create a placeholder, but further up in this method
  14458. // if (paramVar->mIsSplat)
  14459. // {
  14460. // if (wantsDIVariables)
  14461. // {
  14462. // auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(diFunction, paramVar->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(paramVar->mResolvedType));
  14463. // mBfIRBuilder->DbgInsertValueIntrinsic(mBfIRBuilder->CreateConst(BfTypeCode_Int64, 0), diVariable);
  14464. // }
  14465. // }
  14466. if (paramVar->mResolvedType->IsValuelessType())
  14467. {
  14468. if ((mBfIRBuilder->HasDebugLocation()) && (wantsDIVariables) && (mCompiler->mOptions.mToolsetType != BfToolsetType_GNU)) // DWARF chokes on this:
  14469. {
  14470. // Only add this placeholder if we don't have any values
  14471. auto diType = mBfIRBuilder->DbgGetType(paramVar->mResolvedType);
  14472. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(mCurMethodState->mCurScope->mDIScope,
  14473. paramVar->mName, mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, diType);
  14474. mBfIRBuilder->DbgInsertValueIntrinsic(BfIRValue(), diVariable);
  14475. }
  14476. }
  14477. }
  14478. if (IsTargetingBeefBackend())
  14479. mCurMethodState->mCurScope->mValueScopeStart = mBfIRBuilder->CreateValueScopeStart();
  14480. if (methodState.mClosureState != NULL)
  14481. {
  14482. for (auto& constLocal : methodState.mClosureState->mConstLocals)
  14483. {
  14484. BfLocalVariable* localVar = new BfLocalVariable();
  14485. *localVar = constLocal;
  14486. AddLocalVariableDef(localVar, true);
  14487. }
  14488. }
  14489. bool wantsRemoveBody = false;
  14490. bool skipBody = false;
  14491. bool skipUpdateSrcPos = false;
  14492. bool skipEndChecks = false;
  14493. bool hasExternSpecifier = (methodDeclaration != NULL) && (methodDeclaration->mExternSpecifier != NULL) && (methodDef->mImportKind != BfImportKind_Dynamic);
  14494. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  14495. if ((methodDef != NULL) && (propertyDeclaration != NULL) && (propertyDeclaration->mExternSpecifier != NULL))
  14496. hasExternSpecifier = true;
  14497. // Allocate, clear, set classVData
  14498. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mIsStatic))
  14499. {
  14500. CreateStaticCtor();
  14501. }
  14502. else if ((mCurTypeInstance->IsBoxed()) && (methodDef->mMethodType != BfMethodType_Ctor) && (methodDef->mName != BF_METHODNAME_DYNAMICCAST) && (methodDef->mName != BF_METHODNAME_DYNAMICCAST_INTERFACE))
  14503. {
  14504. skipBody = true;
  14505. skipEndChecks = true;
  14506. if (HasCompiledOutput())
  14507. {
  14508. // Clear out DebugLoc - to mark the ".addr" code as part of prologue
  14509. mBfIRBuilder->ClearDebugLocation();
  14510. BfBoxedType* boxedType = (BfBoxedType*) mCurTypeInstance;
  14511. BfTypeInstance* innerType = boxedType->mElementType;
  14512. PopulateType(innerType, BfPopulateType_DataAndMethods);
  14513. mBfIRBuilder->PopulateType(mCurTypeInstance);
  14514. BfGetMethodInstanceFlags flags = BfGetMethodInstanceFlag_None;
  14515. if (methodInstance->mIsForeignMethodDef)
  14516. {
  14517. flags = BfGetMethodInstanceFlag_ForeignMethodDef;
  14518. }
  14519. BfTypeVector methodGenericArguments;
  14520. if (methodInstance->mMethodInfoEx != NULL)
  14521. methodGenericArguments = methodInstance->mMethodInfoEx->mMethodGenericArguments;
  14522. auto innerMethodInstance = GetMethodInstance(innerType, methodDef, methodGenericArguments, flags, methodInstance->GetForeignType());
  14523. if (innerMethodInstance.mMethodInstance->IsSkipCall())
  14524. {
  14525. if (!methodInstance->mReturnType->IsValuelessType())
  14526. {
  14527. auto retVal = GetDefaultValue(methodInstance->mReturnType);
  14528. CreateReturn(retVal);
  14529. }
  14530. }
  14531. else
  14532. {
  14533. BF_ASSERT(innerMethodInstance.mMethodInstance->mMethodDef == methodDef);
  14534. SizedArray<BfIRValue, 8> innerParams;
  14535. BfExprEvaluator exprEvaluator(this);
  14536. if (!innerType->IsValuelessType())
  14537. {
  14538. BfIRValue thisValue = mBfIRBuilder->CreateInBoundsGEP(mCurMethodState->mLocals[0]->mValue, 0, 1);
  14539. BfTypedValue innerVal(thisValue, innerType, true);
  14540. if (boxedType->IsBoxedStructPtr())
  14541. {
  14542. innerVal = LoadValue(innerVal);
  14543. innerVal = BfTypedValue(innerVal.mValue, innerType, true);
  14544. }
  14545. exprEvaluator.PushThis(NULL, innerVal, innerMethodInstance.mMethodInstance, innerParams);
  14546. }
  14547. for (int i = 1; i < (int)mCurMethodState->mLocals.size(); i++)
  14548. {
  14549. BfLocalVariable* localVar = mCurMethodState->mLocals[i];
  14550. BfTypedValue localVal = exprEvaluator.LoadLocal(localVar, true);
  14551. exprEvaluator.PushArg(localVal, innerParams);
  14552. }
  14553. if (!innerMethodInstance.mFunc)
  14554. {
  14555. BF_ASSERT(innerType->IsUnspecializedType());
  14556. }
  14557. else if (methodInstance->HasStructRet())
  14558. {
  14559. mBfIRBuilder->PopulateType(methodInstance->mReturnType);
  14560. auto returnType = BfTypedValue(mBfIRBuilder->GetArgument(0), methodInstance->mReturnType, true);
  14561. exprEvaluator.mReceivingValue = &returnType;
  14562. auto retVal = exprEvaluator.CreateCall(innerMethodInstance.mMethodInstance, innerMethodInstance.mFunc, true, innerParams, NULL, true);
  14563. BF_ASSERT(exprEvaluator.mReceivingValue == NULL); // Ensure it was actually used
  14564. mBfIRBuilder->CreateRetVoid();
  14565. }
  14566. else
  14567. {
  14568. mBfIRBuilder->PopulateType(methodInstance->mReturnType);
  14569. auto retVal = exprEvaluator.CreateCall(innerMethodInstance.mMethodInstance, innerMethodInstance.mFunc, true, innerParams, NULL, true);
  14570. if (mCurMethodInstance->mReturnType->IsValueType())
  14571. retVal = LoadValue(retVal);
  14572. CreateReturn(retVal.mValue);
  14573. }
  14574. }
  14575. }
  14576. mCurMethodState->SetHadReturn(true);
  14577. mCurMethodState->mLeftBlockUncond = true;
  14578. }
  14579. else if (methodDef->mMethodType == BfMethodType_CtorClear)
  14580. {
  14581. SetIllegalSrcPos();
  14582. mBfIRBuilder->ClearDebugLocation();
  14583. PopulateType(mCurTypeInstance, BfPopulateType_Data);
  14584. auto thisVal = GetThis();
  14585. int prevSize = mContext->mBfObjectType->mInstSize;
  14586. int curSize = mCurTypeInstance->mInstSize;
  14587. if (curSize > prevSize)
  14588. {
  14589. auto int8PtrType = CreatePointerType(GetPrimitiveType(BfTypeCode_Int8));
  14590. auto int8PtrVal = mBfIRBuilder->CreateBitCast(thisVal.mValue, mBfIRBuilder->MapType(int8PtrType));
  14591. int8PtrVal = mBfIRBuilder->CreateInBoundsGEP(int8PtrVal, GetConstValue(prevSize));
  14592. mBfIRBuilder->CreateMemSet(int8PtrVal, GetConstValue8(0), GetConstValue(curSize - prevSize), GetConstValue(mCurTypeInstance->mInstAlign));
  14593. }
  14594. skipUpdateSrcPos = true;
  14595. }
  14596. else if (((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorNoBody)) && (!hasExternSpecifier))
  14597. {
  14598. EmitCtorBody(skipBody);
  14599. }
  14600. else if ((methodDef->mMethodType == BfMethodType_Dtor) && (!hasExternSpecifier))
  14601. {
  14602. EmitDtorBody();
  14603. skipBody = true;
  14604. }
  14605. if ((!mCurTypeInstance->IsBoxed()) && (methodDeclaration != NULL) && (methodDeclaration->mHadYield) && (methodDef->mBody != NULL))
  14606. {
  14607. EmitIteratorBlock(skipBody);
  14608. }
  14609. if (methodDef->mName == BF_METHODNAME_MARKMEMBERS)
  14610. {
  14611. // We need to be able to mark deleted objects
  14612. mCurMethodState->mIgnoreObjectAccessCheck = true;
  14613. }
  14614. auto customAttributes = methodInstance->GetCustomAttributes();
  14615. if ((customAttributes != NULL) && (customAttributes->Contains(mCompiler->mDisableObjectAccessChecksAttributeTypeDef)))
  14616. mCurMethodState->mIgnoreObjectAccessCheck = true;
  14617. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) && (!methodDef->mIsStatic) &&
  14618. ((methodInstance->mChainType == BfMethodChainType_ChainHead) || (methodInstance->mChainType == BfMethodChainType_None)))
  14619. {
  14620. // We chain even non-default ctors to the default ctors
  14621. auto defaultCtor = methodInstance;
  14622. if (defaultCtor->mChainType == BfMethodChainType_ChainHead)
  14623. CallChainedMethods(defaultCtor, false);
  14624. }
  14625. auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody);
  14626. if (methodDef->mBody == NULL)
  14627. {
  14628. if (methodDeclaration != NULL)
  14629. {
  14630. if (auto operatorDeclaration = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  14631. {
  14632. if (operatorDeclaration->mIsConvOperator)
  14633. wantsRemoveBody = true;
  14634. }
  14635. }
  14636. bool isDllImport = false;
  14637. if (methodDef->mImportKind == BfImportKind_Static)
  14638. {
  14639. for (auto customAttr : methodInstance->GetCustomAttributes()->mAttributes)
  14640. {
  14641. if (customAttr.mType->mTypeDef->mFullName.ToString() == "System.ImportAttribute")
  14642. {
  14643. if (customAttr.mCtorArgs.size() == 1)
  14644. {
  14645. auto fileNameArg = customAttr.mCtorArgs[0];
  14646. int strNum = 0;
  14647. auto constant = mCurTypeInstance->mConstHolder->GetConstant(fileNameArg);
  14648. if (constant != NULL)
  14649. {
  14650. if (constant->IsNull())
  14651. continue; // Invalid
  14652. strNum = constant->mInt32;
  14653. }
  14654. else
  14655. {
  14656. strNum = GetStringPoolIdx(fileNameArg, mCurTypeInstance->mConstHolder);
  14657. }
  14658. if (!mImportFileNames.Contains(strNum))
  14659. mImportFileNames.Add(strNum);
  14660. }
  14661. }
  14662. }
  14663. //mImportFileNames
  14664. }
  14665. else if (methodDef->mImportKind == BfImportKind_Dynamic)
  14666. {
  14667. CreateDllImportMethod();
  14668. }
  14669. else if (((mCurTypeInstance->mTypeDef->mIsDelegate) || (mCurTypeInstance->mTypeDef->mIsFunction)) &&
  14670. (methodDef->mName == "Invoke") && (methodDef->mMethodType == BfMethodType_Normal))
  14671. {
  14672. if (mCurTypeInstance->mTypeDef->mIsFunction)
  14673. {
  14674. // Emit nothing
  14675. }
  14676. else
  14677. {
  14678. CreateDelegateInvokeMethod();
  14679. mCurMethodState->SetHadReturn(true);
  14680. mCurMethodState->mLeftBlockUncond = true;
  14681. }
  14682. }
  14683. else if ((methodDef->mName == BF_METHODNAME_DYNAMICCAST) || (methodDef->mName == BF_METHODNAME_DYNAMICCAST_INTERFACE))
  14684. {
  14685. if (mCurTypeInstance->IsObject())
  14686. {
  14687. CreateDynamicCastMethod();
  14688. }
  14689. else
  14690. {
  14691. mBfIRBuilder->CreateRet(GetDefaultValue(methodInstance->mReturnType));
  14692. mCurMethodState->mHadReturn = true;
  14693. }
  14694. }
  14695. else if ((methodDef->mName == BF_METHODNAME_ENUM_HASFLAG) && (mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()))
  14696. {
  14697. BfIRValue ret;
  14698. if (mCurMethodState->mLocals[1]->mResolvedType != mCurTypeInstance)
  14699. {
  14700. // This can happen if we provide an invalid name
  14701. AssertErrorState();
  14702. ret = mBfIRBuilder->CreateRet(GetDefaultValue(GetPrimitiveType(BfTypeCode_Boolean)));
  14703. }
  14704. else
  14705. {
  14706. // Unfortunate DebugLoc shenanigans-
  14707. // 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,
  14708. // so we only set the loc on the CreateRet which gets inlined out
  14709. mBfIRBuilder->SaveDebugLocation();
  14710. mBfIRBuilder->ClearDebugLocation();
  14711. BfIRValue fromBool;
  14712. if (!mCurTypeInstance->IsTypedPrimitive())
  14713. {
  14714. fromBool = GetDefaultValue(methodInstance->mReturnType);
  14715. }
  14716. else
  14717. {
  14718. auto andResult = mBfIRBuilder->CreateAnd(mCurMethodState->mLocals[0]->mValue, mCurMethodState->mLocals[1]->mValue);
  14719. auto toBool = mBfIRBuilder->CreateCmpNE(andResult, GetDefaultValue(mCurMethodState->mLocals[0]->mResolvedType));
  14720. fromBool = mBfIRBuilder->CreateNumericCast(toBool, false, BfTypeCode_Boolean);
  14721. }
  14722. mBfIRBuilder->RestoreDebugLocation();
  14723. ret = mBfIRBuilder->CreateRet(fromBool);
  14724. //ExtendLocalLifetimes(0);
  14725. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  14726. }
  14727. mCurMethodState->SetHadReturn(true);
  14728. mCurMethodState->mLeftBlockUncond = true;
  14729. }
  14730. else if (((methodDef->mName == BF_METHODNAME_ENUM_GETUNDERLYINGREF) || (methodDef->mName == BF_METHODNAME_ENUM_GETUNDERLYING)) &&
  14731. (mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()))
  14732. {
  14733. BfIRValue ret;
  14734. // Unfortunate DebugLoc shenanigans-
  14735. // 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,
  14736. // so we only set the loc on the CreateRet which gets inlined out
  14737. mBfIRBuilder->SaveDebugLocation();
  14738. mBfIRBuilder->ClearDebugLocation();
  14739. BfIRValue fromBool;
  14740. mBfIRBuilder->RestoreDebugLocation();
  14741. ret = mBfIRBuilder->CreateRet(GetThis().mValue);
  14742. //ExtendLocalLifetimes(0);
  14743. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  14744. mCurMethodState->SetHadReturn(true);
  14745. mCurMethodState->mLeftBlockUncond = true;
  14746. }
  14747. else if ((mCurTypeInstance->IsEnum()) && (!mCurTypeInstance->IsBoxed()) && (methodDef->mName == BF_METHODNAME_TO_STRING))
  14748. {
  14749. auto enumType = ResolveTypeDef(mCompiler->mEnumTypeDef);
  14750. if (HasCompiledOutput())
  14751. {
  14752. EmitEnumToStringBody();
  14753. }
  14754. mBfIRBuilder->CreateRetVoid();
  14755. mCurMethodState->SetHadReturn(true);
  14756. mCurMethodState->mLeftBlockUncond = true;
  14757. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  14758. }
  14759. else if ((mCurTypeInstance->IsTuple()) && (!mCurTypeInstance->IsBoxed()) && (methodDef->mName == BF_METHODNAME_TO_STRING))
  14760. {
  14761. auto enumType = ResolveTypeDef(mCompiler->mEnumTypeDef);
  14762. if (HasCompiledOutput())
  14763. {
  14764. EmitTupleToStringBody();
  14765. }
  14766. mBfIRBuilder->CreateRetVoid();
  14767. mCurMethodState->SetHadReturn(true);
  14768. mCurMethodState->mLeftBlockUncond = true;
  14769. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  14770. }
  14771. else if (methodDef->mName == BF_METHODNAME_DEFAULT_EQUALS)
  14772. {
  14773. CreateValueTypeEqualsMethod();
  14774. skipBody = true;
  14775. skipEndChecks = true;
  14776. }
  14777. else if ((methodDef->mName == BF_METHODNAME_EQUALS) && (typeDef == mCompiler->mValueTypeTypeDef))
  14778. {
  14779. CreateValueTypeEqualsMethod();
  14780. skipBody = true;
  14781. skipEndChecks = true;
  14782. }
  14783. else if (HasCompiledOutput())
  14784. {
  14785. if ((methodDef->mName == BF_METHODNAME_MARKMEMBERS) || (methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC))
  14786. {
  14787. if (mCompiler->mOptions.mEnableRealtimeLeakCheck)
  14788. {
  14789. EmitGCMarkMembers();
  14790. }
  14791. else if (!mCurTypeInstance->IsObject())
  14792. {
  14793. }
  14794. }
  14795. else if (methodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS)
  14796. {
  14797. if (mCompiler->mOptions.mEnableRealtimeLeakCheck)
  14798. {
  14799. EmitGCFindTLSMembers();
  14800. }
  14801. }
  14802. }
  14803. }
  14804. else if (!skipBody)
  14805. {
  14806. bool isEmptyBodied = BfNodeDynCast<BfTokenNode>(methodDef->mBody) != NULL;
  14807. if (isEmptyBodied) // Generate autoProperty things
  14808. {
  14809. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  14810. if ((propertyDeclaration != NULL) && (!typeDef->HasAutoProperty(propertyDeclaration)))
  14811. {
  14812. if ((!mCurTypeInstance->IsInterface()) && (!hasExternSpecifier))
  14813. Fail("Body expected", methodDef->mBody);
  14814. }
  14815. else if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  14816. {
  14817. if (methodInstance->mReturnType->IsValuelessType())
  14818. {
  14819. mBfIRBuilder->CreateRetVoid();
  14820. }
  14821. else if (HasCompiledOutput())
  14822. {
  14823. String autoPropName = typeDef->GetAutoPropertyName(propertyDeclaration);
  14824. BfFieldInstance* fieldInstance = GetFieldByName(mCurTypeInstance, autoPropName);
  14825. BfFieldDef* fieldDef = NULL;
  14826. if (fieldInstance != NULL)
  14827. fieldDef = fieldInstance->GetFieldDef();
  14828. BfType* retType = methodInstance->mReturnType;
  14829. if (retType->IsRef())
  14830. retType = retType->GetUnderlyingType();
  14831. if ((fieldInstance != NULL) && (fieldInstance->GetResolvedType() == retType) &&
  14832. ((fieldInstance->mDataIdx >= 0) || (fieldDef->IsNonConstStatic())))
  14833. {
  14834. BfTypedValue lookupValue;
  14835. if (fieldDef->IsNonConstStatic())
  14836. lookupValue = ReferenceStaticField(fieldInstance);
  14837. else if (mCurTypeInstance->IsObject())
  14838. lookupValue = BfTypedValue(mBfIRBuilder->CreateInBoundsGEP(GetThis().mValue, 0, fieldInstance->mDataIdx), fieldInstance->mResolvedType, true);
  14839. else
  14840. lookupValue = ExtractValue(GetThis(), fieldInstance, fieldInstance->mFieldIdx);
  14841. if (!methodInstance->mReturnType->IsRef())
  14842. lookupValue = LoadValue(lookupValue);
  14843. mBfIRBuilder->CreateRet(lookupValue.mValue);
  14844. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  14845. }
  14846. else
  14847. {
  14848. // This can happen if we have two properties with the same name but different types
  14849. AssertErrorState();
  14850. mBfIRBuilder->CreateRet(GetDefaultValue(methodInstance->mReturnType));
  14851. }
  14852. }
  14853. else
  14854. {
  14855. // During autocomplete, the actual type may not have the proper field instance
  14856. mBfIRBuilder->CreateRet(GetDefaultValue(methodInstance->mReturnType));
  14857. }
  14858. mCurMethodState->SetHadReturn(true);
  14859. }
  14860. else if (methodDef->mMethodType == BfMethodType_PropertySetter)
  14861. {
  14862. if (!mCompiler->IsAutocomplete())
  14863. {
  14864. String autoPropName = typeDef->GetAutoPropertyName(propertyDeclaration);
  14865. BfFieldInstance* fieldInstance = GetFieldByName(mCurTypeInstance, autoPropName);
  14866. auto fieldDef = fieldInstance->GetFieldDef();
  14867. auto& lastParam = mCurMethodState->mLocals.back();
  14868. if ((fieldInstance != NULL) && (fieldInstance->GetResolvedType() == lastParam->mResolvedType) &&
  14869. ((fieldInstance->mDataIdx >= 0) || (fieldDef->IsNonConstStatic())))
  14870. {
  14871. BfIRValue lookupAddr;
  14872. if (fieldDef->IsNonConstStatic())
  14873. lookupAddr = ReferenceStaticField(fieldInstance).mValue;
  14874. else
  14875. {
  14876. auto thisValue = GetThis();
  14877. if (thisValue.IsSplat())
  14878. {
  14879. BF_FATAL("Should not happen");
  14880. }
  14881. if (mCurTypeInstance->IsObject())
  14882. thisValue = LoadValue(thisValue);
  14883. lookupAddr = mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, fieldInstance->mDataIdx);
  14884. }
  14885. mBfIRBuilder->CreateStore(lastParam->mValue, lookupAddr);
  14886. }
  14887. else if (!fieldInstance->mResolvedType->IsValuelessType())
  14888. {
  14889. // This can happen if we have two properties with the same name but different types
  14890. AssertErrorState();
  14891. }
  14892. }
  14893. }
  14894. }
  14895. if ((!mCurMethodInstance->mReturnType->IsValuelessType()) && (!isEmptyBodied))
  14896. {
  14897. mBfIRBuilder->PopulateType(mCurMethodInstance->mReturnType);
  14898. if (mCurMethodInstance->HasStructRet())
  14899. {
  14900. auto ptrType = CreatePointerType(mCurMethodInstance->mReturnType);
  14901. auto allocaInst = AllocLocalVariable(ptrType, "__return.addr", false);
  14902. auto storeInst = mBfIRBuilder->CreateStore(mBfIRBuilder->GetArgument(0), allocaInst);
  14903. mBfIRBuilder->ClearDebugLocation(storeInst);
  14904. mCurMethodState->mRetValAddr = allocaInst;
  14905. }
  14906. else
  14907. {
  14908. auto allocaInst = AllocLocalVariable(mCurMethodInstance->mReturnType, "__return", false);
  14909. mCurMethodState->mRetVal = BfTypedValue(allocaInst, mCurMethodInstance->mReturnType, true);
  14910. }
  14911. }
  14912. if (methodDef->mMethodType == BfMethodType_CtorCalcAppend)
  14913. {
  14914. mBfIRBuilder->CreateStore(GetConstValue(0), mCurMethodState->mRetVal.mValue);
  14915. BfGetSymbolReferenceKind prevSymbolKind;
  14916. BfAutoComplete* prevAutoComplete;
  14917. if (mCompiler->mResolvePassData != NULL)
  14918. {
  14919. prevSymbolKind = mCompiler->mResolvePassData->mGetSymbolReferenceKind;
  14920. prevAutoComplete = mCompiler->mResolvePassData->mAutoComplete;
  14921. mCompiler->mResolvePassData->mGetSymbolReferenceKind = BfGetSymbolReferenceKind_None;
  14922. }
  14923. EmitCtorCalcAppend();
  14924. if (mCompiler->mResolvePassData != NULL)
  14925. {
  14926. mCompiler->mResolvePassData->mGetSymbolReferenceKind = prevSymbolKind;
  14927. mCompiler->mResolvePassData->mAutoComplete = prevAutoComplete;
  14928. }
  14929. }
  14930. else if (!isEmptyBodied)
  14931. {
  14932. if (!mCurMethodState->mIRExitBlock)
  14933. mCurMethodState->mIRExitBlock = mBfIRBuilder->CreateBlock("exit", true);
  14934. bool isExpressionBody = false;
  14935. if (methodDeclaration != NULL)
  14936. {
  14937. if (methodDeclaration->mFatArrowToken != NULL)
  14938. isExpressionBody = true;
  14939. }
  14940. else if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  14941. {
  14942. if (auto propBodyExpr = BfNodeDynCast<BfPropertyBodyExpression>(propertyDeclaration->mDefinitionBlock))
  14943. {
  14944. isExpressionBody = true;
  14945. }
  14946. }
  14947. else
  14948. {
  14949. if (auto block = BfNodeDynCast<BfBlock>(methodDef->mBody))
  14950. {
  14951. if (!block->mChildArr.IsEmpty())
  14952. {
  14953. if (auto exprStmt = BfNodeDynCast<BfExpressionStatement>(block->mChildArr.GetLast()))
  14954. {
  14955. if (exprStmt->mTrailingSemicolon == NULL)
  14956. isExpressionBody = true;
  14957. }
  14958. }
  14959. }
  14960. else
  14961. isExpressionBody = true;
  14962. }
  14963. if (auto fieldDtorBody = BfNodeDynCast<BfFieldDtorDeclaration>(methodDef->mBody))
  14964. {
  14965. while (fieldDtorBody != NULL)
  14966. {
  14967. VisitEmbeddedStatement(fieldDtorBody->mBody);
  14968. fieldDtorBody = fieldDtorBody->mNextFieldDtor;
  14969. }
  14970. }
  14971. else if (!isExpressionBody)
  14972. {
  14973. auto bodyBlock = BfNodeDynCast<BfBlock>(methodDef->mBody);
  14974. mCurMethodState->mHeadScope.mAstBlock = bodyBlock;
  14975. mCurMethodState->mHeadScope.mCloseNode = bodyBlock->mCloseBrace;
  14976. VisitCodeBlock(bodyBlock);
  14977. }
  14978. else if (auto expressionBody = BfNodeDynCast<BfExpression>(methodDef->mBody))
  14979. {
  14980. if ((methodDef->mMethodType != BfMethodType_Normal) && (propertyDeclaration == NULL))
  14981. {
  14982. BF_ASSERT(methodDeclaration->mFatArrowToken != NULL);
  14983. Fail("Only normal methods can have expression bodies", methodDeclaration->mFatArrowToken);
  14984. }
  14985. auto expectingType = mCurMethodInstance->mReturnType;
  14986. // if ((expectingType->IsVoid()) && (IsInSpecializedSection()))
  14987. // {
  14988. // Warn(0, "Using a 'void' return with an expression-bodied method isn't needed. Consider removing '=>' token", methodDeclaration->mFatArrowToken);
  14989. // }
  14990. //TODO: Why did we have all this stuff for handling void?
  14991. // if (expectingType->IsVoid())
  14992. // {
  14993. // bool wasReturnGenericParam = false;
  14994. // if ((mCurMethodState->mClosureState != NULL) && (mCurMethodState->mClosureState->mReturnType != NULL))
  14995. // {
  14996. // wasReturnGenericParam = mCurMethodState->mClosureState->mReturnType->IsGenericParam();
  14997. // }
  14998. // else
  14999. // {
  15000. // auto unspecializedMethodInstance = GetUnspecializedMethodInstance(mCurMethodInstance);
  15001. // if ((unspecializedMethodInstance != NULL) && (unspecializedMethodInstance->mReturnType->IsGenericParam()))
  15002. // wasReturnGenericParam = true;
  15003. // }
  15004. //
  15005. // // If we the void return was from a generic specialization, allow us to return a void result,
  15006. // // otherwise treat expression as though it must be a statement
  15007. // bool isStatement = expressionBody->VerifyIsStatement(mCompiler->mPassInstance, wasReturnGenericParam);
  15008. // if (isStatement)
  15009. // expectingType = NULL;
  15010. // }
  15011. UpdateSrcPos(expressionBody);
  15012. auto retVal = CreateValueFromExpression(expressionBody, expectingType);
  15013. if ((retVal) && (expectingType != NULL))
  15014. {
  15015. mCurMethodState->mHadReturn = true;
  15016. retVal = LoadValue(retVal);
  15017. EmitReturn(retVal.mValue);
  15018. }
  15019. }
  15020. }
  15021. }
  15022. BF_ASSERT(mCurMethodState->mCurScope == &mCurMethodState->mHeadScope);
  15023. if (skipUpdateSrcPos)
  15024. {
  15025. // Skip
  15026. }
  15027. else if ((bodyBlock != NULL) && (bodyBlock->mCloseBrace != NULL))
  15028. UpdateSrcPos(bodyBlock->mCloseBrace);
  15029. else if (methodDef->mBody != NULL)
  15030. UpdateSrcPos(methodDef->mBody);
  15031. else if (methodDeclaration != NULL)
  15032. UpdateSrcPos(methodDeclaration);
  15033. else if (methodDef->mDeclaringType->mTypeDeclaration != NULL)
  15034. UpdateSrcPos(methodDef->mDeclaringType->mTypeDeclaration);
  15035. else
  15036. UseDefaultSrcPos();
  15037. if (methodDef->mMethodType == BfMethodType_CtorCalcAppend)
  15038. {
  15039. if (mCurMethodState->mRetVal)
  15040. {
  15041. mCurMethodState->SetHadReturn(true);
  15042. auto retVal = mBfIRBuilder->CreateLoad(mCurMethodState->mRetVal.mValue);
  15043. mBfIRBuilder->CreateRet(retVal);
  15044. }
  15045. else
  15046. AssertErrorState();
  15047. }
  15048. if (!mCurMethodState->mHadReturn)
  15049. {
  15050. // Clear off the stackallocs that have occurred after a scopeData break
  15051. EmitDeferredScopeCalls(false, &mCurMethodState->mHeadScope, mCurMethodState->mIRExitBlock);
  15052. }
  15053. if (mCurMethodState->mIRExitBlock)
  15054. {
  15055. for (auto preExitBlock : mCurMethodState->mHeadScope.mAtEndBlocks)
  15056. mBfIRBuilder->MoveBlockToEnd(preExitBlock);
  15057. mBfIRBuilder->MoveBlockToEnd(mCurMethodState->mIRExitBlock);
  15058. mBfIRBuilder->SetInsertPoint(mCurMethodState->mIRExitBlock);
  15059. if (!mCurMethodState->mDIRetVal)
  15060. CreateDIRetVal();
  15061. }
  15062. for (auto localVar : mCurMethodState->mLocals)
  15063. {
  15064. if ((skipEndChecks) || (bodyBlock == NULL))
  15065. break;
  15066. LocalVariableDone(localVar, true);
  15067. }
  15068. if (mCurMethodState->mIRExitBlock)
  15069. {
  15070. if ((mCurMethodState->mRetVal) && (!mCurMethodInstance->HasStructRet()))
  15071. {
  15072. auto loadedVal = mBfIRBuilder->CreateLoad(mCurMethodState->mRetVal.mValue);
  15073. CreateReturn(loadedVal);
  15074. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  15075. if (mCurMethodState->mDIRetVal)
  15076. mBfIRBuilder->DbgLifetimeEnd(mCurMethodState->mDIRetVal);
  15077. }
  15078. else
  15079. {
  15080. // Have something on the last line to step onto
  15081. if (mHasFullDebugInfo)
  15082. {
  15083. if ((bodyBlock != NULL) && (bodyBlock->mCloseBrace != NULL))
  15084. UpdateSrcPos(bodyBlock->mCloseBrace);
  15085. EmitEnsureInstructionAt();
  15086. if ((irParamCount == 0) && (!IsTargetingBeefBackend()) && (mCompiler->mOptions.mAllowHotSwapping))
  15087. {
  15088. // This may be a case where we only emit 4 bytes, whereas we need 5 for a hot replace jump
  15089. mBfIRBuilder->EnsureFunctionPatchable();
  15090. }
  15091. }
  15092. mBfIRBuilder->CreateRetVoid();
  15093. EmitLifetimeEnds(&mCurMethodState->mHeadScope);
  15094. if (mCurMethodState->mDIRetVal)
  15095. mBfIRBuilder->DbgLifetimeEnd(mCurMethodState->mDIRetVal);
  15096. }
  15097. }
  15098. if ((mCurMethodInstance->mReturnType == NULL) || (mCurMethodInstance->mReturnType->IsValuelessType()))
  15099. {
  15100. if ((!mCurMethodState->mHadReturn) && (!mCurMethodState->mIRExitBlock))
  15101. {
  15102. if ((irParamCount == 0) && (!IsTargetingBeefBackend()) && (mCompiler->mOptions.mAllowHotSwapping))
  15103. {
  15104. // This may be a case where we only emit 4 bytes, whereas we need 5 for a hot replace jump
  15105. mBfIRBuilder->EnsureFunctionPatchable();
  15106. }
  15107. mBfIRBuilder->CreateRetVoid();
  15108. }
  15109. }
  15110. else
  15111. {
  15112. if (!mCurMethodState->mHadReturn)
  15113. {
  15114. auto refNode = mCurMethodInstance->mMethodDef->GetRefNode();
  15115. if (bodyBlock != NULL)
  15116. {
  15117. if (bodyBlock->mCloseBrace != NULL)
  15118. {
  15119. BfAstNode* target = bodyBlock->mCloseBrace;
  15120. Fail("Method must return value", target);
  15121. }
  15122. else
  15123. {
  15124. // It's possible to not have a closing brace if the method ends in an EOF
  15125. AssertErrorState();
  15126. }
  15127. }
  15128. }
  15129. }
  15130. // Move 'init' into 'entry'
  15131. mBfIRBuilder->MergeBlockDown(mCurMethodState->mIRInitBlock, mCurMethodState->mIREntryBlock);
  15132. mBfIRBuilder->MergeBlockDown(mCurMethodState->mIRHeadBlock, mCurMethodState->mIREntryBlock);
  15133. if ((mCurMethodInstance->mIsUnspecialized) /*|| (typeDef->mIsFunction)*/ || (mCurTypeInstance->IsUnspecializedType()))
  15134. {
  15135. // Don't keep instructions for unspecialized types
  15136. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  15137. }
  15138. if ((hasExternSpecifier) && (!skipBody))
  15139. {
  15140. // If we hot swap, we want to make sure at least one method refers to this extern method so it gets pulled in
  15141. // incase it gets called later by some hot-loaded coded
  15142. if (mCompiler->mOptions.mAllowHotSwapping)
  15143. CreateFakeCallerMethod(mangledName);
  15144. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  15145. }
  15146. else if ((methodDef->mImportKind == BfImportKind_Dynamic) && (!mCompiler->IsHotCompile()))
  15147. {
  15148. // We only need the DLL stub when we may be hot swapping
  15149. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  15150. }
  15151. else if (wantsRemoveBody)
  15152. mBfIRBuilder->Func_DeleteBody(mCurMethodInstance->mIRFunction);
  15153. // We don't want to hold on to pointers to LLVMFunctions of unspecialized types.
  15154. // This allows us to delete the mScratchModule LLVM module without rebuilding all
  15155. // unspecialized types
  15156. if ((mCurTypeInstance->IsUnspecializedType()) || (mCurTypeInstance->IsInterface()))
  15157. {
  15158. BfLogSysM("ProcessMethod Clearing IRFunction: %p\n", methodInstance);
  15159. methodInstance->mIRFunction = BfIRFunction();
  15160. }
  15161. CheckAddFailType();
  15162. if (mHadBuildError)
  15163. prevHadBuildError.CancelRestore();
  15164. if (mHadBuildWarning)
  15165. prevHadWarning.CancelRestore();
  15166. if (!methodDef->mIsLocalMethod)
  15167. ProcessMethod_ProcessDeferredLocals();
  15168. mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  15169. if (methodState.mHotDataReferenceBuilder != NULL)
  15170. {
  15171. AddHotDataReferences(&hotDataReferenceBuilder);
  15172. }
  15173. else
  15174. {
  15175. if ((methodInstance->mHotMethod != NULL) && (!methodInstance->mIsReified))
  15176. {
  15177. // Remove the hot method data
  15178. auto hotMethod = methodInstance->mHotMethod;
  15179. auto prevMethod = hotMethod->mPrevVersion;
  15180. if (prevMethod != NULL)
  15181. {
  15182. // If there's a prev method then pull its data into the main HotMethod.
  15183. // This, in effect, removes the 'hotMethod' data and rebases 'prevMethod'
  15184. // over to the main HotMethod definition to keep the HotMethod address
  15185. // invariant
  15186. for (auto ref : hotMethod->mReferences)
  15187. ref->Deref();
  15188. hotMethod->mReferences.Clear();
  15189. BF_ASSERT(prevMethod->mRefCount == 1);
  15190. hotMethod->mReferences = prevMethod->mReferences;
  15191. if (hotMethod->mSrcTypeVersion != NULL)
  15192. hotMethod->mSrcTypeVersion->Deref();
  15193. hotMethod->mSrcTypeVersion = prevMethod->mSrcTypeVersion;
  15194. prevMethod->mSrcTypeVersion = NULL;
  15195. prevMethod->mReferences.Clear();
  15196. hotMethod->mPrevVersion = prevMethod->mPrevVersion;
  15197. prevMethod->mPrevVersion = NULL;
  15198. prevMethod->Deref();
  15199. }
  15200. hotMethod->Deref();
  15201. methodInstance->mHotMethod = NULL;
  15202. }
  15203. }
  15204. }
  15205. String BfModule::GetLocalMethodName(const StringImpl& baseName, BfAstNode* anchorNode, BfMethodState* declMethodState, BfMixinState* declMixinState)
  15206. {
  15207. String name;
  15208. bool found = false;
  15209. auto checkMethodState = mCurMethodState;
  15210. while (checkMethodState != NULL)
  15211. {
  15212. if (checkMethodState->mClosureState == NULL)
  15213. break;
  15214. if (checkMethodState->mClosureState->mClosureMethodDef != NULL)
  15215. {
  15216. found = true;
  15217. name += checkMethodState->mClosureState->mClosureMethodDef->mName;
  15218. break;
  15219. }
  15220. checkMethodState = checkMethodState->mPrevMethodState;
  15221. }
  15222. if (!found)
  15223. name += mCurMethodInstance->mMethodDef->mName;
  15224. int prevSepPos = (int)name.LastIndexOf('$');
  15225. if (prevSepPos != -1)
  15226. {
  15227. name.RemoveToEnd(prevSepPos);
  15228. }
  15229. name += "@";
  15230. name += baseName;
  15231. HashContext hashCtx;
  15232. if (anchorNode != NULL)
  15233. {
  15234. hashCtx.Mixin(anchorNode->GetStartCharId());
  15235. }
  15236. //
  15237. {
  15238. auto checkMethodState = declMethodState;
  15239. auto checkMixinState = declMixinState;
  15240. while (checkMethodState != NULL)
  15241. {
  15242. if (checkMixinState != NULL)
  15243. {
  15244. hashCtx.Mixin(checkMixinState->mSource->GetStartCharId());
  15245. }
  15246. checkMethodState = checkMethodState->mPrevMethodState;
  15247. if (checkMethodState != NULL)
  15248. checkMixinState = checkMethodState->mMixinState;
  15249. }
  15250. }
  15251. auto rootMethodState = mCurMethodState->GetRootMethodState();
  15252. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  15253. {
  15254. for (auto methodGenericArg : rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  15255. {
  15256. StringT<128> genericTypeName;
  15257. BfMangler::Mangle(genericTypeName, mCompiler->GetMangleKind(), methodGenericArg);
  15258. hashCtx.MixinStr(genericTypeName);
  15259. }
  15260. }
  15261. uint64 hashVal = hashCtx.Finish64();
  15262. name += "$";
  15263. name += BfTypeUtils::HashEncode64(hashVal);
  15264. return name;
  15265. }
  15266. BfMethodDef* BfModule::GetLocalMethodDef(BfLocalMethod* localMethod)
  15267. {
  15268. if (localMethod->mMethodDef != NULL)
  15269. return localMethod->mMethodDef;
  15270. auto rootMethodState = mCurMethodState->GetRootMethodState();
  15271. auto declMethodState = localMethod->mDeclMethodState;
  15272. auto declMixinState = localMethod->mDeclMixinState;
  15273. auto typeInst = mCurTypeInstance;
  15274. BfAstNode* body = NULL;
  15275. BfAstNode* anchorNode = NULL;
  15276. auto _AllocDirectTypeRef = [&](BfType* type)
  15277. {
  15278. BfDirectTypeReference* directTypeRef = localMethod->mDirectTypeRefs.Alloc();
  15279. directTypeRef->Init(type);
  15280. return directTypeRef;
  15281. };
  15282. auto methodDeclaration = localMethod->mMethodDeclaration;
  15283. if (methodDeclaration != NULL)
  15284. {
  15285. body = methodDeclaration->mBody;
  15286. anchorNode = methodDeclaration->mOpenParen;
  15287. }
  15288. else
  15289. {
  15290. body = localMethod->mLambdaBindExpr->mBody;
  15291. anchorNode = localMethod->mLambdaBindExpr->mFatArrowToken;
  15292. }
  15293. BF_ASSERT(rootMethodState->mCurLocalVarId >= 0);
  15294. int methodLocalIdx = rootMethodState->mCurLocalVarId++;
  15295. BfMethodDef* methodDef;
  15296. if (methodDeclaration != NULL)
  15297. {
  15298. BfDefBuilder defBuilder(mCompiler->mSystem);
  15299. defBuilder.mPassInstance = mCompiler->mPassInstance;
  15300. defBuilder.mCurTypeDef = mCurMethodInstance->mMethodDef->mDeclaringType;
  15301. BfMethodDef* outerMethodDef = NULL;
  15302. if (localMethod->mOuterLocalMethod != NULL)
  15303. outerMethodDef = localMethod->mOuterLocalMethod->mMethodDef;
  15304. else
  15305. outerMethodDef = rootMethodState->mMethodInstance->mMethodDef;
  15306. methodDef = defBuilder.CreateMethodDef(methodDeclaration, outerMethodDef);
  15307. }
  15308. else
  15309. {
  15310. auto invokeMethod = localMethod->mLambdaInvokeMethodInstance;
  15311. methodDef = new BfMethodDef();
  15312. methodDef->mName = localMethod->mMethodName;
  15313. methodDef->mDeclaringType = mCurMethodInstance->mMethodDef->mDeclaringType;
  15314. methodDef->mReturnTypeRef = _AllocDirectTypeRef(invokeMethod->mReturnType);
  15315. methodDef->mBody = body;
  15316. for (int paramIdx = 0; paramIdx < invokeMethod->GetParamCount(); paramIdx++)
  15317. {
  15318. auto paramType = invokeMethod->GetParamType(paramIdx);
  15319. String paramName;
  15320. if (paramIdx < (int)localMethod->mLambdaBindExpr->mParams.size())
  15321. paramName = localMethod->mLambdaBindExpr->mParams[paramIdx]->ToString();
  15322. else
  15323. paramName = invokeMethod->GetParamName(paramIdx);
  15324. auto paramDef = new BfParameterDef();
  15325. paramDef->mTypeRef = _AllocDirectTypeRef(paramType);
  15326. paramDef->mName = paramName;
  15327. methodDef->mParams.Add(paramDef);
  15328. }
  15329. }
  15330. methodDef->mIdx = ~methodLocalIdx;
  15331. BF_ASSERT(!localMethod->mExpectedFullName.IsEmpty());
  15332. methodDef->mName = localMethod->mExpectedFullName;
  15333. // methodDef->mName = GetLocalMethodName(methodDef->mName, anchorNode, declMethodState, declMixinState);
  15334. //
  15335. // if (!localMethod->mExpectedFullName.IsEmpty())
  15336. // BF_ASSERT(methodDef->mName == localMethod->mExpectedFullName);
  15337. methodDef->mIsStatic = true;
  15338. methodDef->mIsLocalMethod = true;
  15339. methodDef->mIsVirtual = false;
  15340. localMethod->mMethodDef = methodDef;
  15341. auto methodInstanceGroup = new BfMethodInstanceGroup();
  15342. localMethod->mMethodInstanceGroup = methodInstanceGroup;
  15343. methodInstanceGroup->mMethodIdx = -1;
  15344. methodInstanceGroup->mOwner = mCurTypeInstance;
  15345. methodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  15346. if ((declMethodState->mMixinState != NULL) && (declMethodState->mMixinState->mTarget))
  15347. {
  15348. methodInstanceGroup->mOwner = declMethodState->mMixinState->mTarget.mType->ToTypeInstance();
  15349. BF_ASSERT(methodInstanceGroup->mOwner != NULL);
  15350. }
  15351. if ((mCompiler->mResolvePassData != NULL) && (methodDeclaration != NULL))
  15352. {
  15353. mCompiler->mResolvePassData->HandleLocalReference(methodDeclaration->mNameNode, typeInst->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, methodLocalIdx);
  15354. auto autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  15355. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(methodDeclaration->mNameNode)))
  15356. {
  15357. autoComplete->SetDefinitionLocation(methodDeclaration->mNameNode);
  15358. autoComplete->mInsertStartIdx = methodDeclaration->mNameNode->GetSrcStart();
  15359. autoComplete->mInsertEndIdx = methodDeclaration->mNameNode->GetSrcEnd();
  15360. autoComplete->mDefType = typeInst->mTypeDef;
  15361. autoComplete->mDefMethod = rootMethodState->mMethodInstance->mMethodDef;
  15362. autoComplete->mReplaceLocalId = methodLocalIdx;
  15363. }
  15364. }
  15365. return localMethod->mMethodDef;
  15366. }
  15367. BfModuleMethodInstance BfModule::GetLocalMethodInstance(BfLocalMethod* localMethod, const BfTypeVector& methodGenericArguments, BfMethodInstance* methodInstance, bool force)
  15368. {
  15369. BP_ZONE_F("GetLocalMethodInstance %s", localMethod->mMethodName.c_str());
  15370. BfLogSysM("GetLocalMethodInstance %p\n", localMethod);
  15371. auto rootMethodState = mCurMethodState->GetRootMethodState();
  15372. auto declMethodState = localMethod->mDeclMethodState;
  15373. auto declMixinState = localMethod->mDeclMixinState;
  15374. auto callerMethodState = mCurMethodState;
  15375. auto typeInst = mCurTypeInstance;
  15376. auto methodDef = GetLocalMethodDef(localMethod);
  15377. BfAstNode* body = NULL;
  15378. auto methodDeclaration = localMethod->mMethodDeclaration;
  15379. if (methodDeclaration != NULL)
  15380. {
  15381. body = methodDeclaration->mBody;
  15382. }
  15383. else
  15384. {
  15385. body = localMethod->mLambdaBindExpr->mBody;
  15386. }
  15387. bool hadConcreteInterfaceGenericArgument = false;
  15388. BfTypeVector sanitizedMethodGenericArguments;
  15389. // Ignore the outermost method's generic method arguments for the purpose of determining if we are the 'default' (ie: unspecialized)
  15390. // version of this method for this pass through the outermost method
  15391. int dependentGenericStartIdx = 0;
  15392. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  15393. dependentGenericStartIdx = (int)rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  15394. BfMethodInstance* outerMethodInstance = mCurMethodInstance;
  15395. if (methodGenericArguments.size() == 0)
  15396. {
  15397. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  15398. sanitizedMethodGenericArguments = rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments;
  15399. }
  15400. else
  15401. {
  15402. int genericArgIdx = 0;
  15403. // for (; genericArgIdx < (int)outerMethodInstance->mMethodGenericArguments.size(); genericArgIdx++)
  15404. // {
  15405. // BF_ASSERT(methodGenericArguments[genericArgIdx] == outerMethodInstance->mMethodGenericArguments[genericArgIdx]);
  15406. // sanitizedMethodGenericArguments.push_back(methodGenericArguments[genericArgIdx]);
  15407. // }
  15408. for (; genericArgIdx < (int)methodGenericArguments.size(); genericArgIdx++)
  15409. {
  15410. auto genericArgType = methodGenericArguments[genericArgIdx];
  15411. BF_ASSERT(!genericArgType->IsRef());
  15412. if (genericArgType->IsConcreteInterfaceType())
  15413. {
  15414. hadConcreteInterfaceGenericArgument = true;
  15415. auto concreteInterfaceType = (BfConcreteInterfaceType*)genericArgType;
  15416. genericArgType = concreteInterfaceType->mInterface;
  15417. }
  15418. sanitizedMethodGenericArguments.push_back(genericArgType);
  15419. }
  15420. }
  15421. bool wantPrematureMethodInstance = false;
  15422. if (!force)
  15423. {
  15424. wantPrematureMethodInstance = (callerMethodState->mClosureState != NULL) && (callerMethodState->mClosureState->mCaptureVisitingBody);
  15425. }
  15426. auto methodInstGroup = localMethod->mMethodInstanceGroup;
  15427. bool isDefaultPass = true;
  15428. BfTypeVector lookupMethodGenericArguments;
  15429. for (int genericArgIdx = dependentGenericStartIdx; genericArgIdx < (int)methodGenericArguments.size(); genericArgIdx++)
  15430. {
  15431. auto genericArgType = methodGenericArguments[genericArgIdx];
  15432. BF_ASSERT(!genericArgType->IsRef());
  15433. lookupMethodGenericArguments.Add(genericArgType);
  15434. if (genericArgType->IsGenericParam())
  15435. {
  15436. auto genericParam = (BfGenericParamType*)genericArgType;
  15437. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  15438. isDefaultPass = false;
  15439. }
  15440. else
  15441. {
  15442. isDefaultPass = false;
  15443. }
  15444. }
  15445. bool hadExistingMethodInstance = false;
  15446. if (methodInstance != NULL)
  15447. {
  15448. hadExistingMethodInstance = true;
  15449. }
  15450. else
  15451. {
  15452. if (isDefaultPass)
  15453. {
  15454. methodInstance = methodInstGroup->mDefault;
  15455. if (methodInstance != NULL)
  15456. {
  15457. hadExistingMethodInstance = true;
  15458. }
  15459. else
  15460. {
  15461. methodInstance = new BfMethodInstance();
  15462. methodInstGroup->mDefault = methodInstance;
  15463. }
  15464. }
  15465. else
  15466. {
  15467. BF_ASSERT(sanitizedMethodGenericArguments.size() != 0);
  15468. if (methodInstGroup->mMethodSpecializationMap == NULL)
  15469. methodInstGroup->mMethodSpecializationMap = new BfMethodInstanceGroup::MapType();
  15470. BfMethodInstance** methodInstancePtr = NULL;
  15471. if (!methodInstGroup->mMethodSpecializationMap->TryAdd(lookupMethodGenericArguments, NULL, &methodInstancePtr))
  15472. {
  15473. methodInstance = *methodInstancePtr;
  15474. hadExistingMethodInstance = true;
  15475. }
  15476. else
  15477. {
  15478. methodInstance = new BfMethodInstance();
  15479. *methodInstancePtr = methodInstance;
  15480. }
  15481. }
  15482. }
  15483. if (hadExistingMethodInstance)
  15484. {
  15485. if ((!methodInstance->mDisallowCalling) ||
  15486. ((wantPrematureMethodInstance) && (methodInstance->mDisallowCalling)))
  15487. return BfModuleMethodInstance(methodInstance);
  15488. BF_ASSERT((methodInstance->mMethodInfoEx == NULL) || (methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState == NULL));
  15489. }
  15490. else
  15491. {
  15492. auto methodInfoEx = methodInstance->GetMethodInfoEx();
  15493. methodInfoEx->mClosureInstanceInfo = new BfClosureInstanceInfo();
  15494. methodInfoEx->mClosureInstanceInfo->mLocalMethod = localMethod;
  15495. methodInstance->mIsReified = mCurMethodInstance->mIsReified;
  15496. methodInstance->mIsAutocompleteMethod = mCurMethodInstance->mIsAutocompleteMethod;
  15497. methodInstance->mMethodDef = methodDef;
  15498. methodInstance->mMethodInstanceGroup = localMethod->mMethodInstanceGroup;
  15499. if (hadConcreteInterfaceGenericArgument)
  15500. methodInstance->mIgnoreBody = true;
  15501. methodInfoEx->mMethodGenericArguments = sanitizedMethodGenericArguments;
  15502. for (auto genericArg : sanitizedMethodGenericArguments)
  15503. {
  15504. if (genericArg->IsPrimitiveType())
  15505. genericArg = GetWrappedStructType(genericArg);
  15506. AddDependency(genericArg, typeInst, BfDependencyMap::DependencyFlag_MethodGenericArg);
  15507. }
  15508. for (int genericParamIdx = (int)sanitizedMethodGenericArguments.size(); genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  15509. {
  15510. auto genericParamType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  15511. methodInfoEx->mMethodGenericArguments.push_back(genericParamType);
  15512. }
  15513. SetupMethodIdHash(methodInstance);
  15514. }
  15515. auto _SetupMethodInstance = [&]()
  15516. {
  15517. BF_ASSERT(methodInstance->GetNumGenericParams() == 0);
  15518. // Generic constraints
  15519. for (int genericParamIdx = 0; genericParamIdx < (int)methodDef->mGenericParams.size(); genericParamIdx++)
  15520. {
  15521. auto genericParamInstance = new BfGenericMethodParamInstance(methodDef, genericParamIdx);
  15522. methodInstance->GetMethodInfoEx()->mGenericParams.push_back(genericParamInstance);
  15523. }
  15524. };
  15525. //////////////////////////////////////////////////////////////////////////
  15526. auto _VisitLambdaBody = [&]()
  15527. {
  15528. if (localMethod->mDeclOnly)
  15529. return;
  15530. if (mCompiler->mCanceling)
  15531. return;
  15532. if (auto blockBody = BfNodeDynCast<BfBlock>(body))
  15533. {
  15534. VisitCodeBlock(blockBody);
  15535. }
  15536. else if (auto bodyExpr = BfNodeDynCast<BfExpression>(body))
  15537. CreateValueFromExpression(bodyExpr);
  15538. };
  15539. auto _SafeResolveTypeRef = [&](BfTypeReference* typeRef)
  15540. {
  15541. SetAndRestoreValue<bool> prevIgnoreError(mIgnoreErrors, true);
  15542. auto result = ResolveTypeRef(typeRef);
  15543. if (result == NULL)
  15544. result = mContext->mBfObjectType;
  15545. return result;
  15546. };
  15547. BfTypeInstance* outerClosure = NULL;
  15548. if ((declMethodState->mClosureState != NULL) && (!declMethodState->mClosureState->mCapturing))
  15549. outerClosure = declMethodState->mClosureState->mClosureType;
  15550. BfMethodState methodState;
  15551. methodState.mPrevMethodState = declMethodState;//mCurMethodState;
  15552. BfIRFunctionType funcType;
  15553. auto voidType = GetPrimitiveType(BfTypeCode_None);
  15554. SizedArray<BfIRType, 0> paramTypes;
  15555. funcType = mBfIRBuilder->CreateFunctionType(mBfIRBuilder->MapType(voidType), paramTypes, false);
  15556. mBfIRBuilder->SaveDebugLocation();
  15557. auto prevInsertBlock = mBfIRBuilder->GetInsertBlock();
  15558. auto prevActiveFunction = mBfIRBuilder->GetActiveFunction();
  15559. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  15560. BfDeferredLocalAssignData deferredLocalAssignData;
  15561. //TODO: Why did we do this? It can cause us to pull in local variables that don't belong to us...
  15562. /*if (declMethodState->mDeferredLocalAssignData != NULL)
  15563. deferredLocalAssignData.ExtendFrom(declMethodState->mDeferredLocalAssignData);*/
  15564. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  15565. methodState.mIRHeadBlock = mBfIRBuilder->CreateBlock("head", true);
  15566. methodState.mIRInitBlock = mBfIRBuilder->CreateBlock("init", true);
  15567. methodState.mIREntryBlock = mBfIRBuilder->CreateBlock("entry", true);
  15568. methodState.mCurScope->mDIScope = localMethod->mDeclDIScope; //declMethodState->mCurScope->mDIScope ;
  15569. //methodState.mCurLocalVarId = declMethodState->mCurLocalVarId;
  15570. methodState.mIRFunction = declMethodState->mIRFunction;
  15571. methodState.mDeferredLocalAssignData = &deferredLocalAssignData;
  15572. mBfIRBuilder->SetInsertPoint(methodState.mIREntryBlock);
  15573. BfClosureState closureState;
  15574. if (methodDef->mMethodType == BfMethodType_Mixin)
  15575. {
  15576. if (declMethodState != NULL)
  15577. {
  15578. if ((declMethodState->mClosureState != NULL) && (declMethodState->mClosureState->mReturnType != NULL))
  15579. closureState.mReturnType = declMethodState->mClosureState->mReturnType;
  15580. else if (declMethodState->mMethodInstance != NULL)
  15581. closureState.mReturnType = declMethodState->mMethodInstance->mReturnType;
  15582. }
  15583. }
  15584. if (closureState.mReturnType == NULL)
  15585. closureState.mReturnType = _SafeResolveTypeRef(methodDef->mReturnTypeRef);
  15586. closureState.mCapturing = true;
  15587. closureState.mLocalMethod = localMethod;
  15588. closureState.mClosureInstanceInfo = methodInstance->mMethodInfoEx->mClosureInstanceInfo;
  15589. closureState.mDeclaringMethodIsMutating = mCurMethodInstance->mMethodDef->mIsMutating;
  15590. methodState.mClosureState = &closureState;
  15591. closureState.mClosureType = outerClosure;
  15592. int outerLocalsCount = (int)methodState.mLocals.size();
  15593. if (!hadExistingMethodInstance)
  15594. {
  15595. BfLogSysM("LocalMethod %p premature DoMethodDeclaration %p (Source:%p)\n", localMethod, methodInstance, (methodDeclaration != NULL) ? methodDeclaration->GetSourceData() : NULL);
  15596. SetAndRestoreValue<bool> prevIgnoreWrites(mWantsIRIgnoreWrites, true);
  15597. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  15598. // Prematurely do declaration. We will have to undo this later, so don't write this one and don't throw errors
  15599. auto declareModule = this;
  15600. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  15601. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  15602. BF_ASSERT(declareModule != NULL);
  15603. methodInstance->mDeclModule = declareModule;
  15604. _SetupMethodInstance();
  15605. declareModule->DoMethodDeclaration(localMethod->mMethodDef->GetMethodDeclaration(), false, false);
  15606. methodInstance->mDisallowCalling = true; // Don't allow us to ACTUALLY call until we add the captures
  15607. }
  15608. if (wantPrematureMethodInstance)
  15609. {
  15610. // Return a premature methodInstance -- since we are partway through determining the capture of a local method, we can't rely on its
  15611. // capture information. This returned method instance can only be used for method matching, but we will visit it later to create
  15612. // its true method instance
  15613. //auto moduleMethodInstance = _CheckReturnedMethod(methodInstance);
  15614. //BF_ASSERT(moduleMethodInstance);
  15615. return BfModuleMethodInstance(methodInstance);
  15616. }
  15617. auto checkInsertBlock = mBfIRBuilder->GetInsertBlock();
  15618. BF_ASSERT(methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState == NULL);
  15619. closureState.mCaptureStartAccessId = mCurMethodState->GetRootMethodState()->mCurAccessId;
  15620. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState = &closureState;
  15621. closureState.mClosureMethodDef = methodDef;
  15622. bool wantsVisitBody = true;
  15623. if ((methodDef->mMethodType == BfMethodType_Mixin) && (!methodGenericArguments.IsEmpty()))
  15624. wantsVisitBody = false;
  15625. if (methodInstance->mIsUnspecializedVariation)
  15626. wantsVisitBody = false;
  15627. if (wantsVisitBody)
  15628. {
  15629. BP_ZONE("VisitLambdaBody");
  15630. // For generic methods, we capture for each specialization, so make sure mIsStatic is set to 'true' for
  15631. // this capture stage for each of those times
  15632. SetAndRestoreValue<bool> prevWasStatis(methodDef->mIsStatic, true);
  15633. /*
  15634. // Only generate errors once. Also there are some errors that will occur during this scanning phase
  15635. // that will not occur during the actual lambda method generation, for example: returning a value
  15636. // when our current method is a 'void' method. This shouldn't affect capture scanning since all
  15637. // our AST nodes will still be visited
  15638. SetAndRestoreValue<bool> ignoreError(mIgnoreErrors, true);
  15639. */
  15640. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  15641. //SetAndRestoreValue<bool> wantsIgnoreWrites(mWantsISIgnoreWrites, true);
  15642. mBfIRBuilder->SaveDebugLocation();
  15643. closureState.mCaptureVisitingBody = true;
  15644. BF_ASSERT(methodInstance->mMethodInfoEx != NULL);
  15645. methodState.mGenericTypeBindings = &methodInstance->mMethodInfoEx->mGenericTypeBindings;
  15646. NewScopeState();
  15647. ProcessMethod_SetupParams(methodInstance, NULL, false, NULL);
  15648. if (methodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)
  15649. {
  15650. // Allow assigning to arguments when we're capturing - which may or may not be legal at the injection site (we throw error there)
  15651. for (auto localDef : methodState.mLocals)
  15652. {
  15653. if (localDef->mResolvedType->IsVar())
  15654. continue;
  15655. localDef->mAddr = CreateAlloca(localDef->mResolvedType);
  15656. }
  15657. }
  15658. _VisitLambdaBody();
  15659. RestoreScopeState();
  15660. //ProcessMethod(methodInstance);
  15661. closureState.mCaptureVisitingBody = false;
  15662. mBfIRBuilder->RestoreDebugLocation();
  15663. }
  15664. // If we ended up being called by a method with a lower captureStartAccessId, propagate that to whoever is calling us, too...
  15665. if ((methodState.mPrevMethodState->mClosureState != NULL) && (methodState.mPrevMethodState->mClosureState->mCapturing))
  15666. {
  15667. auto prevClosureState = methodState.mPrevMethodState->mClosureState;
  15668. if (closureState.mCaptureStartAccessId < prevClosureState->mCaptureStartAccessId)
  15669. prevClosureState->mCaptureStartAccessId = closureState.mCaptureStartAccessId;
  15670. }
  15671. //RestoreScopeState();
  15672. // Actually get the referenced local methods. It's important we wait until after visiting the body, because then our own capture information
  15673. // can be used by these methods (which will be necessary if any of these methods call us directly or indirectly)
  15674. closureState.mClosureMethodDef = NULL;
  15675. for (auto methodInstance : closureState.mLocalMethodRefs)
  15676. {
  15677. GetLocalMethodInstance(methodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod, BfTypeVector(), methodInstance);
  15678. }
  15679. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState = NULL;
  15680. prevIgnoreWrites.Restore();
  15681. std::multiset<BfClosureCapturedEntry> capturedEntries;
  15682. //
  15683. {
  15684. auto varMethodState = declMethodState;
  15685. while (varMethodState != NULL)
  15686. {
  15687. if ((varMethodState->mMixinState != NULL) && (varMethodState->mMixinState->mLastTargetAccessId >= closureState.mCaptureStartAccessId))
  15688. {
  15689. BF_ASSERT(methodInstance->GetOwner() == varMethodState->mMixinState->mTarget.mType);
  15690. methodDef->mIsStatic = false;
  15691. if (rootMethodState->mMethodInstance->mMethodDef->mIsMutating)
  15692. methodDef->mIsMutating = true;
  15693. }
  15694. bool copyOuterCaptures = false;
  15695. for (int localIdx = 0; localIdx < varMethodState->mLocals.size(); localIdx++)
  15696. {
  15697. auto localVar = varMethodState->mLocals[localIdx];
  15698. if ((localVar->mReadFromId >= closureState.mCaptureStartAccessId) || (localVar->mWrittenToId >= closureState.mCaptureStartAccessId))
  15699. {
  15700. if (localVar->mIsThis)
  15701. {
  15702. // We can only set mutating if our owning type is mutating
  15703. if (localVar->mWrittenToId >= closureState.mCaptureStartAccessId)
  15704. {
  15705. if (mCurTypeInstance->IsValueType())
  15706. {
  15707. if (rootMethodState->mMethodInstance->mMethodDef->mIsMutating)
  15708. methodDef->mIsMutating = true;
  15709. }
  15710. }
  15711. methodDef->mIsStatic = false;
  15712. continue;
  15713. }
  15714. if ((localVar->mIsThis) && (outerClosure != NULL))
  15715. {
  15716. continue;
  15717. }
  15718. if ((localVar->mConstValue) || (localVar->mResolvedType->IsValuelessType()))
  15719. {
  15720. closureState.mConstLocals.push_back(*localVar);
  15721. continue;
  15722. }
  15723. BfClosureCapturedEntry capturedEntry;
  15724. auto capturedType = localVar->mResolvedType;
  15725. bool captureByRef = false;
  15726. if (!capturedType->IsRef())
  15727. {
  15728. if (localVar->mIsThis)
  15729. {
  15730. if ((localVar->mResolvedType->IsValueType()) && (mCurMethodInstance->mMethodDef->HasNoThisSplat()))
  15731. captureByRef = true;
  15732. }
  15733. else if ((!localVar->mIsReadOnly) && (localVar->mWrittenToId >= closureState.mCaptureStartAccessId))
  15734. captureByRef = true;
  15735. }
  15736. else
  15737. {
  15738. if (localVar->mWrittenToId < closureState.mCaptureStartAccessId)
  15739. {
  15740. capturedType = ((BfRefType*)capturedType)->mElementType;
  15741. }
  15742. }
  15743. if (captureByRef)
  15744. {
  15745. //capturedEntry.mIsByReference = true;
  15746. capturedType = CreateRefType(capturedType);
  15747. }
  15748. else
  15749. {
  15750. //capturedEntry.mIsByReference = false;
  15751. }
  15752. capturedEntry.mNameNode = localVar->mNameNode;
  15753. capturedEntry.mType = capturedType;
  15754. capturedEntry.mName = localVar->mName;
  15755. //capturedEntry.mLocalVarDef = localVar;
  15756. capturedEntries.insert(capturedEntry);
  15757. }
  15758. }
  15759. varMethodState = varMethodState->mPrevMethodState;
  15760. if ((varMethodState == NULL) ||
  15761. (varMethodState->mMixinState != NULL) ||
  15762. ((varMethodState->mClosureState != NULL) && (!varMethodState->mClosureState->mCapturing)))
  15763. break;
  15764. }
  15765. }
  15766. for (auto& copyField : closureState.mReferencedOuterClosureMembers)
  15767. {
  15768. auto fieldDef = copyField->GetFieldDef();
  15769. BfClosureCapturedEntry capturedEntry;
  15770. capturedEntry.mName = copyField->GetFieldDef()->mName;
  15771. capturedEntry.mType = copyField->mResolvedType;
  15772. if (capturedEntry.mType->IsRef())
  15773. {
  15774. // Keep by ref
  15775. }
  15776. else if (!fieldDef->mIsReadOnly)
  15777. {
  15778. capturedEntry.mType = CreateRefType(capturedEntry.mType);
  15779. }
  15780. capturedEntries.insert(capturedEntry);
  15781. }
  15782. int captureIdx = 0;
  15783. for (auto& capturedEntry : capturedEntries)
  15784. {
  15785. methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries.Add(capturedEntry);
  15786. }
  15787. /*if (isDefaultPass)
  15788. {
  15789. // Insert captured members a params at the start. If we added at the end then it would screw up varargs methods
  15790. int captureIdx = 0;
  15791. for (auto& capturedEntry : capturedEntries)
  15792. {
  15793. methodInstance->mClosureInstanceInfo->mCaptureNodes.Add(BfNodeDynCast<BfIdentifierNode>(capturedEntry.mNameNode));
  15794. BfParameterDef* paramDef = new BfParameterDef();
  15795. paramDef->mName = capturedEntry.mName;
  15796. BfDirectTypeReference* directTypeRef = new BfDirectTypeReference();
  15797. directTypeRef->mType = capturedEntry.mType;
  15798. typeInst->mTypeDef->mDirectAllocNodes.push_back(directTypeRef);
  15799. paramDef->mTypeRef = directTypeRef;
  15800. paramDef->mParamKind = BfParamKind_ImplicitCapture;
  15801. methodDef->mParams.Insert(captureIdx, paramDef);
  15802. captureIdx++;
  15803. }
  15804. }
  15805. else
  15806. {
  15807. auto defaultMethodInstance = methodInstGroup->mDefault;
  15808. methodInstance->mClosureInstanceInfo->mCaptureNodes = defaultMethodInstance->mClosureInstanceInfo->mCaptureNodes;
  15809. }*/
  15810. methodState.Reset();
  15811. closureState.mCapturing = false;
  15812. //////////////////////////////////////////////////////////////////////////
  15813. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, false);
  15814. if (methodInstance->mReturnType != NULL)
  15815. {
  15816. BF_ASSERT(methodInstance->mDisallowCalling);
  15817. // We did a premature declaration (without captures)
  15818. methodInstance->UndoDeclaration();
  15819. methodInstance->mDisallowCalling = false;
  15820. BfLogSysM("LocalMethod %p UndoingDeclaration %p\n", localMethod, methodInstance);
  15821. }
  15822. auto declareModule = this;
  15823. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(declareModule->mCurMethodInstance, methodInstance);
  15824. SetAndRestoreValue<BfFilePosition> prevFilePos(declareModule->mCurFilePosition);
  15825. BF_ASSERT(declareModule != NULL);
  15826. methodInstance->mDeclModule = declareModule;
  15827. _SetupMethodInstance();
  15828. BfLogSysM("LocalMethod %p DoMethodDeclaration %p\n", localMethod, methodInstance);
  15829. declareModule->DoMethodDeclaration(localMethod->mMethodDef->GetMethodDeclaration(), false, false);
  15830. closureState.mReturnType = methodInstance->mReturnType;
  15831. mCompiler->mStats.mMethodsQueued++;
  15832. mCompiler->UpdateCompletion();
  15833. declareModule->mIncompleteMethodCount++;
  15834. mCompiler->mStats.mMethodsProcessed++;
  15835. if (!methodInstance->mIsReified)
  15836. mCompiler->mStats.mUnreifiedMethodsProcessed++;
  15837. auto deferMethodState = rootMethodState;
  15838. // 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)
  15839. if ((!localMethod->mDeclOnly) && (!methodInstance->mIsUnspecializedVariation) &&
  15840. (!mWantsIRIgnoreWrites) && (methodDef->mMethodType != BfMethodType_Mixin))
  15841. {
  15842. BP_ZONE("BfDeferredLocalMethod:create");
  15843. BfDeferredLocalMethod* deferredLocalMethod = new BfDeferredLocalMethod();
  15844. deferredLocalMethod->mLocalMethod = localMethod;
  15845. deferredLocalMethod->mConstLocals = closureState.mConstLocals;
  15846. deferredLocalMethod->mMethodInstance = methodInstance;
  15847. auto checkMethodState = declMethodState;
  15848. while (checkMethodState != NULL)
  15849. {
  15850. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mActiveDeferredLocalMethod != NULL))
  15851. {
  15852. for (auto& mixinRecord : checkMethodState->mClosureState->mActiveDeferredLocalMethod->mMixinStateRecords)
  15853. deferredLocalMethod->mMixinStateRecords.Add(mixinRecord);
  15854. }
  15855. if (checkMethodState->mMixinState != NULL)
  15856. {
  15857. BfMixinRecord mixinRecord;
  15858. mixinRecord.mSource = checkMethodState->mMixinState->mSource;
  15859. deferredLocalMethod->mMixinStateRecords.Add(mixinRecord);
  15860. }
  15861. checkMethodState = checkMethodState->mPrevMethodState;
  15862. }
  15863. rootMethodState->mDeferredLocalMethods.Add(deferredLocalMethod);
  15864. }
  15865. mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  15866. mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  15867. mBfIRBuilder->RestoreDebugLocation();
  15868. if (methodInstance == localMethod->mMethodInstanceGroup->mDefault)
  15869. {
  15870. auto checkMethodState = mCurMethodState;
  15871. while (checkMethodState != NULL)
  15872. {
  15873. BfLocalMethod* nextLocalMethod = NULL;
  15874. if (checkMethodState->mLocalMethodMap.TryGetValue(localMethod->mMethodName, &nextLocalMethod))
  15875. {
  15876. while (nextLocalMethod != NULL)
  15877. {
  15878. auto checkLocalMethod = nextLocalMethod;
  15879. nextLocalMethod = nextLocalMethod->mNextWithSameName;
  15880. if (checkLocalMethod == localMethod)
  15881. continue;
  15882. if (checkLocalMethod->mMethodInstanceGroup == NULL)
  15883. continue;
  15884. auto checkMethodInstance = checkLocalMethod->mMethodInstanceGroup->mDefault;
  15885. if (checkMethodInstance == NULL)
  15886. continue; // Not generated yet
  15887. if (CompareMethodSignatures(localMethod->mMethodInstanceGroup->mDefault, checkMethodInstance))
  15888. {
  15889. auto bfError = Fail("Method already declared with the same parameter types", methodInstance->mMethodDef->GetRefNode(), true);
  15890. if (bfError != NULL)
  15891. mCompiler->mPassInstance->MoreInfo("First declaration", checkMethodInstance->mMethodDef->GetRefNode());
  15892. }
  15893. }
  15894. }
  15895. checkMethodState = checkMethodState->mPrevMethodState;
  15896. }
  15897. }
  15898. return BfModuleMethodInstance(methodInstance);
  15899. }
  15900. int BfModule::GetLocalInferrableGenericArgCount(BfMethodDef* methodDef)
  15901. {
  15902. if ((!methodDef->mIsLocalMethod) || (methodDef->mGenericParams.size() == 0))
  15903. return 0;
  15904. auto rootMethodState = mCurMethodState->GetRootMethodState();
  15905. int rootMethodGenericParamCount = 0;
  15906. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  15907. rootMethodGenericParamCount = (int)rootMethodState->mMethodInstance->mMethodInfoEx->mGenericParams.size();
  15908. if (mCurMethodInstance == NULL)
  15909. return rootMethodGenericParamCount;
  15910. if ((mCurMethodInstance->mMethodInfoEx == NULL) || (mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo == NULL))
  15911. return rootMethodGenericParamCount;
  15912. BfLocalMethod* callerLocalMethod = mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo->mLocalMethod;
  15913. if (callerLocalMethod == NULL)
  15914. return rootMethodGenericParamCount;
  15915. BfLocalMethod* calledLocalMethod = NULL;
  15916. rootMethodState->mLocalMethodCache.TryGetValue(methodDef->mName, &calledLocalMethod);
  15917. while ((calledLocalMethod != NULL) && (callerLocalMethod != NULL))
  15918. {
  15919. if (calledLocalMethod->mOuterLocalMethod == callerLocalMethod)
  15920. return (int)callerLocalMethod->mMethodDef->mGenericParams.size();
  15921. callerLocalMethod = calledLocalMethod->mOuterLocalMethod;
  15922. }
  15923. return rootMethodGenericParamCount;
  15924. }
  15925. void BfModule::GetMethodCustomAttributes(BfMethodInstance* methodInstance)
  15926. {
  15927. auto methodDef = methodInstance->mMethodDef;
  15928. if (methodInstance->GetCustomAttributes() != NULL)
  15929. return;
  15930. auto methodDeclaration = methodDef->GetMethodDeclaration();
  15931. auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration();
  15932. auto typeInstance = methodInstance->GetOwner();
  15933. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  15934. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  15935. if ((methodDeclaration != NULL) && (methodDeclaration->mAttributes != NULL))
  15936. {
  15937. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes == NULL)
  15938. methodInstance->mMethodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  15939. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes = GetCustomAttributes(methodDeclaration->mAttributes,
  15940. ((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend)) ? BfAttributeTargets_Constructor : BfAttributeTargets_Method);
  15941. }
  15942. else if ((propertyMethodDeclaration != NULL) && (propertyMethodDeclaration->mAttributes != NULL))
  15943. {
  15944. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes == NULL)
  15945. methodInstance->mMethodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  15946. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mCustomAttributes = GetCustomAttributes(propertyMethodDeclaration->mAttributes, BfAttributeTargets_Method);
  15947. }
  15948. }
  15949. void BfModule::SetupIRFunction(BfMethodInstance* methodInstance, StringImpl& mangledName, bool isTemporaryFunc, bool* outIsIntrinsic)
  15950. {
  15951. if (methodInstance->GetImportCallKind() == BfImportCallKind_GlobalVar)
  15952. {
  15953. // Don't create a func
  15954. return;
  15955. }
  15956. auto typeInstance = methodInstance->GetOwner();
  15957. auto methodDef = methodInstance->mMethodDef;
  15958. BfIRFunctionType funcType = mBfIRBuilder->MapMethod(methodInstance);
  15959. // Don't set these pointers during resolve pass because they may become invalid if it's just a temporary autocomplete method
  15960. if (mCompiler->mResolvePassData == NULL)
  15961. {
  15962. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mIsStatic))
  15963. {
  15964. typeInstance->mHasStaticInitMethod = true;
  15965. }
  15966. if ((methodDef->mMethodType == BfMethodType_Dtor) && (methodDef->mIsStatic))
  15967. {
  15968. typeInstance->mHasStaticDtorMethod = true;
  15969. }
  15970. if ((methodDef->mMethodType == BfMethodType_Normal) && (methodDef->mIsStatic) && (methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC))
  15971. {
  15972. typeInstance->mHasStaticMarkMethod = true;
  15973. }
  15974. if ((methodDef->mMethodType == BfMethodType_Normal) && (methodDef->mIsStatic) && (methodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS))
  15975. {
  15976. typeInstance->mHasTLSFindMethod = true;
  15977. }
  15978. }
  15979. if (isTemporaryFunc)
  15980. {
  15981. BF_ASSERT((mCompiler->mIsResolveOnly) && (mCompiler->mResolvePassData->mAutoComplete != NULL));
  15982. mangledName = "autocomplete_tmp";
  15983. }
  15984. if (!mBfIRBuilder->mIgnoreWrites)
  15985. {
  15986. BfIRFunction prevFunc;
  15987. // Remove old version (if we have one)
  15988. prevFunc = mBfIRBuilder->GetFunction(mangledName);
  15989. if (prevFunc)
  15990. {
  15991. if (methodDef->mIsExtern)
  15992. {
  15993. // Allow this
  15994. BfLogSysM("Function collision allowed multiple extern functions for %p: %d\n", methodInstance, prevFunc.mId);
  15995. }
  15996. else if (typeInstance->IsIRFuncUsed(prevFunc))
  15997. {
  15998. // We can have a collision of names when we have generic methods that differ only in
  15999. // their constraints, but they should only collide in their unspecialized form
  16000. // since only one will be chosen for a given concrete type
  16001. mCurMethodInstance->mMangleWithIdx = true;
  16002. mangledName.Clear();
  16003. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  16004. prevFunc = mBfIRBuilder->GetFunction(mangledName);
  16005. BfLogSysM("Function collision forced mangleWithIdx for %p: %d\n", methodInstance, prevFunc.mId);
  16006. }
  16007. else
  16008. {
  16009. BfLogSysM("Function collision erased prevFunc %p: %d\n", methodInstance, prevFunc.mId);
  16010. mBfIRBuilder->Func_EraseFromParent(prevFunc);
  16011. }
  16012. }
  16013. }
  16014. if (typeInstance != mContext->mBfObjectType)
  16015. {
  16016. // Only allow attributes on System.Object methods that can be handled inside the DefBuilder
  16017. GetMethodCustomAttributes(methodInstance);
  16018. }
  16019. // if (prevFunc)
  16020. // {
  16021. // if (methodDef->mIsExtern)
  16022. // {
  16023. // BfLogSysM("Reusing function for %p: %d\n", methodInstance, prevFunc.mId);
  16024. // methodInstance->mIRFunction = prevFunc;
  16025. // }
  16026. // else
  16027. // {
  16028. // if ((methodInstance->IsSpecializedByAutoCompleteMethod()) ||
  16029. // ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mResolveType >= BfResolveType_GoToDefinition)))
  16030. // {
  16031. // // If we're doing re-pass over the methods for something like BfResolveType_ShowFileSymbolReferences, then allow this collision
  16032. // BfLogSysM("Ignoring function name collision\n");
  16033. // }
  16034. // else
  16035. // {
  16036. // if (methodDef->mMethodDeclaration == NULL)
  16037. // {
  16038. // AssertErrorState();
  16039. // }
  16040. // else
  16041. // {
  16042. // BF_ASSERT(mIsSpecialModule);
  16043. // if ((mCompiler->mRevision == 1) && (HasCompiledOutput()))
  16044. // {
  16045. // // We shouldn't have name collisions on the first run!
  16046. // AssertErrorState();
  16047. // }
  16048. // }
  16049. // }
  16050. // BfLogSysM("Before erase\n");
  16051. // mBfIRBuilder->Func_EraseFromParent(prevFunc);
  16052. // }
  16053. // }
  16054. bool isIntrinsic = false;
  16055. if (!methodInstance->mIRFunction)
  16056. {
  16057. BfIRFunction func;
  16058. bool wantsLLVMFunc = ((!typeInstance->IsUnspecializedType()) && (!methodDef->IsEmptyPartial())) && (funcType);
  16059. /*if (mCurTypeInstance->mTypeDef->mName->ToString() == "ClassA")
  16060. {
  16061. if (!mIsReified)
  16062. wantsLLVMFunc = false;
  16063. }*/
  16064. if (wantsLLVMFunc)
  16065. {
  16066. func = GetIntrinsic(methodInstance, true);
  16067. if (func)
  16068. {
  16069. isIntrinsic = true;
  16070. }
  16071. else
  16072. {
  16073. func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, mangledName);
  16074. BfLogSysM("Creating FuncId:%d %s in module %p\n", func.mId, mangledName.c_str(), this);
  16075. if (methodInstance->mAlwaysInline)
  16076. mBfIRBuilder->Func_AddAttribute(func, -1, BFIRAttribute_AlwaysInline);
  16077. // if (prevFunc)
  16078. // BfLogSysM("Removing Func %d, replacing with %d\n", prevFunc.mId, func.mId);
  16079. }
  16080. methodInstance->mIRFunction = func;
  16081. //if (!ignoreWrites)
  16082. //BF_ASSERT(!func.IsFake());
  16083. }
  16084. }
  16085. if (outIsIntrinsic != NULL)
  16086. *outIsIntrinsic = isIntrinsic;
  16087. if (!isIntrinsic)
  16088. SetupIRMethod(methodInstance, methodInstance->mIRFunction, methodInstance->mAlwaysInline);
  16089. }
  16090. void BfModule::CheckHotMethod(BfMethodInstance* methodInstance, const StringImpl& inMangledName)
  16091. {
  16092. if (methodInstance->mHotMethod != NULL)
  16093. return;
  16094. if ((mCompiler->mOptions.mAllowHotSwapping) && (!methodInstance->mIsUnspecialized))
  16095. {
  16096. auto srcTypeInst = methodInstance->GetOwner();
  16097. StringT<128> mangledName = inMangledName;
  16098. if (mangledName.IsEmpty())
  16099. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  16100. // We always keep the current primary method at the same address
  16101. BfHotMethod* hotMethod;
  16102. BfHotMethod** hotMethodPtr;
  16103. if (mCompiler->mHotData->mMethodMap.TryAdd(mangledName, NULL, &hotMethodPtr))
  16104. {
  16105. hotMethod = new BfHotMethod();
  16106. *hotMethodPtr = hotMethod;
  16107. hotMethod->mRefCount = 1;
  16108. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  16109. #ifdef BF_DBG_HOTMETHOD_IDX
  16110. static int sMethodIdx = 0;
  16111. hotMethod->mMethodIdx = sMethodIdx++;
  16112. #endif
  16113. BfLogSysM("HotMethodData %p created for method %p %s - %s\n", hotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  16114. }
  16115. else
  16116. {
  16117. hotMethod = *hotMethodPtr;
  16118. if ((hotMethod->mFlags & BfHotDepDataFlag_IsBound) != 0)
  16119. {
  16120. // This is a duplicate mangled name - we link to this new entry via a 'BfHotDupMethod'
  16121. auto prevHotMethod = *hotMethodPtr;
  16122. hotMethod = new BfHotMethod();
  16123. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  16124. BfHotDupMethod* hotDupMethod = new BfHotDupMethod(hotMethod);
  16125. hotDupMethod->mRefCount++;
  16126. prevHotMethod->mReferences.Add(hotDupMethod);
  16127. prevHotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_HasDup);
  16128. BfLogSysM("HotMethodData %p (duplicate of %p) created for method %p %s - %s\n", hotMethod, prevHotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  16129. }
  16130. else if (mCompiler->IsHotCompile())
  16131. {
  16132. // Link the previous version into the mPrevVersion
  16133. BfHotMethod* prevMethod = new BfHotMethod();
  16134. prevMethod->mRefCount = 1;
  16135. prevMethod->mPrevVersion = hotMethod->mPrevVersion;
  16136. hotMethod->mPrevVersion = prevMethod;
  16137. prevMethod->mSrcTypeVersion = hotMethod->mSrcTypeVersion;
  16138. hotMethod->mSrcTypeVersion = NULL;
  16139. prevMethod->mFlags = hotMethod->mFlags;
  16140. hotMethod->mFlags = BfHotDepDataFlag_IsBound;
  16141. hotMethod->mReferences.MoveTo(prevMethod->mReferences);
  16142. #ifdef BF_DBG_HOTMETHOD_NAME
  16143. prevMethod->mMangledName = hotMethod->mMangledName;
  16144. #endif
  16145. BfLogSysM("HotMethodData %p created for prevmethod of %p for method %p %s\n", prevMethod, hotMethod, methodInstance, MethodToString(methodInstance).c_str());
  16146. }
  16147. else
  16148. {
  16149. BfLogSysM("HotMethodData %p used for method %p %s - %s\n", hotMethod, methodInstance, MethodToString(methodInstance).c_str(), mangledName.c_str());
  16150. hotMethod->Clear(true);
  16151. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_IsBound);
  16152. }
  16153. }
  16154. if (methodInstance->mIsClosure)
  16155. {
  16156. hotMethod->mFlags = (BfHotDepDataFlags)(hotMethod->mFlags | BfHotDepDataFlag_RetainMethodWithoutBinding);
  16157. }
  16158. hotMethod->mSrcTypeVersion = srcTypeInst->mHotTypeData->GetLatestVersion();
  16159. hotMethod->mSrcTypeVersion->mRefCount++;
  16160. hotMethod->mRefCount++;
  16161. #ifdef BF_DBG_HOTMETHOD_NAME
  16162. hotMethod->mMangledName = mangledName;
  16163. #endif
  16164. methodInstance->mHotMethod = hotMethod;
  16165. }
  16166. }
  16167. // methodDeclaration is NULL for default constructors
  16168. void BfModule::DoMethodDeclaration(BfMethodDeclaration* methodDeclaration, bool isTemporaryFunc, bool addToWorkList)
  16169. {
  16170. BP_ZONE("BfModule::BfMethodDeclaration");
  16171. // We could trigger a DoMethodDeclaration from a const resolver or other location, so we reset it here
  16172. // to effectively make mIgnoreWrites method-scoped
  16173. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mWantsIRIgnoreWrites || mCurMethodInstance->mIsUnspecialized);
  16174. SetAndRestoreValue<bool> prevIsCapturingMethodMatchInfo;
  16175. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, NULL);
  16176. if (mCompiler->IsAutocomplete())
  16177. prevIsCapturingMethodMatchInfo.Init(mCompiler->mResolvePassData->mAutoComplete->mIsCapturingMethodMatchInfo, false);
  16178. if (mCurMethodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference)
  16179. mCurMethodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingReference;
  16180. bool ignoreWrites = mBfIRBuilder->mIgnoreWrites;
  16181. if (mAwaitingInitFinish)
  16182. FinishInit();
  16183. auto typeInstance = mCurTypeInstance;
  16184. auto typeDef = typeInstance->mTypeDef;
  16185. auto methodDef = mCurMethodInstance->mMethodDef;
  16186. BF_ASSERT(methodDef->mName != "__ASSERTNAME");
  16187. if (typeInstance->IsClosure())
  16188. {
  16189. if (methodDef->mName == "Invoke")
  16190. return;
  16191. }
  16192. auto methodInstance = mCurMethodInstance;
  16193. if ((methodInstance->IsSpecializedByAutoCompleteMethod()) || (mCurTypeInstance->IsFunction()))
  16194. addToWorkList = false;
  16195. bool hasNonGenericParams = false;
  16196. bool hasGenericParams = false;
  16197. int dependentGenericStartIdx = 0;
  16198. if (methodDef->mIsLocalMethod)
  16199. {
  16200. // If we're a local generic method inside an outer generic method, we can still be considered unspecialized
  16201. // if our outer method's generic args are specialized but ours are unspecialized. This is because locals get
  16202. // instantiated uniquely for each specialized or unspecialized pass through the outer method, but the local
  16203. // method still 'inherits' the outer's generic arguments -- but we still need to make an unspecialized pass
  16204. // over the local method each time
  16205. auto rootMethodInstance = prevMethodState.mPrevVal->GetRootMethodState()->mMethodInstance;
  16206. dependentGenericStartIdx = 0;
  16207. if (rootMethodInstance->mMethodInfoEx != NULL)
  16208. dependentGenericStartIdx = (int)rootMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  16209. methodInstance->mIsUnspecialized = rootMethodInstance->mIsUnspecialized;
  16210. methodInstance->mIsUnspecializedVariation = rootMethodInstance->mIsUnspecializedVariation;
  16211. }
  16212. for (int genericArgIdx = dependentGenericStartIdx; genericArgIdx < (int) methodInstance->GetNumGenericArguments(); genericArgIdx++)
  16213. {
  16214. auto genericArgType = methodInstance->mMethodInfoEx->mMethodGenericArguments[genericArgIdx];
  16215. if (genericArgType->IsGenericParam())
  16216. {
  16217. hasGenericParams = true;
  16218. auto genericParam = (BfGenericParamType*)genericArgType;
  16219. methodInstance->mIsUnspecialized = true;
  16220. if ((genericParam->mGenericParamKind != BfGenericParamKind_Method) || (genericParam->mGenericParamIdx != genericArgIdx))
  16221. methodInstance->mIsUnspecializedVariation = true;
  16222. }
  16223. else
  16224. {
  16225. hasNonGenericParams = true;
  16226. if (genericArgType->IsUnspecializedType())
  16227. {
  16228. methodInstance->mIsUnspecialized = true;
  16229. methodInstance->mIsUnspecializedVariation = true;
  16230. }
  16231. }
  16232. }
  16233. if ((hasGenericParams) && (hasNonGenericParams))
  16234. {
  16235. methodInstance->mIsUnspecializedVariation = true;
  16236. }
  16237. if (typeInstance->IsUnspecializedType())
  16238. {
  16239. // A specialized method within an unspecialized type is considered an unspecialized variation -- in the sense that we don't
  16240. // actually want to do method processing on it
  16241. if ((!methodInstance->mIsUnspecialized) && (methodInstance->GetNumGenericArguments() != 0))
  16242. methodInstance->mIsUnspecializedVariation = true;
  16243. methodInstance->mIsUnspecialized = true;
  16244. }
  16245. methodInstance->mIsUnspecializedVariation |= typeInstance->IsUnspecializedTypeVariation();
  16246. for (auto genericParamDef : methodDef->mGenericParams)
  16247. {
  16248. if (mCompiler->IsAutocomplete())
  16249. {
  16250. auto autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  16251. //autoComplete->CheckTypeRef()
  16252. }
  16253. }
  16254. if (methodInstance->mIsUnspecializedVariation)
  16255. {
  16256. }
  16257. if (methodInstance->mIsUnspecializedVariation)
  16258. BF_ASSERT(methodInstance->mIsUnspecialized);
  16259. if (methodDef->mMethodType == BfMethodType_Mixin)
  16260. methodInstance->mIsUnspecialized = true;
  16261. BfAutoComplete* bfAutocomplete = NULL;
  16262. if (mCompiler->mResolvePassData != NULL)
  16263. bfAutocomplete = mCompiler->mResolvePassData->mAutoComplete;
  16264. if (methodInstance->mMethodInfoEx != NULL)
  16265. {
  16266. for (int genericParamIdx = 0; genericParamIdx < (int)methodInstance->mMethodInfoEx->mGenericParams.size(); genericParamIdx++)
  16267. {
  16268. auto genericParam = methodInstance->mMethodInfoEx->mGenericParams[genericParamIdx];
  16269. if (genericParamIdx < (int)methodDef->mGenericParams.size())
  16270. {
  16271. genericParam->mExternType = GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  16272. }
  16273. else
  16274. {
  16275. auto externConstraintDef = genericParam->GetExternConstraintDef();
  16276. genericParam->mExternType = ResolveTypeRef(externConstraintDef->mTypeRef);
  16277. auto autoComplete = mCompiler->GetAutoComplete();
  16278. if (autoComplete != NULL)
  16279. autoComplete->CheckTypeRef(externConstraintDef->mTypeRef, false);
  16280. if (genericParam->mExternType != NULL)
  16281. {
  16282. //
  16283. }
  16284. else
  16285. genericParam->mExternType = GetPrimitiveType(BfTypeCode_Var);
  16286. }
  16287. ResolveGenericParamConstraints(genericParam, methodInstance->mIsUnspecialized);
  16288. if (genericParamIdx < (int)methodDef->mGenericParams.size())
  16289. {
  16290. auto genericParamDef = methodDef->mGenericParams[genericParamIdx];
  16291. if (bfAutocomplete != NULL)
  16292. {
  16293. for (auto nameNode : genericParamDef->mNameNodes)
  16294. {
  16295. HandleMethodGenericParamRef(nameNode, typeDef, methodDef, genericParamIdx);
  16296. }
  16297. }
  16298. }
  16299. }
  16300. for (auto genericParam : methodInstance->mMethodInfoEx->mGenericParams)
  16301. {
  16302. for (auto constraintTypeInst : genericParam->mInterfaceConstraints)
  16303. AddDependency(constraintTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  16304. if (genericParam->mTypeConstraint != NULL)
  16305. AddDependency(genericParam->mTypeConstraint, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  16306. }
  16307. }
  16308. if ((methodInstance->mIsAutocompleteMethod) && (methodDeclaration != NULL) && (!methodInstance->IsSpecializedGenericMethod()) && (methodDef->mIdx >= 0))
  16309. {
  16310. auto autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  16311. BfAstNode* nameNode = methodDeclaration->mNameNode;
  16312. if (nameNode == NULL)
  16313. {
  16314. if (auto ctorDeclaration = BfNodeDynCast<BfConstructorDeclaration>(methodDeclaration))
  16315. nameNode = ctorDeclaration->mThisToken;
  16316. }
  16317. if (autoComplete->IsAutocompleteNode(nameNode))
  16318. {
  16319. autoComplete->mInsertStartIdx = nameNode->GetSrcStart();
  16320. autoComplete->mInsertEndIdx = nameNode->GetSrcEnd();
  16321. autoComplete->mDefType = typeDef;
  16322. autoComplete->mDefMethod = methodDef;
  16323. autoComplete->SetDefinitionLocation(nameNode);
  16324. if (methodDef->mIsOverride)
  16325. {
  16326. for (int virtIdx = 0; virtIdx < (int)typeInstance->mVirtualMethodTable.size(); virtIdx++)
  16327. {
  16328. auto& ventry = typeInstance->mVirtualMethodTable[virtIdx];
  16329. if (ventry.mDeclaringMethod.mMethodNum == -1)
  16330. continue;
  16331. BfMethodInstance* virtMethod = ventry.mImplementingMethod;
  16332. if (virtMethod != NULL)
  16333. {
  16334. auto virtMethodDeclaration = virtMethod->mMethodDef->GetMethodDeclaration();
  16335. if ((virtMethod->GetOwner() == typeInstance) && (virtMethodDeclaration != NULL) &&
  16336. (virtMethodDeclaration->GetSrcStart() == methodDeclaration->GetSrcStart()))
  16337. {
  16338. // Is matching method
  16339. if (virtIdx < (int)typeInstance->mBaseType->mVirtualMethodTable.size())
  16340. {
  16341. auto baseType = typeInstance->mBaseType;
  16342. if (baseType != NULL)
  16343. {
  16344. while ((baseType->mBaseType != NULL) && (virtIdx < baseType->mBaseType->mVirtualMethodTableSize))
  16345. baseType = baseType->mBaseType;
  16346. BfMethodInstance* baseVirtMethod = baseType->mVirtualMethodTable[virtIdx].mImplementingMethod;
  16347. autoComplete->SetDefinitionLocation(baseVirtMethod->mMethodDef->GetRefNode(), true);
  16348. autoComplete->mDefType = baseType->mTypeDef;
  16349. autoComplete->mDefMethod = baseVirtMethod->mMethodDef;
  16350. }
  16351. }
  16352. break;
  16353. }
  16354. }
  16355. }
  16356. }
  16357. }
  16358. }
  16359. bool reportErrors = true;
  16360. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  16361. reportErrors = true;
  16362. // Only the defining contexts needs to report errors here
  16363. SetAndRestoreValue<bool> prevReporErrors(mReportErrors, reportErrors);
  16364. if (methodDef->mMethodType == BfMethodType_Dtor)
  16365. {
  16366. if (methodDef->mIsStatic)
  16367. {
  16368. }
  16369. else
  16370. {
  16371. if ((typeInstance->IsStruct()) || (typeInstance->IsTypedPrimitive()))
  16372. {
  16373. BfAstNode* refNode = methodDeclaration;
  16374. if (refNode == NULL)
  16375. {
  16376. // Whatever caused this ctor to be generated should have caused another failure
  16377. // But that failure might not be generated until the ctor is generated
  16378. }
  16379. else
  16380. {
  16381. auto dtorDecl = BfNodeDynCast<BfDestructorDeclaration>(methodDeclaration);
  16382. if (dtorDecl != NULL)
  16383. refNode = dtorDecl->mThisToken;
  16384. Fail("Structs cannot have destructors", refNode);
  16385. }
  16386. }
  16387. auto methodDeclaration = methodDef->GetMethodDeclaration();
  16388. if ((methodDeclaration != NULL) && (methodDeclaration->mVirtualSpecifier != NULL) &&
  16389. (mCurTypeInstance != mContext->mBfObjectType))
  16390. {
  16391. Fail("Virtual specifier is not required, all destructors are implicitly virtual.", methodDeclaration->mVirtualSpecifier);
  16392. }
  16393. }
  16394. }
  16395. BfType* resolvedReturnType = NULL;
  16396. if (((methodDef->mMethodType == BfMethodType_Normal) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend) || (methodDef->mMethodType == BfMethodType_PropertyGetter) || (methodDef->mMethodType == BfMethodType_Operator)) &&
  16397. (methodDef->mReturnTypeRef != NULL))
  16398. {
  16399. SetAndRestoreValue<bool> prevIngoreErrors(mIgnoreErrors, mIgnoreErrors || (methodDef->GetPropertyDeclaration() != NULL));
  16400. resolvedReturnType = ResolveTypeRef(methodDef->mReturnTypeRef, BfPopulateType_Declaration,
  16401. (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_AllowRef | BfResolveTypeRefFlag_AllowRefGeneric));
  16402. if ((resolvedReturnType != NULL) && (resolvedReturnType->IsVar()) && (methodDef->mMethodType != BfMethodType_Mixin))
  16403. {
  16404. Fail("Cannot declare var return types", methodDef->mReturnTypeRef);
  16405. resolvedReturnType = GetPrimitiveType(BfTypeCode_Var);
  16406. }
  16407. if (resolvedReturnType == NULL)
  16408. resolvedReturnType = GetPrimitiveType(BfTypeCode_Var);
  16409. }
  16410. else
  16411. {
  16412. resolvedReturnType = ResolveTypeDef(mSystem->mTypeVoid);
  16413. }
  16414. BF_ASSERT(resolvedReturnType != NULL);
  16415. mCurMethodInstance->mReturnType = resolvedReturnType;
  16416. //TODO: We used to NOT add the return value dependency for specialized methods, but when we have types that are
  16417. // specialized based on the method's generic param then they can get deleted if no one else has referred to them (yet)
  16418. //if (!methodInstance->IsSpecializedGenericMethod())
  16419. AddDependency(resolvedReturnType, typeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  16420. if (methodDef->mExplicitInterface != NULL)
  16421. {
  16422. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  16423. mCompiler->mResolvePassData->mAutoComplete->CheckTypeRef(methodDef->mExplicitInterface, false);
  16424. auto explicitInterface = ResolveTypeRef(methodDef->mExplicitInterface, BfPopulateType_Declaration);
  16425. if (explicitInterface != NULL)
  16426. mCurMethodInstance->GetMethodInfoEx()->mExplicitInterface = explicitInterface->ToTypeInstance();
  16427. if ((mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mExplicitInterface != NULL))
  16428. {
  16429. bool interfaceFound = false;
  16430. for (auto ifaceInst : typeInstance->mInterfaces)
  16431. interfaceFound |= ifaceInst.mInterfaceType == mCurMethodInstance->mMethodInfoEx->mExplicitInterface;
  16432. if (!interfaceFound)
  16433. {
  16434. if (methodDef->mMethodDeclaration != NULL)
  16435. Fail("Containing class has not declared to implement this interface", methodDef->mMethodDeclaration);
  16436. else
  16437. {
  16438. // For property decls, we should have already given the error during type population
  16439. if (mCompiler->mRevision == 1)
  16440. AssertErrorState();
  16441. }
  16442. }
  16443. }
  16444. }
  16445. bool isThisStruct = mCurTypeInstance->IsStruct();
  16446. BfType* thisType = NULL;
  16447. if ((!methodDef->mIsStatic) && (!mCurTypeInstance->IsValuelessType()))
  16448. {
  16449. if ((isThisStruct) || (mCurTypeInstance->IsTypedPrimitive()))
  16450. {
  16451. thisType = mCurTypeInstance;
  16452. if (thisType == NULL)
  16453. return;
  16454. if ((thisType->IsSplattable()) && (!methodDef->HasNoThisSplat()))
  16455. {
  16456. BfTypeUtils::SplatIterate([&](BfType* checkType)
  16457. {
  16458. PopulateType(checkType, BfPopulateType_Data);
  16459. }, thisType);
  16460. }
  16461. }
  16462. else
  16463. {
  16464. thisType = mCurTypeInstance;
  16465. PopulateType(thisType, BfPopulateType_Declaration);
  16466. }
  16467. }
  16468. int implicitParamCount = 0;
  16469. if ((mCurMethodInstance->mMethodInfoEx != NULL) && (mCurMethodInstance->mMethodInfoEx->mClosureInstanceInfo != NULL))
  16470. implicitParamCount = (int)methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries.size();
  16471. methodInstance->mMethodDef->mParams.Reserve((int)methodDef->mParams.size());
  16472. bool hadDelegateParams = false;
  16473. bool hadParams = false;
  16474. for (int paramIdx = 0; paramIdx < (int)methodDef->mParams.size() + implicitParamCount; paramIdx++)
  16475. {
  16476. BfClosureCapturedEntry* closureCaptureEntry = NULL;
  16477. BfParameterDef* paramDef = NULL;
  16478. int paramDefIdx = -1;
  16479. if (paramIdx < implicitParamCount)
  16480. closureCaptureEntry = &methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries[paramIdx];
  16481. else
  16482. {
  16483. paramDefIdx = paramIdx - implicitParamCount;
  16484. paramDef = methodDef->mParams[paramDefIdx];
  16485. }
  16486. if (hadParams)
  16487. break;
  16488. if ((paramDef != NULL) && (mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL) &&
  16489. (paramDef->mParamKind != BfParamKind_AppendIdx))
  16490. mCompiler->mResolvePassData->mAutoComplete->CheckTypeRef(paramDef->mTypeRef, false);
  16491. if ((paramDef != NULL) && (paramDef->mParamDeclaration != NULL) && (paramDef->mParamDeclaration->mAttributes != NULL))
  16492. {
  16493. if (methodInstance->GetMethodInfoEx()->mMethodCustomAttributes == NULL)
  16494. methodInstance->mMethodInfoEx->mMethodCustomAttributes = new BfMethodCustomAttributes();
  16495. while ((int)methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.size() < paramIdx)
  16496. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.push_back(NULL);
  16497. auto customAttributes = GetCustomAttributes(paramDef->mParamDeclaration->mAttributes, BfAttributeTargets_Parameter);
  16498. methodInstance->mMethodInfoEx->mMethodCustomAttributes->mParamCustomAttributes.push_back(customAttributes);
  16499. }
  16500. BfType* resolvedParamType = NULL;
  16501. if (closureCaptureEntry != NULL)
  16502. resolvedParamType = closureCaptureEntry->mType;
  16503. else if (paramDef->mTypeRef->IsA<BfLetTypeReference>())
  16504. {
  16505. Fail("Cannot declare 'let' parameters", paramDef->mTypeRef);
  16506. resolvedParamType = mContext->mBfObjectType;
  16507. }
  16508. else if (paramDef->mTypeRef->IsA<BfVarTypeReference>())
  16509. {
  16510. if (methodDef->mMethodType != BfMethodType_Mixin)
  16511. {
  16512. Fail("Cannot declare var parameters", paramDef->mTypeRef);
  16513. resolvedParamType = mContext->mBfObjectType;
  16514. }
  16515. else
  16516. resolvedParamType = GetPrimitiveType(BfTypeCode_Var);
  16517. }
  16518. BfType* unresolvedParamType = resolvedParamType;
  16519. bool wasGenericParam = false;
  16520. if (resolvedParamType == NULL)
  16521. {
  16522. SetAndRestoreValue<bool> prevIngoreErrors(mIgnoreErrors, mIgnoreErrors || (methodDef->GetPropertyDeclaration() != NULL));
  16523. resolvedParamType = ResolveTypeRef(paramDef->mTypeRef, BfPopulateType_Declaration,
  16524. (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_AllowRef | BfResolveTypeRefFlag_AllowRefGeneric | BfResolveTypeRefFlag_AllowGenericMethodParamConstValue));
  16525. }
  16526. if (resolvedParamType == NULL)
  16527. {
  16528. resolvedParamType = GetPrimitiveType(BfTypeCode_Var);
  16529. unresolvedParamType = resolvedParamType;
  16530. if (mCurTypeInstance->IsBoxed())
  16531. {
  16532. auto boxedType = (BfBoxedType*)mCurTypeInstance;
  16533. // If we failed a lookup here then we better have also failed it in the original type
  16534. BF_ASSERT(boxedType->mElementType->mModule->mHadBuildError || mContext->mFailTypes.Contains(boxedType->mElementType));
  16535. }
  16536. }
  16537. if (!methodInstance->IsSpecializedGenericMethod())
  16538. AddDependency(resolvedParamType, typeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  16539. PopulateType(resolvedParamType, BfPopulateType_Declaration);
  16540. AddDependency(resolvedParamType, mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
  16541. if ((paramDef != NULL) && (paramDef->mParamDeclaration != NULL) && (paramDef->mParamDeclaration->mInitializer != NULL) &&
  16542. (!paramDef->mParamDeclaration->mInitializer->IsA<BfBlock>()))
  16543. {
  16544. BfMethodState methodState;
  16545. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  16546. methodState.mTempKind = BfMethodState::TempKind_Static;
  16547. BfTypedValue defaultValue;
  16548. if (resolvedParamType->IsConstExprValue())
  16549. {
  16550. auto constExprType = (BfConstExprValueType*)resolvedParamType;
  16551. BfExprEvaluator exprEvaluator(this);
  16552. exprEvaluator.mExpectingType = constExprType->mType;
  16553. exprEvaluator.GetLiteral(NULL, constExprType->mValue);
  16554. defaultValue = exprEvaluator.GetResult();
  16555. }
  16556. else
  16557. {
  16558. BfConstResolver constResolver(this);
  16559. defaultValue = constResolver.Resolve(paramDef->mParamDeclaration->mInitializer, resolvedParamType, BfConstResolveFlag_NoCast);
  16560. if ((defaultValue) && (defaultValue.mType != resolvedParamType))
  16561. {
  16562. SetAndRestoreValue<bool> prevIgnoreWrite(mBfIRBuilder->mIgnoreWrites, true);
  16563. auto castedDefaultValue = Cast(paramDef->mParamDeclaration->mInitializer, defaultValue, resolvedParamType, (BfCastFlags)(BfCastFlags_SilentFail | BfCastFlags_NoConversionOperator));
  16564. if ((castedDefaultValue) && (castedDefaultValue.mValue.IsConst()))
  16565. {
  16566. defaultValue = castedDefaultValue; // Good!
  16567. }
  16568. else if (!CanImplicitlyCast(defaultValue, resolvedParamType))
  16569. {
  16570. // We only care that we get a constant value that can be implicitly casted at the callsite- even if that requires
  16571. // a conversion operator.
  16572. // This should throw an error
  16573. defaultValue = Cast(paramDef->mParamDeclaration->mInitializer, defaultValue, resolvedParamType);
  16574. AssertErrorState();
  16575. if (!defaultValue.mValue.IsConst())
  16576. defaultValue = BfTypedValue();
  16577. }
  16578. }
  16579. }
  16580. if (!defaultValue)
  16581. {
  16582. defaultValue = GetDefaultTypedValue(resolvedParamType);
  16583. if (!defaultValue.mValue.IsConst())
  16584. defaultValue = BfTypedValue();
  16585. }
  16586. if (defaultValue)
  16587. {
  16588. BF_ASSERT(defaultValue.mValue.IsConst());
  16589. while ((int)mCurMethodInstance->mDefaultValues.size() < paramDefIdx)
  16590. mCurMethodInstance->mDefaultValues.Add(BfIRValue());
  16591. CurrentAddToConstHolder(defaultValue.mValue);
  16592. mCurMethodInstance->mDefaultValues.Add(defaultValue.mValue);
  16593. }
  16594. }
  16595. if ((paramDef != NULL) && (paramDef->mParamKind == BfParamKind_Params))
  16596. {
  16597. bool addParams = true;
  16598. bool isValid = false;
  16599. auto resolvedParamTypeInst = resolvedParamType->ToTypeInstance();
  16600. if ((resolvedParamTypeInst != NULL) && (resolvedParamTypeInst->mTypeDef == mCompiler->mSpanTypeDef))
  16601. {
  16602. // Span<T>
  16603. isValid = true;
  16604. }
  16605. else if (resolvedParamType->IsArray())
  16606. {
  16607. // Array is the 'normal' params type
  16608. isValid = true;
  16609. }
  16610. else if ((resolvedParamType->IsDelegate()) || (resolvedParamType->IsFunction()))
  16611. {
  16612. hadDelegateParams = true;
  16613. // This means we copy the params from a delegate
  16614. BfMethodParam methodParam;
  16615. methodParam.mResolvedType = resolvedParamType;
  16616. methodParam.mParamDefIdx = paramDefIdx;
  16617. methodParam.mDelegateParamIdx = 0;
  16618. auto invokeMethodInstance = methodParam.GetDelegateParamInvoke();
  16619. for (int delegateParamIdx = 0; delegateParamIdx < invokeMethodInstance->GetParamCount(); delegateParamIdx++)
  16620. {
  16621. methodParam.mDelegateParamIdx = delegateParamIdx;
  16622. mCurMethodInstance->mParams.Add(methodParam);
  16623. auto paramType = invokeMethodInstance->GetParamType(delegateParamIdx);
  16624. if (!methodInstance->IsSpecializedGenericMethod())
  16625. AddDependency(paramType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  16626. }
  16627. isValid = true;
  16628. addParams = false;
  16629. }
  16630. else if (resolvedParamType->IsGenericParam())
  16631. {
  16632. auto genericParamInstance = GetGenericParamInstance((BfGenericParamType*)resolvedParamType);
  16633. if (genericParamInstance->mTypeConstraint != NULL)
  16634. {
  16635. auto typeInstConstraint = genericParamInstance->mTypeConstraint->ToTypeInstance();
  16636. if (genericParamInstance->mTypeConstraint->IsArray())
  16637. {
  16638. BfMethodParam methodParam;
  16639. methodParam.mResolvedType = resolvedParamType;
  16640. methodParam.mParamDefIdx = paramDefIdx;
  16641. mCurMethodInstance->mParams.Add(methodParam);
  16642. isValid = true;
  16643. }
  16644. else if ((genericParamInstance->mTypeConstraint->IsDelegate()) || (genericParamInstance->mTypeConstraint->IsFunction()) ||
  16645. ((genericParamInstance != NULL) && (typeInstConstraint != NULL) &&
  16646. ((typeInstConstraint->mTypeDef == mCompiler->mDelegateTypeDef) || (typeInstConstraint->mTypeDef == mCompiler->mFunctionTypeDef))))
  16647. {
  16648. mCurMethodInstance->mHadGenericDelegateParams = true;
  16649. isValid = true;
  16650. addParams = false;
  16651. }
  16652. }
  16653. }
  16654. else
  16655. {
  16656. auto paramTypeInst = resolvedParamType->ToTypeInstance();
  16657. if ((paramTypeInst != NULL) &&
  16658. ((paramTypeInst->mTypeDef == mCompiler->mDelegateTypeDef) || (paramTypeInst->mTypeDef == mCompiler->mFunctionTypeDef)))
  16659. {
  16660. // If we have a 'params T' and 'T' gets specialized with actually 'Delegate' or 'Function' then just ignore it
  16661. isValid = true;
  16662. addParams = false;
  16663. }
  16664. }
  16665. if (!isValid)
  16666. {
  16667. Fail("Parameters with 'params' specifiers can only be used for array, span, delegate, or function types", paramDef->mParamDeclaration->mModToken);
  16668. // Failure case, make it an Object[]
  16669. resolvedParamType = CreateArrayType(mContext->mBfObjectType, 1);
  16670. }
  16671. if (addParams)
  16672. {
  16673. BfMethodParam methodParam;
  16674. methodParam.mResolvedType = resolvedParamType;
  16675. methodParam.mParamDefIdx = paramDefIdx;
  16676. mCurMethodInstance->mParams.push_back(methodParam);
  16677. }
  16678. if (paramDefIdx < (int)methodDef->mParams.size() - 1)
  16679. {
  16680. Fail("Only the last parameter can specify 'params'", paramDef->mParamDeclaration->mModToken);
  16681. }
  16682. }
  16683. else
  16684. {
  16685. BfMethodParam methodParam;
  16686. methodParam.mResolvedType = resolvedParamType;
  16687. methodParam.mParamDefIdx = paramDefIdx;
  16688. mCurMethodInstance->mParams.Add(methodParam);
  16689. }
  16690. }
  16691. if (hadDelegateParams)
  16692. {
  16693. HashSet<String> usedNames;
  16694. Dictionary<int, int> usedParamDefIdx;
  16695. for (auto methodParam : methodDef->mParams)
  16696. {
  16697. usedNames.Add(methodParam->mName);
  16698. }
  16699. for (auto& methodParam : mCurMethodInstance->mParams)
  16700. {
  16701. if ((methodParam.mParamDefIdx != -1) && (methodParam.mDelegateParamIdx == 0))
  16702. {
  16703. int* refCount = NULL;
  16704. usedParamDefIdx.TryAdd(methodParam.mParamDefIdx, NULL, &refCount);
  16705. (*refCount)++;
  16706. }
  16707. }
  16708. for (auto& methodParam : mCurMethodInstance->mParams)
  16709. {
  16710. if (methodParam.mDelegateParamIdx != -1)
  16711. {
  16712. if (usedParamDefIdx[methodParam.mParamDefIdx] > 1)
  16713. methodParam.mDelegateParamNameCombine = true;
  16714. BfMethodInstance* invokeMethodInstance = methodParam.GetDelegateParamInvoke();
  16715. String paramName = invokeMethodInstance->GetParamName(methodParam.mDelegateParamIdx);
  16716. if (usedNames.Contains(paramName))
  16717. methodParam.mDelegateParamNameCombine = true;
  16718. }
  16719. }
  16720. }
  16721. int argIdx = 0;
  16722. PopulateType(methodInstance->mReturnType, BfPopulateType_Data);
  16723. if (methodInstance->HasStructRet())
  16724. argIdx++;
  16725. if (!methodDef->mIsStatic)
  16726. {
  16727. if (methodInstance->GetParamIsSplat(-1))
  16728. argIdx += methodInstance->GetParamType(-1)->GetSplatCount();
  16729. else if (!methodInstance->GetOwner()->IsValuelessType())
  16730. argIdx++;
  16731. }
  16732. for (auto& methodParam : mCurMethodInstance->mParams)
  16733. {
  16734. if (methodParam.mResolvedType->IsMethodRef())
  16735. {
  16736. methodParam.mIsSplat = true;
  16737. }
  16738. else if (methodParam.mResolvedType->IsComposite())
  16739. {
  16740. PopulateType(methodParam.mResolvedType, BfPopulateType_Data);
  16741. if (methodParam.mResolvedType->IsSplattable())
  16742. {
  16743. int splatCount = methodParam.mResolvedType->GetSplatCount();
  16744. if (argIdx + splatCount <= mCompiler->mOptions.mMaxSplatRegs)
  16745. {
  16746. methodParam.mIsSplat = true;
  16747. argIdx += splatCount;
  16748. continue;
  16749. }
  16750. }
  16751. }
  16752. argIdx++;
  16753. }
  16754. bool hasExternSpecifier = (methodDeclaration != NULL) && (methodDeclaration->mExternSpecifier != NULL);
  16755. if ((hasExternSpecifier) && (methodDeclaration->mBody != NULL))
  16756. {
  16757. Fail("Cannot 'extern' and declare a body", methodDeclaration->mExternSpecifier);
  16758. }
  16759. else if ((methodDeclaration != NULL) && (methodDeclaration->mBody == NULL) && (!hasExternSpecifier) &&
  16760. (!typeInstance->IsInterface()) && (!mCurTypeInstance->IsDelegate()) && (!mCurTypeInstance->IsFunction()) &&
  16761. (!methodDef->mIsPartial) && (!methodDef->mIsAbstract) &&
  16762. (!methodDef->mIsSkipCall))
  16763. {
  16764. if (methodDeclaration->mEndSemicolon == NULL)
  16765. {
  16766. AssertParseErrorState();
  16767. }
  16768. else
  16769. {
  16770. bool isError = true;
  16771. if (typeInstance->IsTypedPrimitive())
  16772. {
  16773. if (auto operatorDeclaration = BfNodeDynCast<BfOperatorDeclaration>(methodDeclaration))
  16774. {
  16775. if ((operatorDeclaration->mIsConvOperator) && (methodInstance->mParams.size() == 1))
  16776. {
  16777. if (((methodInstance->mReturnType == typeInstance) && (methodInstance->GetParamType(0) == typeInstance->GetUnderlyingType())) ||
  16778. ((methodInstance->mReturnType == typeInstance->GetUnderlyingType()) && (methodInstance->GetParamType(0) == typeInstance)))
  16779. {
  16780. isError = false;
  16781. }
  16782. }
  16783. }
  16784. }
  16785. if (isError)
  16786. {
  16787. Fail(StrFormat("'%s' must declare a body because it is not marked abstract, extern, or partial",
  16788. MethodToString(methodInstance).c_str()),
  16789. methodDef->GetRefNode());
  16790. }
  16791. }
  16792. }
  16793. if (methodDef->IsEmptyPartial())
  16794. hasExternSpecifier = true;
  16795. if (!methodInstance->IsAutocompleteMethod())
  16796. {
  16797. auto defaultMethodInstance = methodInstance->mMethodInstanceGroup->mDefault;
  16798. int implicitParamCount = methodInstance->GetImplicitParamCount();
  16799. int defaultImplicitParamCount = defaultMethodInstance->GetImplicitParamCount();
  16800. int actualParamCount = (int)methodInstance->mParams.size() - implicitParamCount;
  16801. BF_ASSERT((actualParamCount == defaultMethodInstance->mParams.size() - defaultImplicitParamCount) || (defaultMethodInstance->mHadGenericDelegateParams));
  16802. mCurMethodInstance->mHadGenericDelegateParams = defaultMethodInstance->mHadGenericDelegateParams;
  16803. int paramIdx = 0;
  16804. int defaultParamIdx = 0;
  16805. while (true)
  16806. {
  16807. bool isDone = paramIdx + implicitParamCount >= (int)methodInstance->mParams.size();
  16808. bool isDefaultDone = defaultParamIdx + defaultImplicitParamCount >= (int)defaultMethodInstance->mParams.size();
  16809. if ((!isDone) && (methodInstance->mParams[paramIdx + implicitParamCount].mDelegateParamIdx >= 0))
  16810. {
  16811. paramIdx++;
  16812. continue;
  16813. }
  16814. if ((!isDefaultDone) && (defaultMethodInstance->mParams[defaultParamIdx + defaultImplicitParamCount].mDelegateParamIdx >= 0))
  16815. {
  16816. defaultParamIdx++;
  16817. continue;
  16818. }
  16819. if ((isDone) || (isDefaultDone))
  16820. {
  16821. // 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
  16822. // to cause us to throw an assertion in the declaration here
  16823. if (!defaultMethodInstance->mHadGenericDelegateParams)
  16824. BF_ASSERT((isDone) && (isDefaultDone));
  16825. break;
  16826. }
  16827. methodInstance->mParams[paramIdx + implicitParamCount].mWasGenericParam = defaultMethodInstance->mParams[defaultParamIdx + defaultImplicitParamCount].mResolvedType->IsGenericParam();
  16828. paramIdx++;
  16829. defaultParamIdx++;
  16830. }
  16831. }
  16832. StringT<128> mangledName;
  16833. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), mCurMethodInstance);
  16834. for (int paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  16835. {
  16836. auto paramType = methodInstance->GetParamType(paramIdx);
  16837. if (paramType->IsComposite())
  16838. PopulateType(paramType, BfPopulateType_Data);
  16839. if (!methodInstance->IsParamSkipped(paramIdx))
  16840. {
  16841. if (paramType->IsStruct())
  16842. {
  16843. //
  16844. }
  16845. else
  16846. {
  16847. PopulateType(paramType, BfPopulateType_Declaration);
  16848. }
  16849. }
  16850. }
  16851. // Only process method in default unspecialized mode, not in variations
  16852. if (methodInstance->mIsUnspecializedVariation)
  16853. return;
  16854. PopulateType(resolvedReturnType, BfPopulateType_Data);
  16855. auto retLLVMType = mBfIRBuilder->MapType(resolvedReturnType);
  16856. if (resolvedReturnType->IsValuelessType())
  16857. retLLVMType = mBfIRBuilder->GetPrimitiveType(BfTypeCode_None);
  16858. if (!mBfIRBuilder->mIgnoreWrites)
  16859. {
  16860. bool isIntrinsic = false;
  16861. if (!methodInstance->mIRFunction)
  16862. SetupIRFunction(methodInstance, mangledName, isTemporaryFunc, &isIntrinsic);
  16863. if (isIntrinsic)
  16864. {
  16865. addToWorkList = false;
  16866. }
  16867. }
  16868. auto func = methodInstance->mIRFunction;
  16869. // if (methodInstance->mIsReified)
  16870. // CheckHotMethod(methodInstance, mangledName);
  16871. 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);
  16872. SizedArray<BfIRMDNode, 8> diParams;
  16873. diParams.push_back(mBfIRBuilder->DbgGetType(resolvedReturnType));
  16874. if ((!methodDef->mIsStatic) && (typeDef->mIsStatic) && (methodDef->mMethodDeclaration != NULL))
  16875. {
  16876. //CS0708
  16877. Fail("Cannot declare instance members in a static class", methodDef->GetRefNode());
  16878. }
  16879. if ((methodDef->mIsVirtual) && (methodDef->mGenericParams.size() != 0))
  16880. {
  16881. Fail("Virtual generic methods not supported", methodDeclaration->mVirtualSpecifier);
  16882. methodDef->mIsVirtual = false;
  16883. }
  16884. if ((methodDeclaration != NULL) && (methodDeclaration->mMutSpecifier != NULL) && (!mCurTypeInstance->IsBoxed()) && (!methodInstance->mIsForeignMethodDef))
  16885. {
  16886. if (methodDef->mIsStatic)
  16887. Warn(0, "Unnecessary 'mut' specifier, static methods have no implicit 'this' target to mutate", methodDeclaration->mMutSpecifier);
  16888. else if ((!mCurTypeInstance->IsValueType()) && (!mCurTypeInstance->IsInterface()))
  16889. Warn(0, "Unnecessary 'mut' specifier, methods of reference types are implicitly mutating", methodDeclaration->mMutSpecifier);
  16890. else if (methodDef->mMethodType == BfMethodType_Ctor)
  16891. Warn(0, "Unnecessary 'mut' specifier, constructors are implicitly mutating", methodDeclaration->mMutSpecifier);
  16892. else if (methodDef->mMethodType == BfMethodType_Dtor)
  16893. Warn(0, "Unnecessary 'mut' specifier, destructors are implicitly mutating", methodDeclaration->mMutSpecifier);
  16894. }
  16895. if (isTemporaryFunc)
  16896. {
  16897. // This handles temporary methods for autocomplete types
  16898. BF_ASSERT(mIsScratchModule);
  16899. BF_ASSERT(mCompiler->IsAutocomplete());
  16900. BfLogSysM("DoMethodDeclaration autocomplete bailout\n");
  16901. return; // Bail out early for autocomplete pass
  16902. }
  16903. //TODO: We used to have this (this != mContext->mExternalFuncModule) check, but it caused us to keep around
  16904. // an invalid mFuncRefernce (which came from GetMethodInstanceAtIdx) which later got remapped by the
  16905. // autocompleter. Why did we have this check anyway?
  16906. /*if ((typeInstance->mContext != mContext) && (!methodDef->IsEmptyPartial()))
  16907. {
  16908. AddMethodReference(methodInstance);
  16909. mFuncReferences[methodInstance] = func;
  16910. BfLogSysM("Adding func reference (DoMethodDeclaration). Module:%p MethodInst:%p LLVMFunc:%p\n", this, methodInstance, func);
  16911. }*/
  16912. if (mParentModule != NULL)
  16913. {
  16914. // For extension modules we need to keep track of our own methods so we can know which methods
  16915. // we have defined ourselves and which are from the parent module or other extensions
  16916. if (!func.IsFake())
  16917. mFuncReferences[methodInstance] = func;
  16918. }
  16919. if (addToWorkList)
  16920. {
  16921. bool wasAwaitingDecl = methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl;
  16922. if (wasAwaitingDecl)
  16923. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingReference;
  16924. if ((!methodDef->mIsAbstract) && (!methodInstance->mIgnoreBody))
  16925. {
  16926. if (!wasAwaitingDecl)
  16927. AddMethodToWorkList(methodInstance);
  16928. }
  16929. else
  16930. {
  16931. BfLogSysM("DoMethodDeclaration ignoring method body %d %d %d\n", hasExternSpecifier, methodDef->mIsAbstract, methodInstance->mIgnoreBody);
  16932. methodInstance->mIgnoreBody = true;
  16933. if (typeInstance->IsUnspecializedType())
  16934. {
  16935. // Don't hold on to actual Function for unspecialized types
  16936. methodInstance->mIRFunction = BfIRFunction();
  16937. }
  16938. }
  16939. }
  16940. if ((!methodInstance->IsSpecializedGenericMethodOrType()) && (!mCurTypeInstance->IsBoxed()) &&
  16941. (!methodDef->mIsLocalMethod) &&
  16942. (!CheckDefineMemberProtection(methodDef->mProtection, methodInstance->mReturnType)))
  16943. {
  16944. if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  16945. {
  16946. //TODO:
  16947. //CS0053
  16948. Fail(StrFormat("Inconsistent accessibility: property type '%s' is less accessible than property '%s'",
  16949. TypeToString(methodInstance->mReturnType).c_str(), MethodToString(methodInstance).c_str()),
  16950. methodDef->mReturnTypeRef, true);
  16951. }
  16952. else
  16953. {
  16954. //CS0050
  16955. Fail(StrFormat("Inconsistent accessibility: return type '%s' is less accessible than method '%s'",
  16956. TypeToString(methodInstance->mReturnType).c_str(), MethodToString(methodInstance).c_str()),
  16957. methodDef->mReturnTypeRef, true);
  16958. }
  16959. }
  16960. if ((typeInstance->IsInterface()) && (methodDef->mMethodType == BfMethodType_Ctor))
  16961. {
  16962. Fail("Interfaces cannot contain constructors", methodDeclaration);
  16963. }
  16964. // Don't compare specialized generic methods against normal methods
  16965. if ((((mCurMethodInstance->mIsUnspecialized) || (mCurMethodInstance->mMethodDef->mGenericParams.size() == 0))) &&
  16966. (!methodDef->mIsLocalMethod))
  16967. {
  16968. if (!methodInstance->mIsForeignMethodDef)
  16969. {
  16970. typeDef->PopulateMemberSets();
  16971. BfMethodDef* nextMethod = NULL;
  16972. BfMemberSetEntry* entry = NULL;
  16973. if (typeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  16974. nextMethod = (BfMethodDef*)entry->mMemberDef;
  16975. while (nextMethod != NULL)
  16976. {
  16977. auto checkMethod = nextMethod;
  16978. nextMethod = nextMethod->mNextWithSameName;
  16979. if ((checkMethod != methodDef) && (typeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault != NULL))
  16980. {
  16981. auto checkMethodInstance = typeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  16982. if (((checkMethodInstance->mChainType == BfMethodChainType_None) || (checkMethodInstance->mChainType == BfMethodChainType_ChainHead)) &&
  16983. (checkMethodInstance->GetExplicitInterface() == methodInstance->GetExplicitInterface()) &&
  16984. (CompareMethodSignatures(checkMethodInstance, mCurMethodInstance)))
  16985. {
  16986. bool canChain = false;
  16987. if ((methodDef->mParams.empty()) &&
  16988. (checkMethodInstance->mMethodDef->mIsStatic == methodInstance->mMethodDef->mIsStatic))
  16989. {
  16990. if ((methodDef->mMethodType == BfMethodType_CtorNoBody) || (methodDef->mMethodType == BfMethodType_Dtor))
  16991. canChain = true;
  16992. else if (methodDef->mMethodType == BfMethodType_Normal)
  16993. {
  16994. if ((methodDef->mName == BF_METHODNAME_MARKMEMBERS) ||
  16995. (methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC) ||
  16996. (methodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS))
  16997. canChain = true;
  16998. }
  16999. }
  17000. if (canChain)
  17001. {
  17002. bool isBetter;
  17003. bool isWorse;
  17004. CompareDeclTypes(checkMethodInstance->mMethodDef->mDeclaringType, methodInstance->mMethodDef->mDeclaringType, isBetter, isWorse);
  17005. if (isBetter && !isWorse)
  17006. {
  17007. methodInstance->mChainType = BfMethodChainType_ChainHead;
  17008. checkMethodInstance->mChainType = BfMethodChainType_ChainMember;
  17009. }
  17010. else
  17011. {
  17012. checkMethodInstance->mChainType = BfMethodChainType_ChainHead;
  17013. methodInstance->mChainType = BfMethodChainType_ChainMember;
  17014. }
  17015. }
  17016. else if ((checkMethod->mBody == NULL) && (methodDef->mBody != NULL) &&
  17017. (checkMethod->mDeclaringType != methodDef->mDeclaringType))
  17018. {
  17019. // We're allowed to override an empty-bodied method
  17020. checkMethodInstance->mChainType = BfMethodChainType_ChainSkip;
  17021. }
  17022. else
  17023. {
  17024. if (!typeInstance->IsTypeMemberAccessible(checkMethod->mDeclaringType, methodDef->mDeclaringType))
  17025. continue;
  17026. bool silentlyAllow = false;
  17027. if (checkMethod->mDeclaringType != methodDef->mDeclaringType)
  17028. {
  17029. if (typeInstance->IsInterface())
  17030. {
  17031. if (methodDef->mIsOverride)
  17032. silentlyAllow = true;
  17033. }
  17034. else
  17035. silentlyAllow = true;
  17036. }
  17037. if ((checkMethod->mCommutableKind == BfCommutableKind_Reverse) || (methodDef->mCommutableKind == BfCommutableKind_Reverse))
  17038. silentlyAllow = true;
  17039. if (!silentlyAllow)
  17040. {
  17041. if ((!methodDef->mName.IsEmpty()) || (checkMethodInstance->mMethodDef->mIsOperator))
  17042. {
  17043. auto refNode = methodDef->GetRefNode();
  17044. auto bfError = Fail("Method already declared with the same parameter types", refNode, true);
  17045. if (bfError != NULL)
  17046. mCompiler->mPassInstance->MoreInfo("First declaration", checkMethod->GetRefNode());
  17047. }
  17048. }
  17049. }
  17050. }
  17051. }
  17052. }
  17053. }
  17054. // Virtual methods give their error while slotting
  17055. if ((!typeInstance->IsBoxed()) && (!methodDef->mIsVirtual) && (methodDef->mProtection != BfProtection_Private) &&
  17056. (!methodDef->mIsLocalMethod) &&
  17057. (!methodInstance->mIsForeignMethodDef) && (typeInstance->mBaseType != NULL) &&
  17058. (methodDef->mMethodType == BfMethodType_Normal) && (methodDef->mMethodDeclaration != NULL))
  17059. {
  17060. bool foundHiddenMethod = false;
  17061. auto baseType = typeInstance->mBaseType;
  17062. while (baseType != NULL)
  17063. {
  17064. //for (int checkMethodIdx = 0; checkMethodIdx < (int) baseType->mTypeDef->mMethods.size(); checkMethodIdx++)
  17065. auto baseTypeDef = baseType->mTypeDef;
  17066. baseTypeDef->PopulateMemberSets();
  17067. BfMethodDef* checkMethod = NULL;
  17068. BfMemberSetEntry* entry = NULL;
  17069. if (baseTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  17070. checkMethod = (BfMethodDef*)entry->mMemberDef;
  17071. while (checkMethod != NULL)
  17072. {
  17073. if (checkMethod->mMethodDeclaration == NULL)
  17074. continue;
  17075. if (baseType->mMethodInstanceGroups.size() == 0)
  17076. {
  17077. BF_ASSERT(baseType->IsIncomplete() && mCompiler->IsAutocomplete());
  17078. break;
  17079. }
  17080. if (checkMethod == methodDef)
  17081. continue;
  17082. if (checkMethod->mName != methodDef->mName)
  17083. continue;
  17084. auto checkMethodInstance = GetRawMethodInstanceAtIdx(baseType, checkMethod->mIdx);
  17085. if (checkMethodInstance != NULL)
  17086. {
  17087. if ((checkMethodInstance->GetExplicitInterface() == methodInstance->GetExplicitInterface()) &&
  17088. (checkMethod->mProtection != BfProtection_Private) &&
  17089. (CompareMethodSignatures(checkMethodInstance, mCurMethodInstance)))
  17090. {
  17091. if (!methodDef->mIsNew)
  17092. {
  17093. BfAstNode* refNode = methodInstance->mMethodDef->GetRefNode();
  17094. if (refNode != NULL)
  17095. {
  17096. 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?
  17097. if (bfError != NULL)
  17098. bfError->mIsPersistent = true;
  17099. }
  17100. }
  17101. foundHiddenMethod = true;
  17102. break;
  17103. }
  17104. }
  17105. checkMethod = checkMethod->mNextWithSameName;
  17106. }
  17107. if (foundHiddenMethod)
  17108. break;
  17109. baseType = baseType->mBaseType;
  17110. }
  17111. if ((methodDef->mIsNew) && (!foundHiddenMethod))
  17112. {
  17113. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  17114. auto tokenNode = (propertyDeclaration != NULL) ? propertyDeclaration->mNewSpecifier :
  17115. methodDeclaration->mNewSpecifier;
  17116. Fail("Method does not hide an inherited member. The 'new' keyword is not required", tokenNode, true);
  17117. }
  17118. }
  17119. }
  17120. mCompiler->mStats.mMethodDeclarations++;
  17121. mCompiler->UpdateCompletion();
  17122. }
  17123. void BfModule::UniqueSlotVirtualMethod(BfMethodInstance* methodInstance)
  17124. {
  17125. BF_ASSERT(methodInstance->GetOwner() == mCurTypeInstance);
  17126. auto typeInstance = mCurTypeInstance;
  17127. auto methodDef = methodInstance->mMethodDef;
  17128. int virtualMethodMatchIdx = -1;
  17129. if (typeInstance->mHotTypeData != NULL)
  17130. {
  17131. if (typeInstance->mHotTypeData->mVTableOrigLength != -1)
  17132. {
  17133. BF_ASSERT(mCompiler->IsHotCompile());
  17134. // In the 'normal' case we'd assert that mIsOverride is false, but if we can't find the declaring method then we
  17135. // may slot this override anyway (?)
  17136. int vTableStart = 0;
  17137. if (typeInstance->mBaseType != NULL)
  17138. vTableStart = typeInstance->mBaseType->mVirtualMethodTableSize;
  17139. StringT<128> mangledName;
  17140. BfMangler::Mangle(mangledName, mCompiler->GetMangleKind(), methodInstance);
  17141. for (int checkIdxOfs = 0; checkIdxOfs < (int)typeInstance->mHotTypeData->mVTableEntries.size(); checkIdxOfs++)
  17142. {
  17143. // O(1) checking when virtual methods haven't changed
  17144. int checkIdx = (typeInstance->mVirtualMethodTableSize - vTableStart + checkIdxOfs) % (int)typeInstance->mHotTypeData->mVTableEntries.size();
  17145. auto& entry = typeInstance->mHotTypeData->mVTableEntries[checkIdx];
  17146. if (mangledName == entry.mFuncName)
  17147. {
  17148. virtualMethodMatchIdx = vTableStart + checkIdx;
  17149. break;
  17150. }
  17151. }
  17152. if (virtualMethodMatchIdx != -1)
  17153. {
  17154. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  17155. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod = methodInstance;
  17156. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod = methodInstance;
  17157. }
  17158. typeInstance->mVirtualMethodTableSize = (int)typeInstance->mVirtualMethodTable.size();
  17159. }
  17160. }
  17161. if (virtualMethodMatchIdx == -1)
  17162. {
  17163. methodInstance->mVirtualTableIdx = typeInstance->mVirtualMethodTableSize++;
  17164. BfVirtualMethodEntry entry = { methodInstance, methodInstance };
  17165. typeInstance->mVirtualMethodTable.push_back(entry);
  17166. }
  17167. }
  17168. void BfModule::CompareDeclTypes(BfTypeDef* newDeclType, BfTypeDef* prevDeclType, bool& isBetter, bool& isWorse)
  17169. {
  17170. if ((!prevDeclType->IsExtension()) && (newDeclType->IsExtension()))
  17171. {
  17172. // When we provide an extension override in the same project a root type override
  17173. isBetter = true;
  17174. isWorse = false;
  17175. }
  17176. else
  17177. {
  17178. isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  17179. isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  17180. }
  17181. }
  17182. bool BfModule::SlotVirtualMethod(BfMethodInstance* methodInstance, BfAmbiguityContext* ambiguityContext)
  17183. {
  17184. BP_ZONE("BfModule::SlotVirtualMethod");
  17185. if (mCurTypeInstance->IsUnspecializedTypeVariation())
  17186. return false;
  17187. auto _AddVirtualDecl = [&](BfMethodInstance* declMethodInstance)
  17188. {
  17189. if (!mCompiler->mOptions.mAllowHotSwapping)
  17190. return;
  17191. if ((!methodInstance->mIsReified) || (!declMethodInstance->mIsReified))
  17192. return;
  17193. if (methodInstance->mHotMethod == NULL)
  17194. CheckHotMethod(methodInstance, "");
  17195. if (methodInstance->mHotMethod == NULL)
  17196. return;
  17197. //BF_ASSERT(declMethodInstance->mHotMethod != NULL);
  17198. if (declMethodInstance->mHotMethod == NULL)
  17199. CheckHotMethod(declMethodInstance, "");
  17200. auto virtualDecl = mCompiler->mHotData->GetVirtualDeclaration(declMethodInstance->mHotMethod);
  17201. virtualDecl->mRefCount++;
  17202. methodInstance->mHotMethod->mReferences.Add(virtualDecl);
  17203. };
  17204. auto typeInstance = mCurTypeInstance;
  17205. auto typeDef = typeInstance->mTypeDef;
  17206. auto methodDef = methodInstance->mMethodDef;
  17207. auto methodDeclaration = methodDef->GetMethodDeclaration();
  17208. auto propertyDeclaration = methodDef->GetPropertyDeclaration();
  17209. auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration();
  17210. BfAstNode* declaringNode = methodDeclaration;
  17211. if (propertyMethodDeclaration != NULL)
  17212. declaringNode = propertyMethodDeclaration->mNameNode;
  17213. BfMethodInstance* methodOverriden = NULL;
  17214. bool usedMethod = false;
  17215. BfTokenNode* virtualToken = NULL;
  17216. if (propertyDeclaration != NULL)
  17217. virtualToken = propertyDeclaration->mVirtualSpecifier;
  17218. else if (methodDeclaration != NULL)
  17219. virtualToken = methodDeclaration->mVirtualSpecifier;
  17220. if ((methodDef->mIsVirtual) && (methodDef->mIsStatic))
  17221. {
  17222. Fail("Static members cannot be marked as override, virtual, or abstract", virtualToken, true);
  17223. }
  17224. else if (methodDef->mIsVirtual)
  17225. {
  17226. if (mCompiler->IsHotCompile())
  17227. mContext->EnsureHotMangledVirtualMethodName(methodInstance);
  17228. if ((methodDef->mProtection == BfProtection_Private) && (virtualToken != NULL))
  17229. Fail("Virtual or abstract members cannot be private", virtualToken, true);
  17230. BfTypeInstance* checkBase = typeInstance;
  17231. // If we are in an extension, look in ourselves first
  17232. if (methodDef->mDeclaringType->mTypeDeclaration == typeInstance->mTypeDef->mTypeDeclaration)
  17233. checkBase = checkBase->mBaseType;
  17234. if (typeInstance->IsValueType())
  17235. {
  17236. if (typeInstance->mBaseType == NULL)
  17237. return false; // It's actually ValueType
  17238. // We allow structs to override object methods for when they get boxed, so just ignore 'override' keyword until it gets boxed
  17239. if (!methodDef->mIsOverride)
  17240. {
  17241. Fail("Structs cannot have virtual methods", virtualToken, true);
  17242. return false;
  17243. }
  17244. checkBase = mContext->mBfObjectType;
  17245. if (checkBase->mVirtualMethodTableSize == 0)
  17246. PopulateType(checkBase, BfPopulateType_Full);
  17247. if (checkBase->mDefineState < BfTypeDefineState_DefinedAndMethodsSlotted)
  17248. return false; // System circular ref, don't do struct checking on those
  17249. }
  17250. int virtualMethodMatchIdx = -1;
  17251. bool hadHidingError = false;
  17252. BfMethodInstance* bestOverrideMethodInstance = NULL;
  17253. BfMethodInstance* ambiguousOverrideMethodInstance = NULL;
  17254. int bestOverrideMethodIdx = -1;
  17255. int ambiguousOverrideMethodIdx = -1;
  17256. if (checkBase != NULL)
  17257. {
  17258. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  17259. auto lookupType = checkBase;
  17260. while (lookupType != NULL)
  17261. {
  17262. lookupType->mTypeDef->PopulateMemberSets();
  17263. BfMethodDef* nextMethodDef = NULL;
  17264. BfMemberSetEntry* entry;
  17265. if (lookupType->mTypeDef->mMethodSet.TryGetWith(methodInstance->mMethodDef->mName, &entry))
  17266. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  17267. while (nextMethodDef != NULL)
  17268. {
  17269. auto checkMethodDef = nextMethodDef;
  17270. nextMethodDef = nextMethodDef->mNextWithSameName;
  17271. if ((!checkMethodDef->mIsVirtual) || (checkMethodDef->mIsOverride))
  17272. continue;
  17273. BfMethodInstance* lookupMethodInstance = lookupType->mMethodInstanceGroups[checkMethodDef->mIdx].mDefault;
  17274. if ((lookupMethodInstance == NULL) || (lookupMethodInstance->mVirtualTableIdx == -1))
  17275. continue;
  17276. int checkMethodIdx = lookupMethodInstance->mVirtualTableIdx;
  17277. auto& baseMethodRef = baseVirtualMethodTable[checkMethodIdx];
  17278. if (baseMethodRef.mDeclaringMethod.mMethodNum == -1)
  17279. {
  17280. BF_ASSERT(mCompiler->mOptions.mHasVDataExtender);
  17281. continue;
  17282. }
  17283. BfMethodInstance* baseMethodInstance = baseVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  17284. if (baseMethodInstance == NULL)
  17285. {
  17286. AssertErrorState();
  17287. continue;
  17288. }
  17289. if ((baseMethodInstance != NULL) && (CompareMethodSignatures(baseMethodInstance, methodInstance)))
  17290. {
  17291. if (methodDef->mIsOverride)
  17292. {
  17293. BfMethodInstance* checkMethodInstance;
  17294. if (typeInstance->IsValueType())
  17295. checkMethodInstance = checkBase->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  17296. else
  17297. checkMethodInstance = typeInstance->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  17298. auto newDeclType = checkMethodInstance->mMethodDef->mDeclaringType;
  17299. if (!typeInstance->IsTypeMemberAccessible(newDeclType, methodDef->mDeclaringType->mProject))
  17300. continue;
  17301. if (bestOverrideMethodInstance != NULL)
  17302. {
  17303. auto prevDeclType = bestOverrideMethodInstance->mMethodDef->mDeclaringType;
  17304. bool isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  17305. bool isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  17306. if (isBetter == isWorse)
  17307. {
  17308. ambiguousOverrideMethodInstance = bestOverrideMethodInstance;
  17309. }
  17310. else
  17311. {
  17312. if (isWorse)
  17313. continue;
  17314. ambiguousOverrideMethodInstance = NULL;
  17315. }
  17316. }
  17317. bestOverrideMethodInstance = checkMethodInstance;
  17318. bestOverrideMethodIdx = checkMethodIdx;
  17319. }
  17320. else
  17321. {
  17322. if ((baseMethodInstance->GetOwner() != methodInstance->GetOwner()) && (!methodDef->mIsNew))
  17323. {
  17324. if (!hadHidingError)
  17325. Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use either 'override' or 'new'.", TypeToString(checkBase).c_str()), declaringNode);
  17326. hadHidingError = true;
  17327. }
  17328. }
  17329. }
  17330. }
  17331. lookupType = lookupType->mBaseType;
  17332. }
  17333. }
  17334. //TODO:
  17335. if ((checkBase != NULL)
  17336. && (false)
  17337. )
  17338. {
  17339. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  17340. for (int checkMethodIdx = (int) baseVirtualMethodTable.size() - 1; checkMethodIdx >= 0; checkMethodIdx--)
  17341. {
  17342. auto& baseMethodRef = baseVirtualMethodTable[checkMethodIdx];
  17343. if (baseMethodRef.mDeclaringMethod.mMethodNum == -1)
  17344. {
  17345. BF_ASSERT(mCompiler->mOptions.mHasVDataExtender);
  17346. continue;
  17347. }
  17348. BfMethodInstance* baseMethodInstance = baseVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  17349. if (baseMethodInstance == NULL)
  17350. {
  17351. AssertErrorState();
  17352. continue;
  17353. }
  17354. if ((baseMethodInstance != NULL) && (CompareMethodSignatures(baseMethodInstance, methodInstance)))
  17355. {
  17356. if (methodDef->mIsOverride)
  17357. {
  17358. BfMethodInstance* checkMethodInstance;
  17359. if (typeInstance->IsValueType())
  17360. checkMethodInstance = checkBase->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  17361. else
  17362. checkMethodInstance = typeInstance->mVirtualMethodTable[checkMethodIdx].mDeclaringMethod;
  17363. auto newDeclType = checkMethodInstance->mMethodDef->mDeclaringType;
  17364. if (!typeInstance->IsTypeMemberAccessible(newDeclType, methodDef->mDeclaringType->mProject))
  17365. continue;
  17366. if (bestOverrideMethodInstance != NULL)
  17367. {
  17368. auto prevDeclType = bestOverrideMethodInstance->mMethodDef->mDeclaringType;
  17369. bool isBetter = newDeclType->mProject->ContainsReference(prevDeclType->mProject);
  17370. bool isWorse = prevDeclType->mProject->ContainsReference(newDeclType->mProject);
  17371. if (isBetter == isWorse)
  17372. {
  17373. ambiguousOverrideMethodInstance = bestOverrideMethodInstance;
  17374. }
  17375. else
  17376. {
  17377. if (isWorse)
  17378. continue;
  17379. ambiguousOverrideMethodInstance = NULL;
  17380. }
  17381. }
  17382. bestOverrideMethodInstance = checkMethodInstance;
  17383. bestOverrideMethodIdx = checkMethodIdx;
  17384. }
  17385. else
  17386. {
  17387. if ((baseMethodInstance->GetOwner() != methodInstance->GetOwner()) && (!methodDef->mIsNew))
  17388. {
  17389. if (!hadHidingError)
  17390. Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use either 'override' or 'new'.", TypeToString(checkBase).c_str()), declaringNode);
  17391. hadHidingError = true;
  17392. }
  17393. }
  17394. }
  17395. }
  17396. }
  17397. if (bestOverrideMethodInstance != NULL)
  17398. {
  17399. if (ambiguousOverrideMethodInstance != NULL)
  17400. {
  17401. bool allow = false;
  17402. // 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.
  17403. // When when specialize, the specialized type will determine wither it has illegally pulled in both declarations or not
  17404. bool canSeeEachOther = false;
  17405. //
  17406. {
  17407. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, ambiguousOverrideMethodInstance);
  17408. if (bestOverrideMethodInstance->GetOwner()->IsTypeMemberIncluded(bestOverrideMethodInstance->mMethodDef->mDeclaringType, ambiguousOverrideMethodInstance->mMethodDef->mDeclaringType, this))
  17409. canSeeEachOther = true;
  17410. }
  17411. //
  17412. {
  17413. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, bestOverrideMethodInstance);
  17414. if (ambiguousOverrideMethodInstance->GetOwner()->IsTypeMemberIncluded(ambiguousOverrideMethodInstance->mMethodDef->mDeclaringType, bestOverrideMethodInstance->mMethodDef->mDeclaringType, this))
  17415. canSeeEachOther = true;
  17416. }
  17417. if (!canSeeEachOther)
  17418. {
  17419. BF_ASSERT(bestOverrideMethodInstance->GetOwner()->IsUnspecializedType() && ambiguousOverrideMethodInstance->GetOwner()->IsUnspecializedType());
  17420. }
  17421. else
  17422. {
  17423. auto error = Fail(StrFormat("Method '%s' is an ambiguous override", MethodToString(methodInstance).c_str()), methodDef->GetRefNode());
  17424. if (error != NULL)
  17425. {
  17426. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", MethodToString(bestOverrideMethodInstance).c_str()), bestOverrideMethodInstance->mMethodDef->GetRefNode());
  17427. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", MethodToString(ambiguousOverrideMethodInstance).c_str()), ambiguousOverrideMethodInstance->mMethodDef->GetRefNode());
  17428. }
  17429. }
  17430. }
  17431. auto& baseVirtualMethodTable = checkBase->mVirtualMethodTable;
  17432. BfMethodInstance* baseVirtualMethodInstance = baseVirtualMethodTable[bestOverrideMethodIdx].mDeclaringMethod;
  17433. if ((baseVirtualMethodInstance != methodInstance) && (methodDef->mIsOverride))
  17434. {
  17435. if (baseVirtualMethodInstance->mReturnType != methodInstance->mReturnType)
  17436. {
  17437. BfTypeReference* returnTypeRef;
  17438. if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  17439. {
  17440. returnTypeRef = propertyDeclaration->mTypeRef;
  17441. Fail("Property differs from overridden property by type", returnTypeRef, true);
  17442. }
  17443. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  17444. {
  17445. returnTypeRef = methodDeclaration->mReturnType;
  17446. Fail("Method differs from overridden method by return value", returnTypeRef, true);
  17447. }
  17448. else
  17449. {
  17450. Fail(StrFormat("Internal error with method '%s'", MethodToString(methodInstance).c_str()));
  17451. }
  17452. return usedMethod;
  17453. }
  17454. }
  17455. if (methodDef->mIsOverride)
  17456. {
  17457. // We can have multiple matches when a virtual method is used to implement interface methods
  17458. // It doesn't matter what we set mVirtualTableIdx, as all base classes will override all matching
  17459. // vtable entries for this method signature
  17460. virtualMethodMatchIdx = bestOverrideMethodIdx;
  17461. if (!typeInstance->IsValueType())
  17462. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  17463. if (typeInstance->IsValueType())
  17464. {
  17465. methodOverriden = checkBase->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod;
  17466. }
  17467. else
  17468. {
  17469. methodInstance->mVirtualTableIdx = virtualMethodMatchIdx;
  17470. auto& overridenRef = typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod;
  17471. if (overridenRef.mKind != BfMethodRefKind_AmbiguousRef)
  17472. {
  17473. methodOverriden = overridenRef;
  17474. BfMethodInstance* setMethodInstance = methodInstance;
  17475. bool doOverride = true;
  17476. if (methodOverriden->GetOwner() == methodInstance->GetOwner())
  17477. {
  17478. bool isBetter = false;
  17479. bool isWorse = false;
  17480. CompareDeclTypes(methodInstance->mMethodDef->mDeclaringType, methodOverriden->mMethodDef->mDeclaringType, isBetter, isWorse);
  17481. if (isBetter == isWorse)
  17482. {
  17483. // We have to resolve later per-project
  17484. if ((ambiguityContext != NULL) && (ambiguityContext->mIsProjectSpecific))
  17485. {
  17486. auto declMethodInstance = checkBase->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod;
  17487. ambiguityContext->Add(virtualMethodMatchIdx, NULL, -1, methodOverriden, methodInstance);
  17488. }
  17489. if ((ambiguityContext == NULL) || (!ambiguityContext->mIsProjectSpecific))
  17490. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod.mKind = BfMethodRefKind_AmbiguousRef;
  17491. doOverride = false;
  17492. }
  17493. else
  17494. {
  17495. if ((isBetter) && (ambiguityContext != NULL))
  17496. {
  17497. ambiguityContext->Remove(virtualMethodMatchIdx);
  17498. }
  17499. doOverride = isBetter;
  17500. }
  17501. }
  17502. if (doOverride)
  17503. {
  17504. auto declMethodInstance = (BfMethodInstance*)typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mDeclaringMethod;
  17505. _AddVirtualDecl(declMethodInstance);
  17506. typeInstance->mVirtualMethodTable[virtualMethodMatchIdx].mImplementingMethod = setMethodInstance;
  17507. }
  17508. }
  17509. }
  17510. if (methodOverriden != NULL)
  17511. {
  17512. auto prevProtection = methodOverriden->mMethodDef->mProtection;
  17513. if ((methodDef->mProtection != prevProtection) && (methodDef->mMethodType != BfMethodType_Dtor))
  17514. {
  17515. const char* protectionNames[] = {"hidden", "private", "protected", "public"};
  17516. BfAstNode* protectionRefNode = NULL;
  17517. if (auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration())
  17518. {
  17519. protectionRefNode = propertyMethodDeclaration->mProtectionSpecifier;
  17520. if (protectionRefNode == NULL)
  17521. protectionRefNode = propertyMethodDeclaration->mPropertyDeclaration->mProtectionSpecifier;
  17522. if (protectionRefNode == NULL)
  17523. protectionRefNode = propertyMethodDeclaration->mPropertyDeclaration->mNameNode;
  17524. }
  17525. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  17526. {
  17527. protectionRefNode = methodDeclaration->mProtectionSpecifier;
  17528. if (protectionRefNode == NULL)
  17529. protectionRefNode = methodDeclaration->mNameNode;
  17530. }
  17531. if (protectionRefNode != NULL)
  17532. Fail(StrFormat("Cannot change access modifiers when overriding '%s' inherited member", protectionNames[(int)prevProtection]), protectionRefNode, true);
  17533. }
  17534. }
  17535. }
  17536. }
  17537. if ((virtualMethodMatchIdx == -1) && ((ambiguityContext == NULL) || (!ambiguityContext->mIsReslotting)))
  17538. {
  17539. if (methodDef->mIsOverride)
  17540. {
  17541. BfTokenNode* overrideToken = NULL;
  17542. if (auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration())
  17543. overrideToken = propertyMethodDeclaration->mPropertyDeclaration->mVirtualSpecifier;
  17544. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  17545. overrideToken = methodDeclaration->mVirtualSpecifier;
  17546. if (overrideToken != NULL)
  17547. {
  17548. if ((propertyDeclaration != NULL) && (propertyDeclaration->mNameNode != NULL) &&
  17549. ((methodDef->mMethodType == BfMethodType_PropertyGetter) || (methodDef->mMethodType == BfMethodType_PropertySetter)))
  17550. Fail(StrFormat("No suitable method found to override for '%s.%s'",
  17551. propertyDeclaration->mNameNode->ToString().c_str(), (methodDef->mMethodType == BfMethodType_PropertyGetter) ? "get" : "set"), overrideToken, true);
  17552. else
  17553. Fail("No suitable method found to override", overrideToken, true);
  17554. }
  17555. return usedMethod;
  17556. }
  17557. UniqueSlotVirtualMethod(methodInstance);
  17558. }
  17559. else
  17560. usedMethod = true;
  17561. if (typeInstance->IsValueType())
  17562. return usedMethod;
  17563. }
  17564. bool foundInterface = false;
  17565. bool hadAnyMatch = false;
  17566. // See if this method matches interfaces
  17567. for (auto& ifaceTypeInst : typeInstance->mInterfaces)
  17568. {
  17569. auto ifaceInst = ifaceTypeInst.mInterfaceType;
  17570. if (ifaceInst->IsIncomplete())
  17571. PopulateType(ifaceInst, BfPopulateType_DataAndMethods);
  17572. int startIdx = ifaceTypeInst.mStartInterfaceTableIdx;
  17573. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  17574. // See "bidirectional" rules mentioned in DoTypeInstanceMethodProcessing
  17575. if ((!typeInstance->IsTypeMemberAccessible(methodDef->mDeclaringType, ifaceTypeInst.mDeclaringType)) &&
  17576. (!typeInstance->IsTypeMemberAccessible(ifaceTypeInst.mDeclaringType, methodDef->mDeclaringType)))
  17577. continue;
  17578. if (!typeInstance->IsTypeMemberIncluded(methodDef->mDeclaringType, ifaceTypeInst.mDeclaringType, this))
  17579. continue;
  17580. bool hadMatch = false;
  17581. bool hadNameMatch = false;
  17582. BfType* expectedReturnType = NULL;
  17583. bool showedError = false;
  17584. // We go through our VTable looking for NULL entries within the interface sections
  17585. // The only instance of finding a "better" method is when we have explicitly interface-dotted method
  17586. // because a normal method declared in this type could have matched earlier
  17587. //for (int iMethodIdx = 0; iMethodIdx < iMethodCount; iMethodIdx++)
  17588. ifaceInst->mTypeDef->PopulateMemberSets();
  17589. BfMethodDef* checkMethodDef = NULL;
  17590. BfMemberSetEntry* entry;
  17591. if (ifaceInst->mTypeDef->mMethodSet.TryGetWith(methodInstance->mMethodDef->mName, &entry))
  17592. checkMethodDef = (BfMethodDef*)entry->mMemberDef;
  17593. while (checkMethodDef != NULL)
  17594. {
  17595. int iMethodIdx = checkMethodDef->mIdx;
  17596. int iTableIdx = iMethodIdx + startIdx;
  17597. BfTypeInterfaceMethodEntry* interfaceMethodEntry = &typeInstance->mInterfaceMethodTable[iTableIdx];
  17598. auto iMethodPtr = &interfaceMethodEntry->mMethodRef;
  17599. bool storeIFaceMethod = false;
  17600. if ((mCompiler->mPassInstance->HasFailed()) && (iMethodIdx >= (int)ifaceInst->mMethodInstanceGroups.size()))
  17601. continue;
  17602. auto& iMethodGroup = ifaceInst->mMethodInstanceGroups[iMethodIdx];
  17603. auto iMethodInst = iMethodGroup.mDefault;
  17604. if (iMethodInst == NULL)
  17605. {
  17606. if ((!ifaceInst->IsGenericTypeInstance()) || (!ifaceInst->mTypeDef->mIsCombinedPartial))
  17607. AssertErrorState();
  17608. continue;
  17609. }
  17610. if (iMethodInst->mMethodDef->mName == methodInstance->mMethodDef->mName)
  17611. hadNameMatch = true;
  17612. bool doesMethodSignatureMatch = CompareMethodSignatures(iMethodInst, methodInstance);
  17613. if ((!doesMethodSignatureMatch) && (iMethodInst->GetNumGenericParams() == 0) && (interfaceMethodEntry->mMethodRef.IsNull()))
  17614. {
  17615. doesMethodSignatureMatch = IsCompatibleInterfaceMethod(iMethodInst, methodInstance);
  17616. }
  17617. if ((doesMethodSignatureMatch) && (methodInstance->GetOwner()->IsValueType()))
  17618. {
  17619. if ((!iMethodInst->mMethodDef->mIsMutating) && (methodInstance->mMethodDef->mIsMutating))
  17620. {
  17621. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface == ifaceInst))
  17622. {
  17623. auto error = mCompiler->mPassInstance->Fail(StrFormat("Implementation method '%s' cannot specify 'mut' because the interface method does not allow it",
  17624. MethodToString(methodInstance).c_str()), methodInstance->mMethodDef->GetMutNode());
  17625. if (error != NULL)
  17626. mCompiler->mPassInstance->MoreInfo(StrFormat("Declare the interface method as 'mut' to allow matching 'mut' implementations"), iMethodInst->mMethodDef->mMethodDeclaration);
  17627. showedError = true;
  17628. }
  17629. }
  17630. }
  17631. if (doesMethodSignatureMatch)
  17632. {
  17633. usedMethod = true;
  17634. hadMatch = true;
  17635. hadAnyMatch = true;
  17636. storeIFaceMethod = true;
  17637. if ((iMethodPtr->mKind != BfMethodRefKind_AmbiguousRef) && (iMethodPtr->mTypeInstance != NULL))
  17638. {
  17639. auto prevMethod = (BfMethodInstance*)*iMethodPtr;
  17640. if ((mCompiler->mIsResolveOnly) && (prevMethod == methodInstance))
  17641. {
  17642. // When autocompletion regenerates a single method body but not the whole type then
  17643. // we will see ourselves in the vtable already
  17644. return usedMethod;
  17645. }
  17646. bool isBetter = false;
  17647. bool isWorse = false;
  17648. isBetter = (methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL);
  17649. isWorse = (prevMethod->mMethodInfoEx != NULL) && (prevMethod->mMethodInfoEx->mExplicitInterface != NULL);
  17650. if (isBetter == isWorse)
  17651. CompareDeclTypes(methodInstance->mMethodDef->mDeclaringType, prevMethod->mMethodDef->mDeclaringType, isBetter, isWorse);
  17652. if (isBetter == isWorse)
  17653. {
  17654. if (ambiguityContext != NULL)
  17655. {
  17656. ambiguityContext->Add(~iTableIdx, &ifaceTypeInst, iMethodIdx, prevMethod, methodInstance);
  17657. }
  17658. iMethodPtr->mKind = BfMethodRefKind_AmbiguousRef;
  17659. storeIFaceMethod = true;
  17660. }
  17661. else
  17662. {
  17663. if ((isBetter) && (ambiguityContext != NULL))
  17664. ambiguityContext->Remove(~iTableIdx);
  17665. storeIFaceMethod = isBetter;
  17666. }
  17667. }
  17668. }
  17669. if (storeIFaceMethod)
  17670. {
  17671. _AddVirtualDecl(iMethodInst);
  17672. *iMethodPtr = methodInstance;
  17673. }
  17674. checkMethodDef = checkMethodDef->mNextWithSameName;
  17675. }
  17676. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface == ifaceInst) && (!hadMatch) && (!showedError))
  17677. {
  17678. if (expectedReturnType != NULL)
  17679. Fail(StrFormat("Wrong return type, expected '%s'", TypeToString(expectedReturnType).c_str()), declaringNode, true);
  17680. else if (hadNameMatch)
  17681. Fail("Method parameters don't match interface method", declaringNode, true);
  17682. else
  17683. Fail("Method name not found in interface", methodDef->GetRefNode(), true);
  17684. }
  17685. }
  17686. // Any overriden virtual methods that were used in interfaces also need to be replaced
  17687. if (methodOverriden != NULL)
  17688. {
  17689. for (auto& methodEntry : typeInstance->mInterfaceMethodTable)
  17690. {
  17691. if (methodEntry.mMethodRef == methodOverriden)
  17692. methodEntry.mMethodRef = methodInstance;
  17693. }
  17694. }
  17695. return usedMethod;
  17696. }
  17697. bool BfModule::SlotInterfaceMethod(BfMethodInstance* methodInstance)
  17698. {
  17699. auto typeInstance = mCurTypeInstance;
  17700. auto methodDef = methodInstance->mMethodDef;
  17701. if (methodDef->mMethodType == BfMethodType_Ctor)
  17702. return true;
  17703. bool foundOverride = false;
  17704. if ((methodDef->mBody == NULL) && (methodDef->mProtection == BfProtection_Private))
  17705. {
  17706. Fail("Private interface methods must provide a body", methodDef->GetMethodDeclaration()->mProtectionSpecifier);
  17707. }
  17708. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL) && (!methodDef->mIsOverride))
  17709. {
  17710. Fail("Explicit interfaces can only be specified for overrides in interface declarations", methodDef->GetMethodDeclaration()->mExplicitInterface);
  17711. }
  17712. BfAstNode* declaringNode = methodDef->GetRefNode();
  17713. for (auto& ifaceTypeInst : typeInstance->mInterfaces)
  17714. {
  17715. auto ifaceInst = ifaceTypeInst.mInterfaceType;
  17716. int startIdx = ifaceTypeInst.mStartInterfaceTableIdx;
  17717. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  17718. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != NULL) && (methodInstance->mMethodInfoEx->mExplicitInterface != ifaceInst))
  17719. continue;
  17720. ifaceInst->mTypeDef->PopulateMemberSets();
  17721. BfMethodDef* nextMethod = NULL;
  17722. BfMemberSetEntry* entry = NULL;
  17723. if (ifaceInst->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  17724. nextMethod = (BfMethodDef*)entry->mMemberDef;
  17725. while (nextMethod != NULL)
  17726. {
  17727. auto checkMethod = nextMethod;
  17728. nextMethod = nextMethod->mNextWithSameName;
  17729. auto ifaceMethod = ifaceInst->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  17730. if (ifaceMethod == NULL)
  17731. continue;
  17732. if (CompareMethodSignatures(ifaceMethod, methodInstance))
  17733. {
  17734. if (methodDef->mIsOverride)
  17735. {
  17736. if (ifaceMethod->mMethodDef->mProtection == BfProtection_Private)
  17737. {
  17738. auto error = Fail(StrFormat("Interface method '%s' cannot override private interface method '%s'", MethodToString(methodInstance).c_str(), MethodToString(ifaceMethod).c_str()), declaringNode);
  17739. if (error != NULL)
  17740. {
  17741. mCompiler->mPassInstance->MoreInfo("See base interface method", ifaceMethod->mMethodDef->GetRefNode());
  17742. }
  17743. }
  17744. foundOverride = true;
  17745. }
  17746. else if (!methodDef->mIsNew)
  17747. {
  17748. Warn(BfWarning_CS0114_MethodHidesInherited, StrFormat("Method hides inherited member from '%s'. Use the 'new' keyword if hiding was intentional.", TypeToString(ifaceInst).c_str()), declaringNode);
  17749. }
  17750. }
  17751. }
  17752. }
  17753. if ((methodDef->mIsOverride) && (!foundOverride))
  17754. {
  17755. // This allows us to declare a method in the base definition or in an extension and then provide
  17756. // an implementation in a more-specific extension
  17757. typeInstance->mTypeDef->PopulateMemberSets();
  17758. BfMethodDef* nextMethod = NULL;
  17759. BfMemberSetEntry* entry = NULL;
  17760. if (typeInstance->mTypeDef->mMethodSet.TryGet(BfMemberSetEntry(methodDef), &entry))
  17761. nextMethod = (BfMethodDef*)entry->mMemberDef;
  17762. while (nextMethod != NULL)
  17763. {
  17764. auto checkMethod = nextMethod;
  17765. nextMethod = nextMethod->mNextWithSameName;
  17766. auto ifaceMethod = typeInstance->mMethodInstanceGroups[checkMethod->mIdx].mDefault;
  17767. if (ifaceMethod == NULL)
  17768. continue;
  17769. if (ifaceMethod->mMethodDef->mDeclaringType == methodInstance->mMethodDef->mDeclaringType)
  17770. continue;
  17771. if (CompareMethodSignatures(ifaceMethod, methodInstance))
  17772. {
  17773. foundOverride = true;
  17774. }
  17775. }
  17776. // for (int methodIdx = 0; methodIdx < typeInstance->mMethodInstanceGroups.size(); methodIdx++)
  17777. // {
  17778. // auto ifaceMethod = typeInstance->mMethodInstanceGroups[methodIdx].mDefault;
  17779. // if (ifaceMethod == NULL)
  17780. // continue;
  17781. // if (ifaceMethod->mMethodDef->mDeclaringType == methodInstance->mMethodDef->mDeclaringType)
  17782. // continue;
  17783. //
  17784. // if (CompareMethodSignatures(ifaceMethod, methodInstance))
  17785. // {
  17786. // foundOverride = true;
  17787. // }
  17788. // }
  17789. }
  17790. if (methodDef->mIsOverride)
  17791. {
  17792. if (!foundOverride)
  17793. {
  17794. BfTokenNode* overrideToken = NULL;
  17795. if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  17796. overrideToken = propertyDeclaration->mVirtualSpecifier;
  17797. else if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  17798. overrideToken = methodDeclaration->mVirtualSpecifier;
  17799. if (overrideToken != NULL)
  17800. {
  17801. Fail("No suitable method found to override", overrideToken, true);
  17802. }
  17803. else
  17804. {
  17805. // Possible cause - DTOR with params
  17806. AssertErrorState();
  17807. }
  17808. }
  17809. return true;
  17810. }
  17811. // Generic methods can't be called virtually
  17812. if (methodInstance->GetNumGenericParams() != 0)
  17813. return true;
  17814. // Only public methods can be called virtually
  17815. if (methodDef->mProtection != BfProtection_Public)
  17816. return true;
  17817. UniqueSlotVirtualMethod(methodInstance);
  17818. return true;
  17819. }
  17820. void BfModule::DbgFinish()
  17821. {
  17822. if ((mBfIRBuilder == NULL) || (mExtensionCount != 0))
  17823. return;
  17824. if (mAwaitingInitFinish)
  17825. FinishInit();
  17826. if (mHasForceLinkMarker)
  17827. return;
  17828. String markerName;
  17829. BfIRValue linkMarker;
  17830. if (mBfIRBuilder->DbgHasInfo())
  17831. {
  17832. bool needForceLinking = false;
  17833. for (auto& ownedType : mOwnedTypeInstances)
  17834. {
  17835. bool hasConfirmedReference = false;
  17836. for (auto& methodInstGroup : ownedType->mMethodInstanceGroups)
  17837. {
  17838. if ((methodInstGroup.IsImplemented()) && (methodInstGroup.mDefault != NULL) &&
  17839. (!methodInstGroup.mDefault->mMethodDef->mIsStatic) && (methodInstGroup.mDefault->mIsReified) &&
  17840. ((methodInstGroup.mOnDemandKind == BfMethodOnDemandKind_AlwaysInclude) || (methodInstGroup.mOnDemandKind == BfMethodOnDemandKind_Referenced)))
  17841. {
  17842. hasConfirmedReference = true;
  17843. }
  17844. }
  17845. if ((!hasConfirmedReference) || (ownedType->IsBoxed()))
  17846. needForceLinking = true;
  17847. }
  17848. if ((needForceLinking) && (mProject->mCodeGenOptions.mAsmKind == BfAsmKind_None))
  17849. {
  17850. BfMethodState methodState;
  17851. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  17852. methodState.mTempKind = BfMethodState::TempKind_Static;
  17853. mHasForceLinkMarker = true;
  17854. auto voidType = mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_None));
  17855. SizedArray<BfIRType, 0> paramTypes;
  17856. BfIRFunctionType funcType = mBfIRBuilder->CreateFunctionType(voidType, paramTypes);
  17857. String linkName = "FORCELINKMOD_" + mModuleName;
  17858. BfIRFunction func = mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, linkName);
  17859. mBfIRBuilder->SetActiveFunction(func);
  17860. auto entryBlock = mBfIRBuilder->CreateBlock("main", true);
  17861. mBfIRBuilder->SetInsertPoint(entryBlock);
  17862. auto firstType = mOwnedTypeInstances[0];
  17863. UpdateSrcPos(mContext->mBfObjectType->mTypeDef->GetRefNode());
  17864. SizedArray<BfIRMDNode, 1> diParamTypes;
  17865. diParamTypes.Add(mBfIRBuilder->DbgGetType(GetPrimitiveType(BfTypeCode_None)));
  17866. BfIRMDNode diFuncType = mBfIRBuilder->DbgCreateSubroutineType(diParamTypes);
  17867. auto diScope = mBfIRBuilder->DbgCreateFunction(mDICompileUnit, "FORCELINKMOD", linkName, mCurFilePosition.mFileInstance->mDIFile,
  17868. mCurFilePosition.mCurLine + 1, diFuncType, false, true, mCurFilePosition.mCurLine + 1, 0, false, func);
  17869. methodState.mCurScope->mDIScope = diScope;
  17870. UpdateSrcPos(mContext->mBfObjectType->mTypeDef->GetRefNode(), BfSrcPosFlag_Force);
  17871. SizedArray<BfIRValue, 8> args;
  17872. BfExprEvaluator exprEvaluator(this);
  17873. for (auto& ownedType : mOwnedTypeInstances)
  17874. {
  17875. auto alloca = mBfIRBuilder->CreateAlloca(mBfIRBuilder->MapType(GetPrimitiveType(BfTypeCode_Int8)));
  17876. auto diVariable = mBfIRBuilder->DbgCreateAutoVariable(diScope, "variable", mCurFilePosition.mFileInstance->mDIFile, mCurFilePosition.mCurLine, mBfIRBuilder->DbgGetType(ownedType));
  17877. mBfIRBuilder->DbgInsertDeclare(alloca, diVariable);
  17878. }
  17879. mBfIRBuilder->CreateRetVoid();
  17880. mBfIRBuilder->SetActiveFunction(BfIRFunction());
  17881. }
  17882. }
  17883. }
  17884. bool BfModule::Finish()
  17885. {
  17886. BP_ZONE("BfModule::Finish");
  17887. BfLogSysM("BfModule finish: %p\n", this);
  17888. if (mHadBuildError)
  17889. {
  17890. // Don't AssertErrorState here, this current pass may not have failed but
  17891. // the module was still queued in mFinishedModuleWorkList
  17892. ClearModule();
  17893. return true;
  17894. }
  17895. if (mUsedSlotCount != -1)
  17896. {
  17897. BF_ASSERT(mCompiler->mMaxInterfaceSlots != -1);
  17898. mUsedSlotCount = mCompiler->mMaxInterfaceSlots;
  17899. }
  17900. BF_ASSERT(mAddedToCount);
  17901. mAddedToCount = false;
  17902. mAwaitingFinish = false;
  17903. mCompiler->mStats.mModulesFinished++;
  17904. if (HasCompiledOutput())
  17905. {
  17906. DbgFinish();
  17907. if (mAwaitingInitFinish)
  17908. FinishInit();
  17909. for (auto ownedTypeInst : mOwnedTypeInstances)
  17910. {
  17911. // Generate dbg info and add global variables if we haven't already
  17912. mBfIRBuilder->PopulateType(ownedTypeInst);
  17913. }
  17914. if (mBfIRBuilder->DbgHasInfo())
  17915. {
  17916. mBfIRBuilder->DbgFinalize();
  17917. }
  17918. String objOutputPath;
  17919. String irOutputPath;
  17920. mIsModuleMutable = false;
  17921. //mOutFileNames.Clear();
  17922. BF_ASSERT((int)mOutFileNames.size() >= mExtensionCount);
  17923. bool writeModule = mBfIRBuilder->HasExports();
  17924. String outputPath;
  17925. BfCodeGenOptions codeGenOptions = mProject->mCodeGenOptions;
  17926. auto& compilerOpts = mCompiler->mOptions;
  17927. codeGenOptions.mSIMDSetting = compilerOpts.mSIMDSetting;
  17928. auto moduleOptions = GetModuleOptions();
  17929. codeGenOptions.mOptLevel = moduleOptions.mOptLevel;
  17930. codeGenOptions.mSIMDSetting = moduleOptions.mSIMDSetting;
  17931. codeGenOptions.mWriteLLVMIR = mCompiler->mOptions.mWriteIR;
  17932. codeGenOptions.mWriteObj = mCompiler->mOptions.mGenerateObj;
  17933. codeGenOptions.mWriteBitcode = mCompiler->mOptions.mGenerateBitcode;
  17934. codeGenOptions.mVirtualMethodOfs = 1 + mCompiler->GetDynCastVDataCount() + mCompiler->mMaxInterfaceSlots;
  17935. codeGenOptions.mDynSlotOfs = mSystem->mPtrSize - mCompiler->GetDynCastVDataCount() * 4;
  17936. mCompiler->mStats.mIRBytes += mBfIRBuilder->mStream.GetSize();
  17937. mCompiler->mStats.mConstBytes += mBfIRBuilder->mTempAlloc.GetAllocSize();
  17938. bool allowWriteToLib = true;
  17939. if ((allowWriteToLib) && (codeGenOptions.mOptLevel == BfOptLevel_OgPlus) && (mModuleName != "vdata"))
  17940. {
  17941. codeGenOptions.mWriteToLib = true;
  17942. mWroteToLib = true;
  17943. }
  17944. else
  17945. {
  17946. mWroteToLib = false;
  17947. }
  17948. for (int fileIdx = 0; fileIdx <= mExtensionCount; fileIdx++)
  17949. {
  17950. outputPath = mModuleName;
  17951. outputPath = mCompiler->mOutputDirectory + "/" + mProject->mName + "/" + outputPath;
  17952. BfModuleFileName moduleFileName;
  17953. if (mParentModule != NULL)
  17954. {
  17955. for (auto&& checkPair : mParentModule->mSpecializedMethodModules)
  17956. {
  17957. if (checkPair.mValue == this)
  17958. moduleFileName.mProjects = checkPair.mKey;
  17959. }
  17960. }
  17961. moduleFileName.mProjects.Add(mProject);
  17962. if (fileIdx > 0)
  17963. outputPath += StrFormat("@%d", fileIdx + 1);
  17964. if (mCompiler->mOptions.mWriteIR)
  17965. irOutputPath = outputPath + ".ll";
  17966. if (mCompiler->mOptions.mGenerateObj)
  17967. {
  17968. objOutputPath = outputPath + BF_OBJ_EXT;
  17969. moduleFileName.mFileName = objOutputPath;
  17970. }
  17971. else if (mCompiler->mOptions.mWriteIR)
  17972. {
  17973. moduleFileName.mFileName = irOutputPath;
  17974. }
  17975. else if ((!mCompiler->mOptions.mGenerateObj) && (!mCompiler->mOptions.mGenerateBitcode) && (!mCompiler->mOptions.mWriteIR))
  17976. {
  17977. BF_FATAL("Neither obj nor IR specified");
  17978. }
  17979. moduleFileName.mModuleWritten = writeModule;
  17980. moduleFileName.mWroteToLib = mWroteToLib;
  17981. if (!mOutFileNames.Contains(moduleFileName))
  17982. mOutFileNames.Add(moduleFileName);
  17983. }
  17984. if (mCompiler->IsHotCompile())
  17985. {
  17986. codeGenOptions.mIsHotCompile = true;
  17987. //TODO: Why did we have this 'mWroteToLib' check? 'vdata' didn't get this flag set, which
  17988. // is required for rebuilding vdata after we hot create a vdata
  17989. //if (mWroteToLib)
  17990. {
  17991. if (mParentModule != NULL)
  17992. mParentModule->mHadHotObjectWrites = true;
  17993. mHadHotObjectWrites = true;
  17994. }
  17995. }
  17996. //TODO: Testing VDATA
  17997. /*if (mModuleName == "vdata")
  17998. {
  17999. codeGenOptions.mOptLevel = 4;
  18000. }*/
  18001. codeGenOptions.GenerateHash();
  18002. BP_ZONE("BfModule::Finish.WriteObjectFile");
  18003. if ((writeModule) && (!mBfIRBuilder->mIgnoreWrites))
  18004. mCompiler->mCodeGen.WriteObjectFile(this, outputPath, codeGenOptions);
  18005. mLastModuleWrittenRevision = mCompiler->mRevision;
  18006. }
  18007. else
  18008. {
  18009. for (auto type : mOwnedTypeInstances)
  18010. {
  18011. BF_ASSERT(!type->IsIncomplete());
  18012. }
  18013. }
  18014. for (auto& specModulePair : mSpecializedMethodModules)
  18015. {
  18016. auto specModule = specModulePair.mValue;
  18017. if ((specModule->mIsModuleMutable) && (!specModule->mAwaitingFinish))
  18018. {
  18019. BfLogSysM(" Mutable spec module remaining: %p\n", specModule);
  18020. }
  18021. }
  18022. CleanupFileInstances();
  18023. // We can't ClearModuleData here because we need the mSpecializedMethodModules to remain valid until we Finish them too
  18024. return true;
  18025. }
  18026. void BfModule::ReportMemory(MemReporter* memReporter)
  18027. {
  18028. memReporter->Add(sizeof(BfModule));
  18029. if (mBfIRBuilder != NULL)
  18030. {
  18031. memReporter->BeginSection("IRBuilder_ConstData");
  18032. memReporter->Add("Used", mBfIRBuilder->mTempAlloc.GetAllocSize());
  18033. memReporter->Add("Unused", mBfIRBuilder->mTempAlloc.GetTotalAllocSize() - mBfIRBuilder->mTempAlloc.GetAllocSize());
  18034. memReporter->EndSection();
  18035. memReporter->BeginSection("IRBuilder_BFIR");
  18036. memReporter->Add("Used", (int)(mBfIRBuilder->mStream.GetSize()));
  18037. memReporter->Add("Unused", (int)(mBfIRBuilder->mStream.mPools.size() * ChunkedDataBuffer::ALLOC_SIZE) - mBfIRBuilder->mStream.GetSize());
  18038. memReporter->EndSection();
  18039. memReporter->Add(sizeof(BfIRBuilder));
  18040. }
  18041. memReporter->BeginSection("FileInstanceMap");
  18042. memReporter->AddMap(mFileInstanceMap);
  18043. memReporter->AddMap(mNamedFileInstanceMap);
  18044. memReporter->Add((int)mNamedFileInstanceMap.size() * sizeof(BfFileInstance));
  18045. memReporter->EndSection();
  18046. memReporter->AddVec(mOwnedTypeInstances, false);
  18047. memReporter->AddVec(mSpecializedMethodModules, false);
  18048. memReporter->AddVec(mOutFileNames, false);
  18049. memReporter->AddMap("FuncReferences", mFuncReferences, false);
  18050. memReporter->AddMap(mInterfaceSlotRefs, false);
  18051. memReporter->AddMap(mStaticFieldRefs, false);
  18052. memReporter->AddMap(mClassVDataRefs, false);
  18053. memReporter->AddMap("VDataExtMap", mClassVDataExtRefs, false);
  18054. memReporter->AddMap(mTypeDataRefs, false);
  18055. memReporter->AddMap(mDbgRawAllocDataRefs, false);
  18056. memReporter->AddMap(mDeferredMethodCallData, false);
  18057. memReporter->AddHashSet(mDeferredMethodIds, false);
  18058. memReporter->AddHashSet("ModuleRefs", mModuleRefs, false);
  18059. }
  18060. // ClearModuleData is called immediately after the module is compiled, so don't clear out any data that needs to
  18061. // be transient through the next compile
  18062. void BfModule::ClearModuleData()
  18063. {
  18064. BfLogSysM("ClearModuleData %p\n", this);
  18065. if (mAddedToCount)
  18066. {
  18067. mCompiler->mStats.mModulesFinished++;
  18068. mAddedToCount = false;
  18069. }
  18070. mDICompileUnit = BfIRMDNode();
  18071. mIsModuleMutable = false;
  18072. mIncompleteMethodCount = 0;
  18073. mHasGenericMethods = false;
  18074. // We don't want to clear these because we want it to persist through module extensions-
  18075. // otherwise we may think an extension succeeds even though the base module failed
  18076. //mHadBuildError = false;
  18077. //mHadBuildWarning = false;
  18078. mClassVDataRefs.Clear();
  18079. mClassVDataExtRefs.Clear();
  18080. for (auto& kv : mTypeDataRefs)
  18081. kv.mValue = BfIRValue();
  18082. mStringCharPtrPool.Clear();
  18083. mStringObjectPool.Clear();
  18084. mStaticFieldRefs.Clear();
  18085. BF_ASSERT(!mIgnoreErrors);
  18086. for (auto prevIRBuilder : mPrevIRBuilders)
  18087. delete prevIRBuilder;
  18088. mPrevIRBuilders.Clear();
  18089. for (auto& specPair : mSpecializedMethodModules)
  18090. {
  18091. auto specModule = specPair.mValue;
  18092. specModule->ClearModuleData();
  18093. }
  18094. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  18095. mBuiltInFuncs[i] = BfIRFunction();
  18096. if (mNextAltModule != NULL)
  18097. mNextAltModule->ClearModuleData();
  18098. BfLogSysM("ClearModuleData. Deleting IRBuilder: %p\n", mBfIRBuilder);
  18099. delete mBfIRBuilder;
  18100. mBfIRBuilder = NULL;
  18101. mWantsIRIgnoreWrites = false;
  18102. }
  18103. void BfModule::DisownMethods()
  18104. {
  18105. for (int i = 0; i < BfBuiltInFuncType_Count; i++)
  18106. mBuiltInFuncs[i] = BfIRFunction();
  18107. BfModule* methodModule = this;
  18108. if (mParentModule != NULL)
  18109. methodModule = mParentModule;
  18110. for (auto typeInst : methodModule->mOwnedTypeInstances)
  18111. {
  18112. for (auto& methodGroup : typeInst->mMethodInstanceGroups)
  18113. {
  18114. if (methodGroup.mDefault != NULL)
  18115. {
  18116. if (methodGroup.mDefault->mIRFunction)
  18117. {
  18118. BF_ASSERT(methodGroup.mDefault->mDeclModule != NULL);
  18119. if (methodGroup.mDefault->mDeclModule == this)
  18120. {
  18121. methodGroup.mDefault->mIRFunction = BfIRFunction();
  18122. }
  18123. }
  18124. }
  18125. if (methodGroup.mMethodSpecializationMap != NULL)
  18126. {
  18127. for (auto& mapPair : *methodGroup.mMethodSpecializationMap)
  18128. {
  18129. auto methodInstance = mapPair.mValue;
  18130. if (methodInstance->mDeclModule == this)
  18131. {
  18132. methodInstance->mIRFunction = BfIRFunction();
  18133. }
  18134. }
  18135. }
  18136. }
  18137. }
  18138. }
  18139. void BfModule::ClearModule()
  18140. {
  18141. ClearModuleData();
  18142. DisownMethods();
  18143. for (auto& specPair : mSpecializedMethodModules)
  18144. {
  18145. auto specModule = specPair.mValue;
  18146. specModule->ClearModule();
  18147. }
  18148. if (mNextAltModule != NULL)
  18149. mNextAltModule->ClearModule();
  18150. }